akhauriyash/Code-Regression huggingface dataset:
//TLE
#include <iostream>
#include <algorithm>
#define int long long
using namespace std;

int n, a, b, c, d;
int comb[1001][1001];
int mod = 1000000007;
int dp[1001][1001];

void make_comb() {
	comb[0][0] = 1;
	for (int i = 1; i <= n; i++) {
		comb[i][0] = 1;
		for (int j = 1; j <= i; j++) {
			comb[i][j] = comb[i-1][j-1] + comb[i-1][j];
			comb[i][j] %= mod;
		}
	}
}

//x～b人グループを作る。残りn人いる。何通り？
int dfs(int x, int n) {
	if (x == b + 1) {
		return (n == 0);
	}
	if (dp[x][n] != -1) {
		return dp[x][n];
	}
	
	int ret = dfs(x + 1, n);
	
	for (int i = c; i <= d; i++) {
		if (n - x * i < 0) { break; }
		
		int cnt = comb[n][x * i];
		for (int j = 0; j < i; j++) {
			cnt *= comb[x * (i - j) - 1][x - 1];
			cnt %= mod;
		}
		
		ret += cnt * dfs(x + 1, n - x * i);
		ret %= mod;
	}
	return (dp[x][n] = ret);
}

signed main() {
	cin >> n >> a >> b >> c >> d;
	make_comb();
	for (int i = a; i <= b; i++) { for (int j = 0; j <= n; j++) { dp[i][j] = -1; } }
	
	cout << dfs(a, n) << endl;
	return 0;
}

Measured memory_bytes: 15104
import java.util.Collections;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;


public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		while(true){
			final int N = sc.nextInt();
			
			if(N == 0){
				break;
			}
			
			final int W = sc.nextInt();
			final int H = sc.nextInt();
			
			boolean[][] p_map = new boolean[H][W];
			
			for(int i = 0; i < N; i++){
				final int x = sc.nextInt() - 1;
				final int y = sc.nextInt() - 1;
				
				p_map[y][x] = true;
			}
			
			final int s_x = sc.nextInt();
			final int s_y = sc.nextInt();
			
			int[] c_map = new int[H];
			for(int i = 0; i < s_y; i++){
				for(int j = 0; j < s_x; j++){
					c_map[0] += p_map[i][j] ? 1 : 0;
				}
			}
			
			int max = c_map[0];
			/*
			System.out.println();
			for(int i = 0; i < H; i++){
				for(int j = 0; j < W; j++){
					System.out.print(p_map[i][j] ? "*" : "-");
				}
				System.out.println();
			}
			*/
			for(int i = s_y - 1; i < H; i++){
				if(i != s_y - 1){
					c_map[i - (s_y - 1)] = c_map[i - s_y];
					
					for(int k = 0; k < s_x; k++){
						c_map[i - (s_y - 1)] -= p_map[i-s_y][k] ? 1 : 0;
						c_map[i - (s_y - 1)] += p_map[i][k] ? 1 : 0;
					}
				}
				
				int inner = c_map[i - (s_y - 1)];
				//System.out.println(i + " " + (s_x - 1) + " " + inner);
				max = Math.max(inner, max);
				
				for(int j = s_x; j < W; j++){
					for(int k = i - (s_y - 1); k <= i; k++){
						inner -= p_map[k][j - s_x] ? 1 : 0;
						inner += p_map[k][j] ? 1 : 0;
					}
					
					max = Math.max(inner, max);
					//System.out.println(i + " " + j + " " + inner);
				}
			}
			
			System.out.println(max);
			
		}
		
	}

}

Measured memory_bytes: 12000
a,b=map(int,input().split())
c=[]
for _ in range(a):
    c.append(list(map(int,input().split())))
result=[]
for i in range(a):
    if c[i][1]<=b:
        result.append(c[i][0])
if result==[]:
    print('TLE')
    exit()
print(min(result))

Measured memory_bytes: 9096
import math

def is_prime(n):
    if n == 1: return False

    for k in range(2, int(math.sqrt(n)) + 1):
        if n % k == 0:
            return False

    return True

X = int(input())

while True:
    if is_prime(X):
        print(X)
        break
    else:
        X += 1



Measured memory_bytes: 2940
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <cctype>
#include <algorithm>
using namespace std;
typedef long long lint;
#define cout cerr
#define ni (next_num<int>())
template<class T>inline T next_num(){
	T i=0;char c;
	while(!isdigit(c=getchar())&&c!='-');
	bool flag=c=='-';
	flag?(c=getchar()):0;
	while(i=i*10-'0'+c,isdigit(c=getchar()));
	return flag?-i:i;
}
template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){if(a<b)a=b;}
template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){if(b<a)a=b;}
const int N=200010,INF=0x7f7f7f7f;
const lint LINF=0x7f7f7f7f7f7f7f7f;
int a[N],b[N],lst[N];
inline bool lcmp(int x,int y){
	return a[x]<a[y];
}
int main(){
	int n=ni,mx=1,mn=1,mxcnt;
	for(int i=1;i<=n;i++){
		a[i]=ni,b[i]=ni;
		if(a[i]>b[i]){
			swap(a[i],b[i]);
		}
		if(a[i]<a[mn]){
			mn=i;
		}
		if(b[i]>b[mx]){
			mx=i,mxcnt=1;
		}else if(b[i]==b[mx]){
			mxcnt++;
		}
		lst[i]=i;
	}
	lint ans;
	{
		int lmx=mn,rmn=mx;
		for(int i=1;i<=n;i++){
			if(a[i]>a[lmx]){
				lmx=i;
			}
			if(b[i]<b[rmn]){
				rmn=i;
			}
		}
		ans=(lint)(a[lmx]-a[mn])*(b[mx]-b[rmn]);
	}
	if(mn!=mx){
		sort(lst+1,lst+n+1,lcmp);
		int rmn=INF,rmx=0,cans=INF;
		for(int i=1;;i++){
			int x=lst[i];
			if(b[x]==b[mx]&&--mxcnt==0){
				break;
			}
			assert(i<n);
			apmin(rmn,b[x]);
			apmax(rmx,b[x]);
			apmin(cans,max(rmx,a[lst[n]])-min(rmn,a[lst[i+1]]));
		}
		apmin(ans,(lint)(b[mx]-a[mn])*cans);
	}
	printf("%lld\n",ans);
	return 0;
}

Measured memory_bytes: 2560
n,m,q=map(int,input().split())
A=[]
i=1
m+=1
while i<m:
    for a in range(i,m):
        if n==2:
            A.append([i,a])
        else:
            for b in range(a,m):
                if n==3:
                    A.append([i,a,b])
                else:
                    for c in range(b,m):
                        if n==4:
                            A.append([i,a,b,c])
                        else:
                            for d in range(c,m):
                                if n==5:
                                    A.append([i,a,b,c,d])
                                else:
                                    for e in range(d,m):
                                        if n==6:
                                            A.append([i,a,b,c,d,e])
                                        else:
                                            for f in range(e,m):
                                                if n==7:
                                                    A.append([i,a,b,c,d,e,f])
                                                else:
                                                    for g in range(f,m):
                                                        if n==8:
                                                            A.append([i,a,b,c,d,e,f,g])
                                                        else:
                                                            for h in range(g,m):
                                                                if n==9:
                                                                    A.append([i,a,b,c,d,e,f,g,h])
                                                                else:
                                                                    for j in range(h,m):
                                                                        A.append([i,a,b,c,d,e,f,g,h,j])
    i+=1
length=len(A)
if length==0:
    print(0)
else:
    l=[]
    ans=0
    for i in range(q):
        l.append(list(map(int,input().split())))
    for tmpA in A:
        tmp=0
        for tmpQ in l:
            if tmpA[tmpQ[1]-1]-tmpA[tmpQ[0]-1]==tmpQ[2]:
                tmp+=tmpQ[3]
        ans=max(tmp,ans)
    print(ans)

Measured memory_bytes: 22920
#include <iostream>
#include <utility>
#include <map>
#include <vector>
#include <algorithm>
#include <queue>
#include <math.h>
#include <stack>
#include <set>
#include <deque>
#include <cmath>
#include <cassert>

using namespace std;
typedef long long ll;
ll mod = 1e9+7;
#define rep(i,n) for(int i = 0; i < (n); ++i)

int main() {
    int n, m;
    cin >> n >> m;
    int ans = 0;  
    int num = 1;
    rep(i, m) {
        num *= 2;
    }
    ans += (1900 * m + (n-m) * 100) * num;
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 3624
#include <iostream>
#include <vector>
using namespace std;

#define LOOP(a,b,c) for(a=b;a<=c;a++)
#define ll long long

int main() {
    int n,i,j,k;
    ll temp,ans=0;
    cin>>n;
    vector<ll> a(n);
    LOOP(i,0,n-1){
        cin>>a[i];
    }
    LOOP(i,0,n-1){
        temp=a[i];
        while(temp%2==0){
            temp/=2;
            ans++;
        }
    }
    cout << ans << endl;

    return 0;
}

Measured memory_bytes: 384
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define FOR(i,n,m) for(int i=(n);i<(m);i++)
#define REP(i,n) FOR(i,0,n)
#define REPR(i,n) for(int i=(n);i>=0;i--)
#define all(vec) vec.begin(),vec.end()
using vi=vector<int>;
using vvi=vector<vi>;
using vl=vector<ll>;
using vvl=vector<vl>;
using P=pair<ll,ll>;
using PP=pair<ll,P>;
using vp=vector<P>;
using vpp=vector<PP>;
using vs=vector<string>;
#define fi first
#define se second
#define pb push_back
template<class T>bool chmax(T &a,const T &b){if(a<b){a=b;return true;}return false;}
template<class T>bool chmin(T &a,const T &b){if(a>b){a=b;return true;}return false;}
const ll MOD=1000000007LL;
const int INF=1<<30;
const ll LINF=1LL<<60;
int main(){
    string st;
    cin>>st;
    if(st[0]!='A'){
        cout<<"WA"<<endl;
        return 0;
    }
    int cnt=0;
    FOR(i,2,st.size()-1){
        if(st[i]=='C'){
            cnt++;
        }
    }
    if(cnt!=1){
        cout<<"WA"<<endl;
        return 0;
    }
    int t=0;
    REP(i,st.size()){
        if('A'<=st[i]&&st[i]<='Z'){
            t++;
        }
    }
    if(t!=2){
        cout<<"WA"<<endl;
    }else{
        cout<<"AC"<<endl;
    }
    return 0;
}

Measured memory_bytes: 256
#ifndef _TEMPLATE_ROOT
#define _TEMPLATE_ROOT
#include "bits/stdc++.h"
using namespace std;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define repl(i, a, b) for(ll i = a; i < (b); ++i)
#define repd(i, a, b) for(int i = a; i >= (b); --i)
#define repdl(i, a, b) for(ll i = a; i >= (b); --i)
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
template<typename H> bool chmin(H& v1, const H v2) { if (v1 > v2) { v1 = v2; return true; } return false; }
template<typename H> bool chmax(H& v1, const H v2) { if (v1 < v2) { v1 = v2; return true; } return false; }
#endif
#ifndef _TEMPLATE_IO
#define _TEMPLATE_IO

template<typename H> void read(H& head) { cin >> head; }
template<typename H, typename ...T> void read(H& head, T& ...tail) { cin >> head; read(tail...); }
template<typename H> void write(H head) { cout << head << '\n'; }
template<typename H, typename ...T> void write(H head, T ...tail) { cout << head << " "; write(tail...); }
template<typename ...T> void writef(T ...tail) { write(tail...); cout << flush; }
template<typename ...T> void die(T ...tok) { write(tok...); exit(0); }
template<typename T>
ostream& operator<<(ostream& out, const vector<T>& v) {
  if (v.size()) {
    rep(i, 0, sz(v) - 1)
      out << v[i] << " ";
    out << v.back();
  }
  return out;
}
#endif
using namespace std;

ll l[105];

int main() {
	cin.tie(0)->sync_with_stdio(0);
	cin.exceptions(cin.failbit);

  int ans = 0;
  int n; read(n);
  rep(i, 0, n) read(l[i]);
  rep(i, 0, n) rep(j, i + 1, n) rep(k, j + 1, n) {
    if (l[i] != l[j] && l[i] != l[k] && l[j] != l[k] &&
          l[i] + l[j] > l[k] && l[i] + l[k] > l[j] && l[j] + l[k] > l[i]) ans++;
  }
  write(ans);
}



Measured memory_bytes: 3628
#include<bits/stdc++.h>

using namespace std;

using int64 = long long;
const int mod = 1e9 + 7;
// const int mod = 998244353;

const int64 infll = (1LL << 62) - 1;
const int inf = (1 << 30) - 1;

struct IoSetup {
  IoSetup() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(10);
    cerr << fixed << setprecision(10);
  }
} iosetup;


template< typename T1, typename T2 >
ostream &operator<<(ostream &os, const pair< T1, T2 > &p) {
  os << p.first << " " << p.second;
  return os;
}

template< typename T1, typename T2 >
istream &operator>>(istream &is, pair< T1, T2 > &p) {
  is >> p.first >> p.second;
  return is;
}

template< typename T >
ostream &operator<<(ostream &os, const vector< T > &v) {
  for(int i = 0; i < (int) v.size(); i++) {
    os << v[i] << (i + 1 != v.size() ? " " : "");
  }
  return os;
}

template< typename T >
istream &operator>>(istream &is, vector< T > &v) {
  for(T &in : v) is >> in;
  return is;
}

template< typename T1, typename T2 >
inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }

template< typename T1, typename T2 >
inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); }

template< typename T = int64 >
vector< T > make_v(size_t a) {
  return vector< T >(a);
}

template< typename T, typename... Ts >
auto make_v(size_t a, Ts... ts) {
  return vector< decltype(make_v< T >(ts...)) >(a, make_v< T >(ts...));
}

template< typename T, typename V >
typename enable_if< is_class< T >::value == 0 >::type fill_v(T &t, const V &v) {
  t = v;
}

template< typename T, typename V >
typename enable_if< is_class< T >::value != 0 >::type fill_v(T &t, const V &v) {
  for(auto &e : t) fill_v(e, v);
}

template< typename F >
struct FixPoint : F {
  FixPoint(F &&f) : F(forward< F >(f)) {}

  template< typename... Args >
  decltype(auto) operator()(Args &&... args) const {
    return F::operator()(*this, forward< Args >(args)...);
  }
};

template< typename F >
inline decltype(auto) MFP(F &&f) {
  return FixPoint< F >{forward< F >(f)};
}

int main() {
  int X;
  cin >> X;
  int add = X / 500;
  X -= add * 500;
  add *= 1000;
  cout << add + X / 5 * 5 << endl;
}






Measured memory_bytes: 256
from collections import Counter

# Initializing variables
intNums = int(input())
intList = list(map(int, input().split()))
c = max(Counter(intList).values())

# Calculating if the input is pairwise distinct or not
if c > 1:
    print('NO')
else:
    print('YES')

# Check out my Youtube channel! https://www.youtube.com/channel/UCMOKVyAbTZOpKikTrX5dy_A


Measured memory_bytes: 33996
#include <bits/stdc++.h>
#define rep(i,n) for (int i=0; i<(int)(n); i++)
#define REP(i,m,n) for(ll i=(ll)(m);i<(ll)(n);i++)
using namespace std;
using ll = long long;
using P = pair<int, int>;

ll gcd(ll a, ll b) {
  if (a % b == 0) return b;
  else return gcd(b, a%b);
}

ll lcm(ll a, ll b) {
  ll d = gcd(a, b);
  return a * b / gcd(a, b);
}

int main() {
  ll a, b; cin >> a >> b;
  ll c, d; cin >> c >> d;
  a--;
  // a~bにおける
  // c の倍数の個数
  ll cn = (b / c - a / c);
  // d の倍数の個数
  ll dn = (b / d - a / d);
  // c,d の公倍数の個数
  ll cdn = (b / lcm(c,d) - a / lcm(c,d));
  ll ans = (b - a) - (cn + dn - cdn);
  cout << ans << endl;

  return 0;
}

Measured memory_bytes: 3640
deg = [0 for _ in range(4)]
for _ in range(3):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    # 0-indexed
    deg[a] += 1
    deg[b] += 1

print('NO' if list(filter(lambda x: x == 3, deg)) else 'YES')

Measured memory_bytes: 3060
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main {
    static PrintWriter out;

    public static void main(String[] args) throws IOException {
        out = new PrintWriter(new OutputStreamWriter(System.out));
        CF_Reader in = new CF_Reader();

        String word = in.next();
        out.println((word.equals("ABC") ? "ARC" : "ABC"));

        out.close();
    }

    static class CF_Reader {
        BufferedReader br;
        StringTokenizer st;

        public CF_Reader() throws IOException {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() throws IOException {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine().trim());
            return st.nextToken();
        }

        long longNext() throws IOException {
            return Long.parseLong(next());
        }

        int intNext() throws IOException {
            return Integer.parseInt(next());
        }

        double doubleNext() throws IOException {
            return Double.parseDouble(next());
        }

        char charNext() throws IOException {
            return next().charAt(0);
        }

        public int[] nextIntArray(final int n) throws IOException {
            final int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = intNext();
            return a;
        }

        public long[] nextLongArray(final int n) throws IOException {
            final long[] a = new long[n];
            for (int i = 0; i < n; i++)
                a[i] = longNext();
            return a;
        }

        String line() throws IOException {
            return br.readLine().trim();
        }
    }
}


Measured memory_bytes: 32652
c = [list(map(int, input().split())) for _ in range(3)]

flag = True

for i in range(1, 3):
    if not(c[i][0] - c[0][0] == c[i][1] - c[0][1] == c[i][2] - c[0][2]):
        flag = False
    if not(c[0][i] - c[0][0] == c[1][i] - c[1][0] == c[2][i] - c[2][0]):
        flag = False

if flag:
    print("Yes")
else:
    print("No")


Measured memory_bytes: 9108
#include <bits/stdc++.h>
using namespace std;

int main(){
    long long r,d,s;cin>>r>>d>>s;vector<long long> x(11);x.at(0)=s;
    for(int i=0;i<10;i++){
        x.at(i+1)=r*x.at(i)-d;
        cout<<x.at(i+1)<<endl;
    }
}

Measured memory_bytes: 256
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>

using namespace std;

int a[100005];
vector<int>vec;


int main() {

	int n;

	scanf("%d",&n);

	int i;

	int ai=-1;

	for(i=0;i<n;i++){
		scanf(" %d",&a[i]);
		if(ai<a[i]){ai=a[i];}
		vec.push_back(a[i]);
	}

	sort(vec.begin(),vec.end());

	if(ai%2==0){

		int index=0;
		int diff=1000000005;

		for(i=0;i<n;i++){
			if(diff>max((ai/2)-vec[i],vec[i]-(ai/2))){
				diff=max((ai/2)-vec[i],vec[i]-(ai/2));
				index=i;
			}
		}
		printf("%d %d\n",ai,vec[index]);
	}
	else{

		int index=0;
		int diff=1000000005;

		for(i=0;i<n;i++){
			if(diff>max((ai/2)-vec[i],vec[i]-(ai/2))){
				diff=max((ai/2)-vec[i],vec[i]-(ai/2));
				index=i;
			}
		}

		for(i=0;i<n;i++){
			if(diff>max((ai/2)+1-vec[i],vec[i]-(ai/2)-1)){
				diff=max((ai/2)+1-vec[i],vec[i]-(ai/2)-1);
				index=i;
			}
		}

		printf("%d %d\n",ai,vec[index]);
	}

	return 0;
}

Measured memory_bytes: 1276
H, W = map(int, input().split())
if H % 3 == 0 or W % 3 == 0:
    print(0)
    exit()
ans = H * W
for i in range(2):
    for h in range(1, H):
        s = [h * W, W // 2 * (H - h), (W - W // 2) * (H - h)]
        s2 = [h * W, (H - h) // 2 * W, ((H - h) - (H - h) // 2) * W]
        ans = min(ans, min(max(s) - min(s), max(s2) - min(s2)))
    H, W = W, H
print(ans)


Measured memory_bytes: 3064
#include <bits/stdc++.h>
#define SpeeD ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define ll long long
#define endl '\n'
//pair<int, int> *p=new pair<int, int>[n];
//std::vector<pair<int,int>> vp;
//v.push_back(make_pair(x,y))
//pair<int, int> p[1000001];
//string *s=new string [n];
//int freq[e];
//freq[a[i]-'a']++; freq[a[i]]++;
using namespace std;
ll n, t, m, c1, c2, c, x, y, sum, mn = 999999999, avg, pos, dif, dis,k, mx, q;
const int MXN=1e5+1;
bool prime[MXN];
const int md=1e9+7;
ll dp [MXN];
ll pre[MXN];

bool PE ( ll x )
{
    for ( ll i = 2; i * i <= x; i+=1+(i&1))
    if ( x % i == 0 )
    return false;
    return true;
}

void sieve()
{
    memset(prime , 1 , sizeof prime);

    for ( ll i = 2; i * i <= MXN; i+=1+(i&1))
    if (prime[i])
    {
          for (ll j = i * i; j < MXN; j +=i)
         prime[j] = false;
    }
}

bool PR ( string s )
{
    int n = s.length();
    for ( ll i = 0; i < n / 2; i++ )
    if ( s[i] != s[n - i - 1] )
    return false;
    return true;
}


int main (void){
    SpeeD;
    
cin >> n >> m;
cin >> x >> y;
cin >> t;

if  (m<=y)
        cout<<"NO";
    else{
        dif=abs(n-x);
        if (dif/(long double)(m-y)<=t)
            cout<<"YES";
        else
            cout<<"NO";
    }
    
    
    
}



Measured memory_bytes: 3660
class UnionFind():
  def __init__(self, n):
    self.n = n
    self.parents = [-1] * n

  def find(self, x):
    if self.parents[x] < 0:
      return x
    else:
      self.parents[x] = self.find(self.parents[x])
      return self.parents[x]

  def union(self, x, y):
    x = self.find(x)
    y = self.find(y)
    if x == y:
      return
    if self.parents[x] > self.parents[y]:
      x, y = y, x
    self.parents[x] += self.parents[y]
    self.parents[y] = x

  def size(self, x):
    return -self.parents[self.find(x)]

  def same(self, x, y):
    return self.find(x) == self.find(y)

  def members(self, x):
    root = self.find(x)
    return [i for i in range(self.n) if self.find(i) == root]

  def roots(self):
    return [i for i, x in enumerate(self.parents) if x < 0]

  def group_count(self):
    return len(self.roots())

  def all_group_members(self):
    return {r: self.members(r) for r in self.roots()}

  def __str__(self):
    return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

N, M = map(int, input().split())
P = list(map(int, input().split()))

uf = UnionFind(N)

for _ in range(M):
  x, y = map(lambda x: int(x)-1, input().split())
  uf.union(x, y)

ans = 0

for i, p in enumerate(P):
  if uf.same(i, p-1):
    ans += 1

print(ans)

Measured memory_bytes: 84840
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <stack>
#include <string>
#include <cstring>
#include <queue>
#include <map>
#include <set>
#include <cmath>
#include <climits>

using namespace std;

const int N = 3e5 + 5000;
int n, m, T, a[N], ans;

int main()
{
#ifdef ONLINE_JUDGE
#else
   // freopen("r.txt", "r", stdin);
#endif
    ios::sync_with_stdio(false);

    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    ans = INT_MAX;
    for (int i = 0; i <= 101; i++)
    {
        int now = 0;
        for (int j = 1; j <= n; j++)
            now += (a[j] - i) * (a[j] - i);
        ans = min(ans, now);
    }
    cout << ans;
}

Measured memory_bytes: 256
//   _/                _/                 _/_/_/   _/
//_/_/_/_/   _/_/   _/_/_/_/   _/_/    _/       _/_/
// _/     _/    _/   _/     _/    _/  _/_/_/     _/
//_/     _/    _/   _/     _/    _/  _/    _/   _/
// _/_/   _/_/       _/_/   _/_/      _/_/     _/
#include<iostream>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<set>
#include<map>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
const int MOD=1e9+7;
const double pi=3.14159265358979323846;
const int inf=2e9;
const ll INF=9e18;
typedef pair<int,int> P;
int main() {
  cin.tie(0),cout.tie(0);
  ios::sync_with_stdio(false);
  ll x,y,z,k,a[1005]={},b[1005]={},c[1005]={};
  cin >> x >> y >> z >> k;
  for(int i=0; i<x; i++) {
    cin >> a[i];
  }
  for(int i=0; i<y; i++) {
    cin >> b[i];
  }
  for(int i=0; i<z; i++) {
    cin >> c[i];
  }
  sort(a,a+x,greater<ll>());
  sort(b,b+y,greater<ll>());
  sort(c,c+z,greater<ll>());
  vector<ll> v;
  for(int i=0; i<x; i++) {
    for(int j=0; j<y; j++) {
      for(int l=0; l<z; l++) {
        if((i+1)*(j+1)*(l+1)<=k) {
          v.push_back(a[i]+b[j]+c[l]);
        }
      }
    }
  }
  sort(v.begin(),v.end(),greater<ll>());
  for(int i=0; i<k; i++) {
    cout << v[i] << endl;
  }
}

Measured memory_bytes: 1400
#include<cstdio>

using namespace std;

int main(){
	int sq[18];
	for(int i=1;i<18;i++)	sq[i]=i*i;

	int memo[301][18];
	memo[0][0]=1;
	for(int i=1;i<=300;i++){
		for(int j=1;j<18;j++){
			memo[i][j]=0;
			for(int k=1;k*sq[j]<=i;k++){
				int rem=i-k*sq[j];
				for(int l=0;l<j;l++)	memo[i][j]+=memo[rem][l];
			}
		}
	}

	for(int p;scanf("%d",&p),p;){
		int cnt=0;
		for(int i=0;i<18;i++)	cnt+=memo[p][i];
		printf("%d\n",cnt);
	}

	return 0;
}

Measured memory_bytes: 0
def gu(s):
    l = len(s)
    if l%2 != 0:
        return 0
    else:
        ct = 0
        for i in range(l//2):
            if s[i] == s[i+(l//2)]:
                ct += 1
        if ct == (l/2):
            return 1
        else:
            return 0 





s = input()

for i in range(1,len(s)):
    s = s[:-1]
    if gu(s) == 1:
        break

print(len(s))




Measured memory_bytes: 3060
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0; i<n; i++)
#define REP(i,m,n) for(ll i=(ll)(m);i<(ll)(n);i++)
long long mo = 1e9 + 7;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> Pii;
typedef pair<ll,ll> Pll;
template<class T, class S> void cmin(T &a, const S &b) { if (a > b)a = b; }
template<class T, class S> void cmax(T &a, const S &b) { if (a < b)a = b; }
template<class A>void PR(A a,ll n){rep(i,n){if(i)cout<<' ';cout<<a[i];}cout << "\n";}
ld PI=3.14159265358979323846;

int main(){
    ll N;
    cin >> N;
    vector<string> S(N);
    rep(i,N){
        cin >> S[i];
    }
    ll ans = 0;
    rep(i,N){
        bool flag = true;
        rep(h,N){
            rotate(S[h].begin(),S[h].begin()+1,S[h].end());
        }
        rep(h,N){
            rep(w,N){
                if(h == w) continue;
                if(S[h][w] != S[w][h]){
                    //cout << i <<" "<< S[h][(i+w)%N] << " " << S[(i+w)%N][h] << endl;
                    flag = false;
                    break;
                }
            }
            if(!flag)break;
        }
        if(flag) ans += N;
    }
    cout << ans << endl;
}

Measured memory_bytes: 3784
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Text;


class Program
{
    static void Main(string[] args)
    {
        // 入力
        var k = int.Parse(Console.ReadLine());
        var s = Console.ReadLine();
        //int[] n = Console.ReadLine().Split().Select(int.Parse).ToArray();

        var tmp = "...";
        var ans = "";
        if (s.Length > k)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < k; i++)
            {
                sb.Append(s[i].ToString());
            }
            sb.Append(tmp);
            ans = sb.ToString();
        }
        else
        {
            ans = s;
        }

        // 出力
        Console.WriteLine(ans);
    }
}

Measured memory_bytes: 27544
using System;

public class Hello
{
    public static void Main()
    {
        var s = Console.ReadLine().Trim();
        var s2 = s.Replace("1", "a");
        var s3 = s2.Replace("9", "1");
        var s4 = s3.Replace("a", "9");
        Console.WriteLine(s4);
    }
}


Measured memory_bytes: 11092
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <cmath>
#include <numeric>
#include <iomanip>
#include <stack>
#include <complex>
#include <functional>
#include <tuple>

using namespace std;

#define Rep(i,a,b) for(ll i = a; i < b; ++i)
#define rep(i,b) Rep(i,0,b)
#define allof(a) (a).begin(), (a).end()

#define Yes(q) ((q) ? "Yes" : "No")
#define YES(q) ((q) ? "YES" : "NO")
#define Possible(q) ((q) ? "Possible" : "Impossible")
#define POSSIBLE(q) ((q) ? "POSSIBLE" : "IMPOSSIBLE")

using ll = long long;

constexpr int inf = 1e9 + 7;
constexpr ll infll = 1ll << 60ll;
constexpr ll mod = 1e9 + 7;
// 0~3までは右下左上 4~7までは斜め
constexpr int dx[] = { 1, 0, -1, 0, 1, -1 };
constexpr int dy[] = { 0, 1, 0, -1, 1, 1 };

namespace {
    template<typename T> bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
    template<typename T> bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }

    void Cout(long long x, const char* end = "\n") { std::cout << x << end; }
    template <typename T> void Cout(const T& x, const char* end = "\n") { std::cout << x << end; }
    template <typename T> void Cout(const std::vector<T>& x, const char* sep = " ", const char* end = "\n") { for (std::size_t i = 0, sz = x.size(); i < sz; ++i) { std::cout << x[i] << (i == sz - 1 ? end : sep); } }

    // 標準入出力
    struct inp {
        std::size_t szi, szj;
        inp(std::size_t _szi = 1, std::size_t _szj = 1) : szi(_szi), szj(_szj) {}
        template <typename T> operator T () const { T a; std::cin >> a; return a; }
        template <typename T> operator std::vector<T>() const { std::vector<T> a(szi); for (std::size_t i = 0; i < szi; ++i) std::cin >> a[i]; return a; }
        template <typename T> operator std::vector<std::vector<T>>() const {
            std::vector<std::vector<T>> a(szi, std::vector<T>(szj));
            for (std::size_t i = 0; i < szi; ++i) for (std::size_t j = 0; j < szj; ++j) cin >> a[i][j]; return a;
        }
    };
    inp inp1;

    ll pow(ll a, ll n) {
        ll result = 1;
        ll base = a;
        ll mask = 1;
        while (mask <= n) {
            if (n & mask) result *= base;
            mask <<= 1;
            base *= base;
        }
        return result;
    }
}

int main() {

    ll n = inp1;

    ll sum = 0LL;

    ll len = 0LL;

    ll base = 1LL;
    int cnt = 0;

    while (true) {
        base *= 26;
        if (sum + base >= n) {
            len = cnt + 1;
            break;
        }
        sum += base;
        ++cnt;
    }

    ll num = n - sum - 1;

    // len文字の下からnum番目を出力
    string ans = "";
    rep(i, len) ans += 'a';
    
    // 下から

    for (int i = len - 1; i >= 0; --i) {
        ll base = pow(26, i);
        if (num >= base) {
            int add = num / base;
            num -= add * base;
            ans[i] = (char)(ans[i] + add);
        }
    }

    reverse(allof(ans));
    Cout(ans);

    return 0;
}


Measured memory_bytes: 4100
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>	// upper_bound(A, A+N, num), lower_bound(A, A+N, num)
#include <functional>
#include <string>
#include <sstream>
#include <complex>
#include <vector>		// V[i],  push_back(x), pop_back(), insert(index, x), erase(index), sort(v.begin(), v.end(), greater<int>())
#include <list>			// push_front(x), push_back(x), pop_front(), pop_back(), insert(index, x)
#include <queue>		// push(x), front(), pop()
#include <deque>
#include <stack>		// push(x), top(), pop()
#include <map>			// M[key],  insert(key, val), erase(key), find(key), 
#include <set>			// insert(key), erase(key), find(key)

using namespace std;
typedef long long ll;
// typedef pair<int, int> P;

#define PI 3.141592653589793)
#define MOD 1000000007
#define REP(i, n) for(int i = 0; i < n; i++)

const int INF = 100000000;
int d[201][201];

int N, M, R;
int r[10];
bool used[8];
int res = 1000000000;

void dfs(int c, int las, int dist) {
	if (c == R) {
		res = min(res, dist);
		return;
	}
	for (int i = 0; i < R; i++) {
		if (!used[i]) {
			used[i] = true;
			if (las == -1) dfs(c + 1, i, 0);
			else dfs(c + 1, i, dist + d[r[las]][r[i]]);
			used[i] = false;
		}
	}
}

void solve() {
	cin >> N >> M >> R;
	N, M, R;
	for (int i = 0; i < R; i++) {
		cin >> r[i];
		r[i]--;
	}

	for (int i = 0; i < N; i++) {
		for (int j = 0; j < N; j++) {
			d[i][j] = INF;
			if (i == j) d[i][j] = 0;
		}
	}

	for (int i = 0; i < M; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		a--, b--;
		d[a][b] = d[b][a] = c;
	}

	for (int k = 0; k < N; k++)
		for (int i = 0; i < N; i++)
			for (int j = 0; j < N; j++)
				d[i][j] = min(d[i][j], d[i][k] + d[k][j]);

	dfs(0, -1, 0);
	cout << res << endl;
}

int main() {
	solve();
	return 0;
}

Measured memory_bytes: 384
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int N, T, A, h, ans;
    cin >> N >> T >> A;
    double diff_min = 1e6;
    for ( int i = 0; i < N; i++ ) {
        cin >> h;
        double diff = abs(T - (h * 0.006) - A);
        if ( diff_min > diff ) {
            diff_min = diff;
            ans = i+1;
        }
    }
    cout << ans << '\n';
    return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <iomanip>
#include <ios> 
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
#include <queue>
#include <stack>
#include <set>
#include <cmath>
#include <bitset>
#include <map>
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define rep1(i,n) for(int i=1;i<=(int)(n);i++)

using namespace std;
typedef long long int lli;
//const int MAX=;
const int INF=1e9;

int main(){
	int D,G;
	cin>>D>>G;
	G/=100;
	int p[10], c[10];
	//p[i]はD-i点のものの個数に
	//c[i]はD-i点のボーナスに
	rep(j,D){
		cin>>p[D-1-j]>>c[D-1-j];
		c[D-1-j]/=100;
	}
	int ans=INF;
	//i桁目がD-i点
	//1ならコンプリート
	for(int a=0;a<(1<<D);++a){
      	//一時的な問題数
      	//q[i]はD-i点のものの個数
		int q[10];
		rep(j,D)q[j]=p[j];
		int prob=0;
		int pt=0;
      	//全部取るものの処理。取らないのは1減らしておく。
		rep(i,D){
			if(a&(1<<i)){
				pt+=q[i]*(D-i)+c[i];
				prob+=q[i];
				q[i]=0;
			}
			else q[i]--;
		}
		if(pt>=G){
			ans=min(prob,ans);
//          	cout<<ans<<endl;
			continue;
		}
		bool ac=false;
		rep(i,D){
			if(a&(1<<i))continue;
			else{
				if(pt+(D-i)*q[i]>=G){
					ac=true;
					int z;
					if((G-pt)%(D-i)==0)z=(G-pt)/(D-i);
					else z=1+(G-pt)/(D-i);
					prob+=z;
					break;
				}
				else{
					prob+=q[i];
					pt+=(D-i)*q[i];
				}
			}
		}
		if(ac)ans=min(prob,ans);
//      	cout<<ans;
	}
	cout<<ans;
}

Measured memory_bytes: 256
import math
def py():
    print("Yes")
def pn():
    print("No")
def iin():
    x = int(input())
    return x

neko = 0
nya = 0
nuko = 0
a,b,c,k = map(int,input().split())
if k>a:
    neko = a
    if k > a + b:
        nya = a + b - k
else:
    neko = k
neko = neko + nya
print(neko)

Measured memory_bytes: 9196
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

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

  int n,x=0,res=0;cin>>n;
  string s;cin>>s;
  for(int i=0;i<n;i++){
      if(s[i]=='I'){
          x++;res=max(res,x);
      }
      else x--;
  }
  cout<<res<<endl;
}


Measured memory_bytes: 256
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
const int maxn = 2e5 + 5;
map<int,int>mp;
int vis[maxn];
int main(){
	int n,a[maxn];
	cin >> n;
	mp.clear();
	for(int i = 1;i <= n;i++){
		cin >> a[i];
		mp[a[i]]++;
	}
	long long sum = 0;
	for(int i = 1;i <= n;i++){
		if(!vis[a[i]]){
			for(int j = mp[a[i]] - 1;j >= 1;j--)
				sum += j;
			vis[a[i]] = 1;
		}
	}
	for(int i = 1;i <= n;i++)
		printf("%lld\n",sum - mp[a[i]] + 1);
	return 0;
}

Measured memory_bytes: 9088
#include<bits/stdc++.h>
using namespace std;

int N, M;

int main () {
  int total = 0;
  cin >> N;
  vector<int> T(N);
  for (int i = 0; i < N; i++){
    cin >> T[i];
    total += T[i];
  }
  
  cin >> M;
  vector<int> P(M);
  vector<int> X(M);
  
  for (int i = 0; i < M; i++){
    cin >> P[i] >> X[i];
  }
  for (int i = 0; i < M; i++){
    cout << total - (T[P[i]-1] - X[i]) << endl;
  }
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int (i)=(0);(i)<(int)(n);++(i))
typedef pair<int, int> P;
typedef long long ll;

int N, K, a[5010];

bool check(int x) {
    bitset<5010> bit;
    bit[0] = 1;
    rep(i, N) if (i!=x) bit |= (bit<<a[i]);
    for (int i=max(K-a[x],0); i<K; ++i) if (bit[i]) return true;
    return false;
}

int main() {
    cin >> N >> K;
    rep(i, N) cin >> a[i];
    sort(a, a+N);
    int l=0, r=N;
    while(l<r) {
        int m=(l+r)/2;
        if (check(m)) r=m;
        else l=m+1;
    }
    cout << l << endl;
    return 0;
}


Measured memory_bytes: 256
import java.util.*;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n, m;
		List<Integer> array = new ArrayList<Integer>(20000);
		
		n = sc.nextInt();
		m = sc.nextInt();
		
		while(!(n == 0 && m == 0)) {
			array.clear();
			for(int i = 0; i < n + m; i++) {
				array.add(sc.nextInt());
			}
			Collections.sort(array, Comparator.naturalOrder());
			
			int interval = 0;
			int nt = 0;
			
			for(int time : array) {
				if (time - nt > interval) {
					interval = time - nt;
				}
				nt = time;
			}
				
			System.out.println(interval);

			n = sc.nextInt();
			m = sc.nextInt();
		}
		
	}
}

Measured memory_bytes: 67156
#include <stdio.h>

#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>

using namespace std;

void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char *x) { cerr << '\"' << x << '\"'; }
void __print(const string &x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }

template <typename T, typename V>
void __print(const pair<T, V> &x) {
    cerr << '{';
    __print(x.first);
    cerr << ',';
    __print(x.second);
    cerr << '}';
}
template <typename T>
void __print(const T &x) {
    int f = 0;
    cerr << '{';
    for (auto &i : x) cerr << (f++ ? "," : ""), __print(i);
    cerr << "}";
}
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) {
    __print(t);
    if (sizeof...(v)) cerr << ", ";
    _print(v...);
}
#ifdef LOCAL
#define debug(x...)               \
    cerr << "[" << #x << "] = ["; \
    _print(x)
#else
#define debug(x...)
#endif

#define UNIQUE(v) v.erase(unique(v.begin(), v.end()), v.end());
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define FOR(i, a, b) for (int i = (a); i < (b); i++)

typedef long long ll;

int f(ll x, ll r, ll D){
    return r*x - D;
}


int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    ll r, D, x;
    cin >> r >> D >> x;

    REP(i, 10){
        x = f(x, r, D);
        cout << x << endl;
    }

    return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>

const int max_N = (int)1e6 + 21;

const int mod = (int)1e9 + 7;

int n, fac[max_N], _fac[max_N], inv[max_N], f[max_N];

int main(){
	scanf("%d", &n);
	
	if(n==1) return puts("1"), 0;
	
	inv[1] = 1;
	for(int i=2;i<=n;++i){
		inv[i] = 1ll*(mod/i)*inv[mod%i]%mod;
		if(inv[i]) inv[i] = mod-inv[i];
	}
	
	fac[0] = _fac[0] = 1;
	for(int i=1;i<=n;++i){
		fac[i] = 1ll*fac[i-1]*i%mod;
		_fac[i] = 1ll*_fac[i-1]*inv[i]%mod;
	}
	
	auto binom = [](int n, int m){
		if(n < m) return 0;
		return int(1ll*fac[n]*_fac[m]%mod*_fac[n-m]%mod);	
	};
	
	for(int i=1;i<n;++i) f[i] = 1ll*binom(i-1, n-i-1)*fac[i]%mod*fac[n-i-1]%mod;
	
	int ans = 0;
	
	for(int i=1;i<n;++i){
		int g = (f[i]-f[i-1]+mod)%mod;
		ans = (ans+1ll*g*i)%mod;
	}
	
	printf("%d\n", ans);
	
	return 0;
}

Measured memory_bytes: 15872
#include<stdio.h>

int main(){
    int k, s;
    scanf("%d%d", &k, &s);
    int count = 0;
    for(int i=0; i<=k; i++){
        for(int j=0; j<=k; j++){
            if(0 <= s-i-j && s-i-j <= k){
                count++;
            }
        }
    }
    printf("%d", count);

    return 0;
}

Measured memory_bytes: 128
import java.io.*
import java.lang.*


fun solve() {
    val (A,B,C,D) = rd.readIntArray()

    val Mod = 998244353L
    //val dp = Array(C+1){Array(D+1){LongMod(0L, Mod)}}
    val dp = Array(C+1){LongArray(D+1){0L} }
    dp[A][B] = 1L

    for (i in A..C) {
        for (j in B..D) {
            val preRow = dp[i-1][j] * j % Mod
            dp[i][j] = (dp[i][j] + preRow) % Mod
            val preCol = dp[i][j-1] * i % Mod
            dp[i][j] = (dp[i][j] + preCol) % Mod
            var preRowCol = dp[i-1][j-1] * (i-1) % Mod
            preRowCol = preRowCol * (j-1) % Mod
            if ((dp[i][j] + Mod - preRowCol) >= Mod) {
                dp[i][j] -= Mod
            }
            dp[i][j] = (dp[i][j] + Mod - preRowCol) % Mod
        }
    }

    val ans = dp[C][D] % Mod
    println(ans)
}


//val rd = debug.Reader("agc", "046", "b", "sample-1")
val rd = Reader()


fun main(args: Array<String>) {
    try {
        var exception: Throwable? = null
        val sth = Thread(null, SolveThread(), "solveThread", 128 * 1024 * 1024)
        sth.setUncaughtExceptionHandler { _, e -> exception = e }
        sth.start(); sth.join()
        if (exception != null) throw exception!!
    } catch (e: Exception) { throw e }
}
const val MOD = 1_000_000_007L; const val INF = Int.MAX_VALUE/2; const val LINF = Long.MAX_VALUE/2
data class IntPair(val first: Int, val second: Int); data class LongPair(val first: Long, val second: Long)
val errPrintln: (Any) -> Unit = { msg -> System.err.println(msg) }
fun rAssert(exp: Boolean, lazyMsg: () -> String = {""}) {
    if (!exp) { val msg = lazyMsg(); errPrintln("EAssert Error: $msg"); throw Error(msg) }
}
fun tAssert(exp: Boolean, lazyMsg: () -> String = {""}) {
    if (!exp) { val msg = lazyMsg(); errPrintln("TAssert Error: $msg"); Thread.sleep(3000) }
}
class SolveThread : Runnable {
    override fun run() { solve() }
}
class Reader {
    private val br = BufferedReader(InputStreamReader(System.`in`))
    val readString: () -> String = { br.readLine() }
    val readInt: () -> Int = { br.readLine().toInt() }
    val readLong: () -> Long = { br.readLine().toLong() }
    val readIntArray: () -> IntArray = { br.readLine().split(' ').map { it.toInt() }.toIntArray() }
    val readLongArray: () -> LongArray = { br.readLine().split(' ').map { it.toLong() }.toLongArray() }
    val readListInt: () -> List<Int> = { br.readLine().split(' ').map { it.toInt() } }
    val readListLong: () -> List<Long> = { br.readLine().split(' ').map { it.toLong() } }
}


Measured memory_bytes: 107976
#include <algorithm>
#include <bitset>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>

using namespace std;
typedef long long ll;

template <typename T> void read(T &x) {
  x = 0;
  char c = getchar();
  T sig = 1;
  for (; !isdigit(c); c = getchar())
    if (c == '-')
      sig = -1;
  for (; isdigit(c); c = getchar())
    x = (x << 3) + (x << 1) + c - '0';
  x *= sig;
}

class Solution {
public:
  void solve() {
    int n;
    read(n);
    vector<vector<int>> red(n + 1), blue(n + 1);
    vector<int> L(n), R(n);
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
    ll ans = 0;
    for (int i = 0; i < n; ++i) {
      int k, l, r;
      read(k), read(l), read(r);
      if (l >= r)
        red[k].emplace_back(i);
      else
        blue[k].emplace_back(i);
      L[i] = l;
      R[i] = r;
      ans += min(l, r);
    }
    for (int i = 1; i <= n; ++i) {
      for (int j : red[i])
        pq.push({L[j] - R[j], j});
      while (pq.size() > i)
        pq.pop();
    }
    while (!pq.empty()) {
      ans += pq.top().first;
      pq.pop();
    }
    int t = red.size();
    for (int i = n; i >= 1; --i) {
      for (int j : blue[i])
        pq.push({R[j] - L[j], j});
      while (pq.size() > n - i)
        pq.pop();
    }
    while (!pq.empty()) {
      ans += pq.top().first;
      pq.pop();
    }
    cout << ans << endl;
  }
};

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  read(t);
  while (t--) {
    Solution solution = Solution();
    solution.solve();
  }
}

Measured memory_bytes: 19652
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> 
#include <ext/pb_ds/tree_policy.hpp> 
using namespace __gnu_pbds;
using namespace std;
typedef tree<pair<int,int>,null_type,less<pair<int,int>>,rb_tree_tag,tree_order_statistics_node_update> oset;
#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
  enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
  ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
  *this << "[";
  for (auto it = d.b; it != d.e; ++it)
	*this << ", " + 2 * (it == d.b) << *it;
  ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
using ll = long long;
const int A = 1e9+7;
int dp[110000];
void test_case() {
	int n,k;cin >> n >> k;
	vector<int> hash(n);
	for(int i = 0;i<n;++i) cin >> hash[i];
	for(int i = 0;i<n;++i) dp[i] = A;
	dp[0] = 0;
	dp[1] = abs(hash[1]-hash[0]);
	for(int i = 2; i<n;++i)
	{
		for(int j = 1;j<=k;++j)
		{
			if(j<=i)
			{
				dp[i] = min(dp[i],dp[i-j] + abs(hash[i]-hash[i-j]));
			}
		}
	}
	cout << dp[n-1] << '\n';
}
 
int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int T=1;
	//cin >> T;
	while(T--) {
		test_case(); 
		
	}
}


Measured memory_bytes: 1024
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
  let stdin = stdin();
  let stdin = stdin.lock();
  let token: String = stdin
    .bytes()
    .map(|c| c.expect("failed to read char") as char) 
    .skip_while(|c| c.is_whitespace())
    .take_while(|c| !c.is_whitespace())
    .collect();
  token.parse().ok().expect("failed to parse token")
}

fn main() {
  let n: usize = read();
  let mut r: usize = 0;
  for i in 1..n+1 {
    if i % 2 == 1 {
      let mut m: usize = 0;
      for j in 1..i+1 {
        m += if i % j == 0 { 1 } else { 0 };
      }
      r += if m == 8 { 1 } else { 0 };
    }
  }
  println!("{}", r);
}

Measured memory_bytes: 4352
#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define debug(x) cerr << #x << " " << x << '\n'
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pli = pair<ll,int>;
const int INF = 0x3f3f3f3f, N = 2e5 + 5;
const ll LINF = 1e18 + 5;
int n, d, a;
ll c[N];
struct node
{
	int x, h;
	bool operator < (const node& a) { return x < a.x; } 
}p[N];
void upd(int x, ll v)
{
	for(int i=x; i<N; i+=(i&-i)) c[i] += v;
}
void modify(int l, int r, ll v)
{
	upd(l, v); upd(r+1, -v);
}
ll ask(int x)
{
	ll ans = 0;
	for(int i=x; i>0; i-=(i&-i)) ans += c[i];
	return ans;
}
int main()
{
 	ios::sync_with_stdio(false);
 	cin.tie(0);
 	cin >> n >> d >> a;
 	for(int i=1; i<=n; i++)
 		cin >> p[i].x >> p[i].h;
 	sort(p+1, p+n+1);
 	ll cnt = 0;
 	for(int i=1; i<=n; i++)
 	{
 		ll r = p[i].x + 2ll*d;
 		ll tmp = ask(i);
 		p[i].h -= tmp;
 		if(p[i].h<=0) continue;
 		ll cur = p[i].h/a + (p[i].h%a ? 1 : 0);
 		cnt += cur;
 		int L = i + 1, R = n, pos = i;
 		while(L<=R)
 		{
 			int mid = (L+R)>>1;
 			if(p[mid].x<=r) pos = mid, L = mid + 1;
 			else R = mid - 1;
 		}
 		//debug(pos);
 		modify(i, pos, cur*a);
 	}
 	cout << cnt;
	return 0;
}


Measured memory_bytes: 3328
#include<iostream>
#include<cmath>
using namespace std;
int prime_serch(int x){
    int i;
    if (x == 2){
        return true;
    } else if (x < 2 || x%2 == 0){
        return false;
    } else {
        i = 3;
        while (i <= sqrt(x)){
            if (x%i == 0){
                return false;
            }
            i += 2;
        }
    }
    return true;
}
int main() {
    int n, x, ans = 0;
    cin >> n;
    for (int i=0; i<n; i++){
        cin >> x;
        if (prime_serch(x)) ans += 1;
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 3088
#include <bits/stdc++.h>

using namespace std;
int a,n;
long long res=0;

int gcd2(int a, int b)
{
    if (a%b==0) return b;
    else return gcd2(b,a%b);
}

int gcd(int a, int b, int c)
{
    return gcd2(a,gcd2(c,b));
}

int main()
{
    cin >> n;
    for (int i=1;i<=n;i++)
        for (int j=1;j<=n;++j)
            for (int k=1;k<=n;++k)
                res+=gcd(i,j,k);
    cout << res;
    return 0;
}


Measured memory_bytes: 3624
#define _CRT_SECURE_NO_WARNINGS
#define llong long long
#define REP(i, n) for(int i=0; i<n; i++)
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <list>
#include <queue>
#include <utility>
#include <stdio.h>
#include <math.h>
using namespace std;

int main() {
	int d;
	cin >> d;
	cout << "Christmas";
	REP(i, 25 - d)cout << " Eve";
	puts("");
}

Measured memory_bytes: 256