akhauriyash/Code-Regression huggingface dataset:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define FOR(i, a, b) for(ll i = (ll)a; i <= (ll)b; i++)
#define DEC(i, a, b) for(ll i = (ll)a; i >= (ll)b; i--)
typedef pair<ll, ll> pi;
typedef pair<ll, pi> pii;
typedef pair<pi, pi> pipi;
#define f first
#define s second
typedef vector<ll> vi;
typedef vector<pi> vpi;
typedef vector<pii> vpii;
#define pb push_back
#define pf push_front
#define all(v) v.begin(), v.end()
#define disc(v) sort(all(v)); v.resize(unique(all(v)) - v.begin());
#define INF (ll) 1e9 + 100
#define LLINF (ll) 1e18
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)

ll n, m, lim, x[200005], y[200005], xss[200005], yss[200005];

bool check(ll g) {
	FOR(i, max(0ll, g-m), min(g, n)) if (xss[i] + yss[g-i] <= lim) return true;
	return false;
}

int main() {
	fastio; cin >> n >> m >> lim;
	FOR(i, 1, n) {
		cin >> x[i];
		xss[i] = xss[i-1] + x[i];
	}
	FOR(i, 1, m) {
		cin >> y[i];
		yss[i] = yss[i-1] + y[i];
	}
	ll lower = 0, upper = n+m+1;
	while (upper - lower > 1) {
		ll mid = (upper + lower)/2;
		if (check(mid)) lower = mid;
		else upper = mid;
	}
	cout << lower;
}


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

using namespace std;
using pii = pair<int, int>;
template <class T> using pq_gt = priority_queue<T, vector<T>, greater<T>>;

template <typename S, typename T>
std::ostream &operator<<(std::ostream &os, std::pair<S, T> &p) {
  os << '(' << p.first << ", " << p.second << ')';
  return os;
}

int main(int argc, char const *argv[]) {
  int n, m;
  cin >> n >> m;
  vector<pair<int, int>> v(n);

  for (int i = 0; i < n; i++) {
    cin >> v[i].first >> v[i].second;
  }

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

  auto cmp = [](pii p1, pii p2) -> bool {
    return (p1.second != p2.second) ? p1.second < p2.second
                                    : p1.first < p2.first;
  };

  priority_queue<pii, vector<pii>, decltype(cmp)> q{cmp};

  int iv = 0;
  int ret = 0;

  for (int i = 1; i <= m; i++) {
    while (iv < n && v[iv].first <= i) {
      q.push(v[iv]);
      iv++;
    }

    if (!q.empty()) {
      pii tmp = q.top();
      ret += tmp.second;
      q.pop();
    }
  }
  cout << ret << endl;

  return 0;
}


Measured memory_bytes: 2168
def factorial(n):
    fact = 1
    for i in range(n, 0, -1):
        fact = (fact * i) % (10 ** 9 + 7)
    return fact

def arrengements(n, m):
    if abs(n - m) == 1:
        return (factorial(n) * factorial(m)) % (10 ** 9 + 7)
    elif n == m:
        return (factorial(n) * factorial(m) * 2) % (10 ** 9 + 7)
    else:
        return 0
        

if __name__ == '__main__':
    n, m = map(int, input().split())
    print(arrengements(n, m) % (10 ** 9 + 7))

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


void solve(long long a, long long b){
    long long pos = b - a - 2;
    long long cnt = 0;
    for(long long i = 1; i <= pos+1; ++i) cnt = cnt + i;
    cout << cnt - a << endl;
}

int main(){
    long long a;
    scanf("%lld",&a);
    long long b;
    scanf("%lld",&b);
    solve(a, b);
    return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#define fi first
#define se second
#define int long long
using namespace std;

int constexpr N = 100009, MOD = 1e9 + 7;
int n, k;
vector<vector<int>> g(N);
vector<int> k1(N), k2(N);
int ans;

void dfs(int u, int p = -1) {
    if(p == -1)
        ans *= k1[g[u].size()], ans %= MOD;
    else
        ans *= k2[g[u].size() - 1], ans %= MOD;
    for(int v : g[u]) if(v != p)
        dfs(v, u);
}


signed main() {
    ios::sync_with_stdio(0); cin.tie(0);
    cin >> n >> k;
    ans = k;
    for(int i = 0, u, v; i < n - 1; ++i) {
        cin >> u >> v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    k1[0] = k2[0] = 1;
    for(int i = 1; i < N; ++i) {
        k1[i] = ((k - i) * k1[i - 1]) % MOD;
    }
    for(int i = 1; i < N; ++i) {
        k2[i] = ((k - i - 1) * k2[i - 1]) % MOD;
    }
    dfs(1);
    cout << ans << endl;
}

Measured memory_bytes: 10752
#include <bits/stdc++.h>
#define IOS                           \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL)
#define ll long long
using namespace std;

int maxLength(string &s, string &t, int i, int j,vector<vector<int>> &dp){

    if(i == s.length() || j == t.length()){
        return 0;
    }
    if(dp[i][j] != -1){
        return dp[i][j];
    }
    if(s[i] == t[j]){
        dp[i][j] = 1 + maxLength(s, t, i + 1, j + 1,dp);
    }else{
        int i1 = maxLength(s, t, i + 1, j,dp);
        int i2 = maxLength(s, t, i, j + 1,dp);
        dp[i][j] = max(i1, i2);
    }
    return dp[i][j];
}

void solve()
{
    string s;
    string t;
    cin >> s;
    cin >> t;
    vector<vector<int>> dp(s.length()+1,vector<int>(t.length()+1,-1));
    int maxLengthfound = maxLength(s, t, 0, 0,dp);
    string ans = "";
    int i = 0;
    int j = 0;
    while(i<s.length() and j<t.length()){
        if(s[i] == t[j]){
            ans = ans + s[i];
            i++;
            j++;
        }
        else
        {
            if(dp[i+1][j] > dp[i][j+1]){
                i++;
            }else{
                j++;
            }
        }
    }
    cout << ans << endl;
}
int main()
{
    IOS;
    // int t;
    // cin>>t;
    // while(t>0)
    {
        solve();
        // t--;
    }
    return 0;
}



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

#define     ll      long long
#define     pb      push_back
#define     eps     1e-9
#define     pi      acos(-1)
#define     ff      first
#define     ss      second
#define     case    cout<<"Case "<<++cs<<": ";
#define     Fast_Read                    ios_base::sync_with_stdio(false); cin.tie(nullptr);  cout.tie(nullptr);
#define     Precision(x)                 cout.setf(ios::fixed); cout.precision(x);

using namespace std;
typedef long double ld;
#ifdef ARnAb
     #define debug(...) __f(#__VA_ARGS__, __VA_ARGS__)
    template < typename Arg1 >
    void __f(const char* name, Arg1&& arg1){
        cerr << name << " is " << arg1 << std::endl;
    }
    template < typename Arg1, typename... Args>
    void __f(const char* names, Arg1&& arg1, Args&&... args){
        const char* comma = strchr(names+1, ',');
        cerr.write(names, comma - names) << " is " << arg1 <<"  ";
        __f(comma+1, args...);
    }
#else
    #define debug(...)
#endif
///******************************************START******************************************
int cs=0;
int node,query;
vector<int> adj[1000005];
bool vis[1000005];
ll val[1000005];
void dfs(int sp,ll valu)
{
    vis[sp]=1;
    val[sp]=valu;
    for(int i=0;i<adj[sp].size();i++)
    {
        if(vis[adj[sp][i]]==1)
            continue;
        dfs(adj[sp][i],val[sp]+val[adj[sp][i]]);
    }
}
void solve()
{
    cin>>node>>query;
    for(int i=0;i<node-1;i++)
    {
        int a,b;
        cin>>a>>b;
        adj[a].pb(b);
        adj[b].pb(a);
    }
    while(query--)
    {
        int x,y;
        cin>>x>>y;
        val[x]+=y;
    }
    dfs(1,val[1]);
    for(int i=1;i<=node;i++)
    {
        cout<<val[i]<<" ";
    }
}
int main()
{
    //Fast_Read
    Precision(6)
    #ifdef ARnAb
        double start_time = clock();
        ///freopen ("output.txt","w",stdout);
        ///freopen ("input.txt","r",stdin);
    #endif
    int tc=1;
    //cin>>tc;
    while(tc--)
    solve();
    return 0;
}


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

#define rep(i,n) for(int i = 0; i < n; i++)
#define REP(i,n) for(int i = 1; i < n; i++)
#define sz(x) int(x.size())
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define YesorNo(a) printf(a ? "Yes\n" : "No\n")
#define endl "\n"
using ll = long long;
using P = pair<int,int>;
using Pl = pair<ll,ll>;
using vi = vector<int>;
using vii = vector<vi>;
using vl = vector<ll>;
using vll = vector<vl>;
using vs = vector<string>;
const int dx[] = {0,1,0,-1,1,1,-1,-1};
const int dy[] = {1,0,-1,0,1,-1,-1,1};
const int inf = (1<<30)-1;
const ll infll = (1LL<<62)-1;
ll ceil(const ll a, const ll b){return ((a)+(b)-1)/b;}


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

  int n;
  cin >> n;
  int f;
  cin >> f;
  deque<int> last;
  last.push_back(f);
  last.push_back(inf);
  REP(i,n) {
    int a;
    cin >> a;
    auto it = lower_bound(all(last), a);
    if(it == last.begin()) {
      last.push_front(a);
    }
    else {
      it--;
      *it = a;
    }
  }
  int ans = sz(last);
  cout << ans-1 << endl;
}

Measured memory_bytes: 640
package main

import "fmt"

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	p := make([]int, m)
	s := make([]string, m)
	for i := 0; i < m; i++ {
		fmt.Scan(&p[i], &s[i])
	}

	ac := 0
	wa := 0

	clear := make(map[int]int, 0)
	for i := 0; i < m; i++ {
		number := p[i] - 1
		if clear[number] == -1 {
			continue
		}
		if s[i] == "AC" {
			ac++
			wa += clear[number]
			clear[number] = -1
		} else if s[i] == "WA" {
			clear[number]++
		}
	}
	fmt.Printf("%v %v\n", ac, wa)
}


Measured memory_bytes: 10368
//#define MyDebug
#include <bits/stdc++.h>

#define rep(i, from, to) for (int i = from; i < to; ++i)
#define REP(i, from, to) for (int i = from; i <= to; ++i)

#ifdef MyDebug
#define debug(x) cerr << #x << " : " << x << endl;
#define debug3(x, y, z) cerr << #x << " : " << x << ", "<<#y << " : " << y <<  ", " << #z << " : " << z << endl;
#else
#define debug(x)
#define debug3(x, y, z)
#endif

using namespace std;

int cnt = 0;
string s;
char now;
string ans;
char op1 = '*', op2 = '+', op3 = '-';
bool isSymbol(char c) {
	return c == '0' || c == '1' || c == '2' || c == 'P' || c == 'Q' || c == 'R';
}
void replaceAll(string &s, char c, int num) {
	rep (i, 0, (int)s.size()) {
		if (s[i] == c) s[i] = (char)(num + '0');
	}
}
void formula() {
	if (s[cnt] == '(') {
		++cnt;
		formula();
		if (s[cnt] == op1) {
			++cnt;
			formula();
			ans += op1;
			debug(ans);
			++cnt;
		}else if (s[cnt] == op2) {
			++cnt;
			formula();
			ans += op2;
			debug(ans);
			++cnt;
		}
	} else if (isSymbol(s[cnt])) {
		ans += s[cnt];
		++cnt;
	} else if (s[cnt] == op3) {
		++cnt;
		formula();
		ans += op3;
	}
}

int my_or[][3] = {{0, 1, 2},
				   {1, 1, 2},
				   {2, 2, 2}};
int my_and[][3] = {{0, 0, 0},
	              {0, 1, 1},
				  {0, 1, 2}};
int my_not[] = {2, 1, 0};

int eval(int x1, int x2, char op) {
	debug3(x1, x2, op);
	if (op == op1) {
	debug(my_and[x1][x2]);
		return my_and[x1][x2];
	}
	if (op == op2) {
	debug(my_or[x1][x2]);
		return my_or[x1][x2];
	}
	if (op == op3) {
	debug(my_not[x1]);
		return my_not[x1];
	}
	cerr << "error" << endl;
	return -1;
}

stack<int> st;

bool isNum(char c) {
	return c == '0' || c == '1' || c == '2';
}
int evalAll(string &s) {
	rep(i, 0, (int)s.size()) {
		//debug(s[i]);
		if (isNum(s[i])) {
			st.push(s[i] - '0');
		} else if (s[i] == op3) {
			int v = eval(st.top(), -1, op3);
			st.pop();
			st.push(v);
		} else if (s[i] == op1 || s[i] == op2){
			int x1 = st.top();st.pop();
			int x2 = st.top();st.pop();
			int v = eval(x1, x2, s[i]);
			st.push(v);
		} else cerr << "error" << endl;
	}
	int top = st.top();
	st.pop();
	return top;
}
int ansN = 0;
void init() {
	ansN = 0;
	ans ="";
	st = stack<int>();
	cnt = 0;
	s = "";
}

void solve() {
	while(cin >> s, s != ".") {
		formula();
		rep(i, 0, 3) {
			rep(j, 0, 3) {
				rep(k, 0, 3) {
					string ans1 = ans;
					replaceAll(ans1, 'P', i);
					replaceAll(ans1, 'Q', j);
					replaceAll(ans1, 'R', k);
					if (evalAll(ans1) == 2) {
						++ansN;
					}
				}
			}
		}
		cout << ansN << endl;
		init();
	}
}
void test() {
	string s = "aaaaaa";
	s.insert(2, "b");
	s.erase(2, 1);
	debug(s);
}
void test2() {
	string a = "01+";
	debug(evalAll(a));
}
void test3() {
	string a = "PQ+Q*-";
	replaceAll(a, 'P', 2);
	replaceAll(a, 'Q', 1);
	cerr << a << endl;
	cerr << evalAll(a) << endl;
}
void test4() {
	string s = "2";
	cerr << evalAll(s) << endl;
}
void test5() {
	s = "(((P+(---Q*Q))*(-(---2*(--0*Q))+(--R+--1)))+(((1*Q)+-1)*-(--0*---P)))";
	//s = "(-(P+(P*Q))*Q)";
	formula();
	cerr << ans << endl;
}

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

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

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


    vector<vector<int>> x(N+1);

    for(int i=0; i<M; i++){
        int a, b;
        cin>> a >> b;
        x[a].push_back(b);
    }

    for(auto a : x[1]){
        for(auto b : x[a]){
            if(b == N){
                cout<< "POSSIBLE" <<endl;
                return 0;
            }
        }
    }
    cout<< "IMPOSSIBLE" <<endl;
    return 0;
}

Measured memory_bytes: 11448
import java.util.*;

class Main{
	public static void main(String[] args) 	{
		Scanner sc = new Scanner(System.in);
		HashSet<String> hs = new HashSet<String>();
		int num = sc.nextInt();
		for(int i = 0 ; i < num ; i++) {
			String str = sc.next();
			if(str.equals("insert")) {
				String add = sc.next();
				hs.add(add);
			}
			if(str.equals("find")) {
				String find = sc.next();
				if(hs.contains(find)) System.out.printf("yes\n");
				else System.out.printf("no\n");
			}
		}
		sc.close();
	}
}


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

const int mod = 1e9 + 7;
const int Half = 500000004;

int N; string S;
int M;

int f[5005][5005];

int main() {
	cin >> N;
	cin >> S; M = (int)S.length();
	f[0][0] = 1;
	for (int i = 1; i <= N; ++i) {
		f[i][0] = (f[i - 1][0] + f[i - 1][1]) % mod;
		for (int j = 1; j <= i; ++j) f[i][j] = (f[i - 1][j - 1] * 2LL + f[i - 1][j + 1]) % mod;
	}
	int ans = f[N][M];
	while (M--) ans = 1LL * ans * Half % mod;
	cout << ans << endl;
}

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

using namespace std;

typedef long long ll;

int n;
ll z,w;

ll dp[2][2005];
vector<ll>v;

ll go(bool turn,int ind,ll x,ll y){
	if(ind==n)
		return abs(x-y);
	if(dp[turn][ind]!=-1)
		return dp[turn][ind];
	ll ret=turn?0:1e18;
	for(int i=ind+1;i<=n;i++){
		if(turn)
			ret=max(ret,go(0,i,v[i-1],y));
		else
			ret=min(ret,go(1,i,x,v[i-1]));
	}
	return dp[turn][ind]=ret;
}
int main(){
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cin>>n>>z>>w;
	memset(dp,-1,sizeof dp);
	v.resize(n);
	for(int i=0;i<n;i++)
		cin>>v[i];
	cout<<go(1,0,z,w)<<endl;
}


Measured memory_bytes: 512
#include<bits/stdc++.h>
using namespace std;
const int maxn=200000;
vector<int>eds[maxn],vv;
int n,x,y;
pair<int,int>go[maxn];
int ad[maxn],ans[maxn];
void dfs1(int v,int p,pair<int,int>ma)
{
    if(ma.second<v) ma.second=v;
    if(ma.second>ma.first) swap(ma.second,ma.first);
    go[v]=ma;
    for(int i=0;i<eds[v].size();i++)
    {
        int u=eds[v][i];
        if(u==p) continue;
        dfs1(u,v,ma);
    }
}
void dfs3(int v,int p,int cnt)
{
    cnt+=ad[v];
    ans[v]=cnt;
    for(int i=0;i<eds[v].size();i++)
    {
        int u=eds[v][i];
        if(u==p) continue;
        dfs3(u,v,cnt);
    }
}
void dfs2(int v,int p)
{
    vv.push_back(v);
    if(v==0) ad[0]++;
    else
    {
        int l=0;
        int r=vv.size()-1;
        while(r-l>1)
        {
            int m=l+r>>1,x=vv[m],f1=0;
            if(go[x].first!=x&&go[x].first==go[v].first
               ||go[x]==go[v]) f1=1;
            if(f1) r=m;
            else l=m;
        }
        ad[vv[r]]++;
    }
    for(int i=0;i<eds[v].size();i++)
    {
        int u=eds[v][i];
        if(u==p) continue;
        dfs2(u,v);
    }
    vv.pop_back();
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<n;i++)
    {
        scanf("%d%d",&x,&y);
        x--;y--;
        eds[x].push_back(y);
        eds[y].push_back(x);
    }
    dfs1(0,-1,make_pair(-1,-1));
    dfs2(0,-1);
    dfs3(0,-1,0);
    for(int i=1;i<n;i++)
        printf(i==n-1?"%d\n":"%d ",ans[i]-1);
}


Measured memory_bytes: 31480
n = int(input())
a = list(map(int, input().split()))
a.sort()
M = a[-1]
m = a[0]
C = -1
for i in range(n):
  c = a[i]*(M-a[i])
  if C < c:
    C = c
    m = a[i]
  else:
    break
print(M, m, sep=' ')

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

typedef long long ll;

ll n,a,b,k,jwb=0,tmp;
const ll MOD = 998244353;
ll f[300010];

ll fastpow(ll a, ll b) {
    if (b==0) return 1;
    ll x=1,y=a; 
    while(b > 0)
    {
        if(b%2 == 1)
        {
            x=(x*y) % MOD;
        }
        y = (y*y) % MOD;
        b /= 2;
    }
    return x;
}

ll inv(ll n) {
    return fastpow(n,MOD-2);
}

ll C(ll n, ll r) {
    return (f[n]*((inv(f[r]) * inv(f[n-r])) % MOD)) % MOD;
}

int main()
{
  cin >> n >> a >> b >> k;
  f[0] = 1;
  for (ll i=1;i<=300000;++i) {
    f[i] = (f[i-1]*i)%MOD;
  }
  for (ll i=0;i<=n;++i) {
    if (k-i*a<0) break;
    if ((k-i*a)%b == 0) {
      ll j = (k-i*a)/b;
      if (j>n) continue;
      tmp = (C(n, i)*C(n, j))%MOD;
      jwb = (jwb+tmp)%MOD;
    }
  }
  cout << jwb << endl;
  return 0;
}

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

int gcd(int i, int j){
  if (j == 0) return i;
  return gcd(j, i%j);
}

int64_t lcm(int i, int j){
  int64_t ret = (int64_t) i * j / gcd(i, j);
  return ret;
}

int main(){
  int64_t a, b;
  int c, d;
  cin >> a >> b >> c >> d;
  auto num_div = [&](int64_t i){
    int64_t l = (a + i - 1)/i;
    int64_t r = b / i;
    return r - l + 1;
  };
  cout << b - a + 1 - num_div(c) - num_div(d) + num_div(lcm(c, d)) << endl;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e6+5,mod=1e9+7;
ll n,f[N];
ll powmod(ll x,ll n)
{
	ll s=1;
	while(n)
	{
		if(n&1)
			s=(s*x)%mod;
		n>>=1;
		x=(x*x)%mod;
	}
	return s;
}
ll C(ll n,ll m)
{
	if(n<m)
		return 0;
	ll a=f[n],b=(f[n-m]*f[m])%mod;
	return (a*powmod(b,mod-2))%mod;
}
int main()
{
	cin>>n;
	f[0]=1;
	for(int i=1;i<=n;i++)
		f[i]=(f[i-1]*i)%mod;
	ll res=0,pre=0;
	for(int k=1;k<n;k++)
	{
		ll tk=(f[k]*f[n-1-k])%mod;
		tk=(tk*C(k-1,n-k-1))%mod;
		ll num=(tk-pre+mod)%mod;
		res=(res+(num*k)%mod)%mod;
		pre=tk;
	}
	cout<<res<<'\n';
	return 0;
}

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

using namespace std;
using uint = unsigned int;
using ll = long long;
using ull = unsigned long long;
template<class T> using V = vector<T>;
template<class T> using VV = V<V<T>>;
constexpr ll TEN(int n) { return (n == 0) ? 1 : 10 * TEN(n-1); }

const ll INF = TEN(18);

int n;
V<ll> a;
VV<int> g;

using P = pair<ll, ll>;
V<P> dfs(int p, int b) {
    V<P> dp = {{0, INF}};
    for (int d: g[p]) {
        if (d == b) continue;
        auto ndp = dfs(d, p);
        int k = int(ndp.size());
        ndp.push_back({INF, INF});
        for (int i = k - 1; i >= 0; i--) {
            if (ndp[i].first < INF / 2 || ndp[i].second < 0) ndp[i + 1].first = min(ndp[i + 1].first, 0LL);
        }
        int m = int(dp.size()) - 1;
        V<P> udp(m + k + 1, {INF, INF});
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= k; j++) {
                udp[i+j].first = min(udp[i+j].first, dp[i].first + ndp[j].first);
                udp[i+j].second = min(udp[i+j].second, dp[i].first + ndp[j].second);
                udp[i+j].second = min(udp[i+j].second, dp[i].second + ndp[j].first);
                udp[i+j].second = min(udp[i+j].second, dp[i].second + ndp[j].second);
            }
        }
        dp = udp;
    }
    int m = int(dp.size()) - 1;
    V<P> udp(m + 1);
    for (int i = 0; i <= m; i++) {
        if (a[p] > 0) {
            udp[i].first = dp[i].first + a[p];
            udp[i].second = dp[i].second + a[p];
        } else {
            udp[i].first = INF;
            udp[i].second = min(dp[i].first, dp[i].second) + a[p];
        }
    }

    return udp;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << setprecision(20) << fixed;

    cin >> n;
    a = V<ll>(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    g = VV<int>(n);
    for (int j = 0; j < n - 1; ++j) {
        int a, b;
        cin >> a >> b; a--; b--;
        g[a].push_back(b);
        g[b].push_back(a);
    }

    auto dp = dfs(0, -1);

    for (int i = 0; i < n; i++) {
        if (dp[i].first < INF / 2 || dp[i].second < 0) {
            cout << i << endl;
            return 0;
        }
    }
    assert(false);
    return 0;
}


Measured memory_bytes: 1916
#include <bits/stdc++.h>
#define va first
#define vb second
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

int R, C, N;
vector<pii> A;

int func(int x, int y) {
	if (y == 0) return x;
	if (x == R) return R + y;
	if (y == C) return R + C + R-x;
	if (x == 0) return R + C + R + C-y;
	return -1;
}
int main() {
	cin.tie(0); ios_base::sync_with_stdio(0);
	cin >> R >> C >> N;
	for (int i=1; i<=N; i++) {
		int xi, yi, xj, yj;
		cin >> xi >> yi >> xj >> yj;

		if (func(xi, yi) == -1 || func(xj, yj) == -1) continue;
		A.emplace_back(func(xi, yi), i);
		A.emplace_back(func(xj, yj), i);
	}
	sort(A.begin(), A.end());

	vector<int> stk;
	for (pii x : A) {
		if (stk.empty() || stk.back() != x.vb) stk.push_back(x.vb);
		else stk.pop_back();
	}

	if (stk.empty()) cout << "YES";
	else cout << "NO";
}

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


#define li          long long int
#define rep(i,to)   for(li i=0;i<((li)(to));i++)
#define repp(i,start,to)    for(li i=(li)(start);i<((li)(to));i++)
#define pb          push_back
#define sz(v)       ((li)(v).size())
#define bgn(v)      ((v).begin())
#define eend(v)     ((v).end())
#define allof(v)    (v).begin(), (v).end()
#define dodp(v,n)       memset(v,(li)n,sizeof(v))
#define bit(n)      (1ll<<(li)(n))
#define mp(a,b)     make_pair(a,b)
#define rin rep(i,n)
#define EPS 1e-12
#define ETOL 1e-8
#define MOD 1000000007
typedef pair<li, li> PI;

#define INF bit(60)

#define DBGP 1


#define idp if(DBGP)
#define F first
#define S second
#define p2(a,b)     idp cout<<a<<"\t"<<b<<endl
#define p3(a,b,c)       idp cout<<a<<"\t"<<b<<"\t"<<c<<endl
#define p4(a,b,c,d)     idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<endl
#define p5(a,b,c,d,e)       idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<endl
#define p6(a,b,c,d,e,f)     idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<endl
#define p7(a,b,c,d,e,f,g)       idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<g<<endl
#define p8(a,b,c,d,e,f,g,h)     idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<g<<"\t"<<h<<endl
#define p9(a,b,c,d,e,f,g,h,i)       idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<g<<"\t"<<h<<"\t"<<i<<endl
#define p10(a,b,c,d,e,f,g,h,i,j)        idp cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<"\t"<<e<<"\t"<<f<<"\t"<<g<<"\t"<<h<<"\t"<<i<<"\t"<<j<<endl
#define foreach(it,v)   for(__typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it)
#define p2p(x)      idp p2((x).F, (x).S)
#define dump(x,n)   idp{rep(i,n){cout<<x[i]<<" ";}puts("");}
#define dump2(x,n)  idp{rep(i,n){cout<<"["<<x[i].F<<" , "<<x[i].S<<"] ";}puts("");}
#define dumpi(x)    idp{foreach(it, x){cout<<(*it)<<" ";}puts("");}
#define dumpi2(x)   idp{foreach(it, x){cout<<"["<<(it)->F<<" , "<<(it)->S<<"] ";}puts("");}

#define read2d(a,w,h)   rep(i,h)rep(j,w)cin>>a[i][j]
#define dump2d(a,w,h)   rep(i,h){rep(j,w)cout<<a[i][j]<<" ";puts("");}

typedef pair<li, li> PI;



int main() {
    li h,a;
    cin>>h>>a;
    cout<<(h+a-1)/a<<endl;

    return 0;
}

Measured memory_bytes: 3620
/*
    Mbak Sana Dong
*/
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
    int n,m,i,j,k,x,y,ans,curr,temp;
    string s;
    cin >> s;
    int len = s.length();
    int sana = 0;
    for(i=0;i<len/2;i++)
    {
        if(s[i] != s[len-i-1]) sana++;
    }
    cout << sana << endl;
    return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
 
#define rep(i,n) for(ll i=0;i<n;++i)
#define ALL(a) (a).begin(),(a).end()
 
using namespace std;
using ll  = long long;
using pll = pair<ll, ll>;
using pdd = pair<double, double>;
 
const ll MOD  = 1e9+7;
const ll LINF = 1LL << 60;
const int INF = 1e9 + 7;

int mvx[]={0, 0, -1, 1};
int mvy[]={-1, 1, 0, 0};

int main(){
    int n, w_max;
    cin >> n >> w_max;
    
    int v[n], w[n];
    rep(i, n)cin >> v[i] >> w[i];

    //dp[i][j] : 重さj以内で、i種類までの品物の合計の最大値
    ll dp[n+1][w_max+1] = {};
    rep(i, n)rep(j, w_max+1){
        dp[i+1][j] = dp[i][j];

        //品物を使う時
        if(j >= w[i]){
            dp[i+1][j] = max(dp[i+1][j], dp[i+1][j-w[i]] + v[i]);
        }
    }

    cout << dp[n][w_max] << endl;
}


Measured memory_bytes: 10984
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
#include <cmath>

static const int MOD = 1000000007;
using ll = long long;
using u32 = unsigned;
using u64 = unsigned long long;
using namespace std;

template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;

int main() {
    int n;
    cin >> n;
    string s = "a";
    auto dfs = [&](int x, int sz, auto &&f){
        if(x == n){
            cout << s << "\n";
            return;
        }
        for (int i = 0; i <= sz+1; ++i) {
            s += 'a' + i;
            f(x+1, max(sz, i), f);
            s.pop_back();
        }
    };
    dfs(1, 0, dfs);
    return 0;
}

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

template<class T> inline bool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, const T& b) { if (b < a) { a = b; return 1; } return 0; }

class modint {
	static constexpr std::int_fast64_t Modulus = 1e9 + 7;
	using u64 = std::int_fast64_t;

public:
	u64 a;
	constexpr modint(const u64 x = 0) noexcept : a(x% Modulus) {}
	constexpr u64& value() noexcept { return a; }
	constexpr const u64& value() const noexcept { return a; }
	constexpr modint operator+(const modint rhs) const noexcept {
		return modint(*this) += rhs;
	}
	constexpr modint operator-(const modint rhs) const noexcept {
		return modint(*this) -= rhs;
	}
	constexpr modint operator*(const ll rhs) const noexcept {
		return modint(*this) *= modint(rhs);
	}
	constexpr modint operator*(const modint rhs) const noexcept {
		return modint(*this) *= rhs;
	}
	constexpr modint& operator+=(const modint rhs) noexcept {
		a += rhs.a;
		if (a >= Modulus) {
			a -= Modulus;
		}
		return *this;
	}
	constexpr modint& operator-=(const modint rhs) noexcept {
		if (a < rhs.a) {
			a += Modulus;
		}
		a -= rhs.a;
		return *this;
	}
	constexpr modint& operator*=(const modint rhs) noexcept {
		a = a * rhs.a % Modulus;
		return *this;
	}
	constexpr operator u64() const { return a; }
};

int main() {
	string L;
	cin >> L;
	int n = L.size();
	vector<vector<modint>> dp(n + 1, vector<modint>(2, 0));
	//dp[i][1]...a+bが等しい
	//dp[i][0]...a+bが小さい
	dp[0][1] = 2;//10,01
	dp[0][0] = 1;//00
	for (int i = 1; i < n; i++) {
		const bool one = L[i] == '1';
		if (one) {
			dp[i][1] += dp[i - 1][1] * 2LL;//10,01
			dp[i][0] += dp[i - 1][0] * 3LL;//10,01,00
			dp[i][0] += dp[i - 1][1] * 1LL;//00
		}
		else {
			dp[i][1] += dp[i - 1][1] * 1LL;//00
			dp[i][0] += dp[i - 1][0] * 3LL;//10,01,00
		}
	}
	ll sum = dp[n - 1][0] + dp[n - 1][1];
	cout << sum << endl;
	return 0;
}


Measured memory_bytes: 8740
n=int(input())
import heapq
a=list(map(int,input().split()))
q=a[:n]
heapq.heapify(q)
x=[sum(q)]
for k in range(n,2*n):
    v=heapq.heappushpop(q,a[k])
    x.append(x[-1]+a[k]-v)
a=a[::-1]
q=[-v for v in a[:n]]
heapq.heapify(q)
y=[-sum(q)]
for k in range(n,2*n):
    v=-heapq.heappushpop(q,-a[k])
    y.append(y[-1]+a[k]-v)
print(max(v-w for v,w in zip(x,y[::-1])))

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

int main() {
    string o, e;
    cin >> o >> e;

    string ans = "";
    if (o.size() == e.size()) {
        for (int i = 0; i < o.size(); i++) {
            ans += o[i];
            ans += e[i];
        }
    } else {
        for (int i = 0; i < e.size(); i++) {
            ans += o[i];
            ans += e[i];
        }
        ans += o[o.size() - 1];
    }
    cout << ans << endl;
    return 0;
}

Measured memory_bytes: 256
import fractions

A,B,C,D = map(int,input().split())

U = B - A + 1

x = B // C - (A-1) // C
y = B // D - (A-1) // D

lcm = C*D // fractions.gcd(C,D)
z = B // lcm - (A-1) // lcm

print(U - (x + y - z))


Measured memory_bytes: 5048
import std.stdio, std.string, std.conv, std.range;

void main() {
  auto N = readln.chomp.to!int;
  ulong power = 1;
  foreach (i; iota(1, N + 1)) {
    power *= i;
    power %= 1000000007;
  }

  power.writeln;
}


Measured memory_bytes: 256
#include <iostream>
#include <string>
#include <algorithm>
#define rep(i,n) for(int i=0;i<n;++i)

using namespace std;

int n, m, ans = 0; string A[10101], str;
int main() {
	cin >> n >> m;
	rep(i, n)  cin >> A[i];
	sort(A, A + n);
	rep(i, n) str += A[i];
	cout << str << endl;
	return 0;
}

Measured memory_bytes: 384
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define rrep(i,n) for(int i = 1; i <= (n); ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define eb emplace_back
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vi> vvi;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
ll gcd(ll a, ll b) { return b?gcd(b,a%b):a;}
ll lcm(ll a, ll b) { return a/gcd(a,b)*b;}
int const INF = 1001001001;
ll const MOD = 1000000007;


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

int N;
cin >> N;
vl T(N);
rep(i,N) cin >> T[i];

ll ans = T[0];
for(int i = 1;i <N;i++) {
    ans = lcm(ans,T[i]);
}

cout << ans << endl;

return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
typedef long long ll;
struct node{
    ll a,b;
} Node[N];

bool cmp(node a,node b){
    return a.a < b.a;
}

int main(){
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++){
        scanf("%lld%lld",&Node[i].a,&Node[i].b);
    }
    sort(Node,Node+n,cmp);
    ll ans = 0;
    int i = 0;
    while(m > 0){
        if(m >= Node[i].b){
            m -= Node[i].b;
            ans += Node[i].b * Node[i].a;
        }
        else ans += Node[i].a * m,m = 0;
        i ++;
    }
    printf("%lld\n",ans);


    return 0;
}


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

int main(){
  int n;
  cin >> n;
  string s;
  cin >> s;
  int a=0;
  for(int i=2;i<n;i++){
    if(s.at(i)=='C'){
      if(s.at(i-1)=='B'){
        if(s.at(i-2)=='A'){
          a++;
        }
      }
    }
  }
  cout << a << endl;
}


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

using namespace std;

int main(){
	int x1, y1, x2,y2;
	cin>>x1>>y1>>x2>>y2;
	cout<<x2+(y1-y2)<<' '<<y2-(x1-x2)<<' '<<x2+(y1-y2)+(x1-x2)<<' '<<y2-(x1-x2)+(y1-y2)<<endl;
	
	
	
	return 0;
	}


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

int main(){
  string S; cin>>S;
  int cnt=0,n=S.length();
  rep(i,n) cnt+=(S[i]=='0');
  cout<<min(n-cnt,cnt)*2<<endl;
  return 0;
}


Measured memory_bytes: 512
#include <iostream>
#include <iomanip>
#include <cassert>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <map>
#include <bitset>
#include <sstream>
#include <istream>
#include <cmath>
#include <cstdio>

using namespace std;

#define vci vector<int>
#define vcs vector<string>
#define pb push_back
#define sz size()
#define mapii map<int, int>
#define mapci map<char, int>
#define mapsi map<string, int>
#define all(x) x.begin(), x.end()
#define minit(a, i) memset(a, i, sizeof(a));

#define for_(i, a, b) for (int i=(int)a; i<(int)b; i++)
#define for_d(i, a, b) for (int i=(int)a-1; i>=b; i--)
#define for_r(i, a, b, c) for (int i=(int)a; i<(int)b; i += c)
#define for_dr(i, a, b, c) for (int i=(int)a-1; i>=b; i -= c)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)

template <class T> int __builtin_popcount(T n) { return n ? 1 + __builtin_popcount(n & (n - 1)) : 0; }

typedef long long ll;
typedef double D;

const int iINF = 2147483647;
const ll lINF = 9223372036854775807;

template <class T> inline void dbg(T t) { cout << t << endl; }


int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,-1,1};


void solve(vcs& board, int bi, int bj) {
	board[bi][bj] = '0';
	
	for_(d, 0, 4) {
		for_(k, 1, 4) {
			int ni = bi + dx[d]*k, nj = bj + dy[d]*k;
			if (ni<0 || ni>=8 || nj<0 || nj>=8) continue;
			
			if (board[ni][nj]=='1') solve(board, ni, nj);
		}
	}
}

int main() {
	int n; cin >> n;
	
	for_(i, 0, n) {
		vcs board(8);
		for_(j, 0, 8) cin>>board[j];
		
		int bi, bj; cin>>bj>>bi;
		
		cout << "Data " << i+1 << ":" << endl;
		solve(board, bi-1, bj-1);
		for_(j, 0, 8) cout << board[j] << endl;
	}
	
	return 0;
}

Measured memory_bytes: 1216
#include <bits/stdc++.h>
using namespace std;
#define _GLIBCXX_DEBUG
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(v) v.begin(), v.end()
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
using ll = long long;
using vi = vector<int>; using vvi = vector<vi>;
const ll MOD = 1e9+7; ll INF = 1LL << 60;
const vi d8x = {1, 0, -1, 0, 1, -1, -1, 1}; vi d8y = {0, 1, 0, -1, 1, 1, -1, -1};
const vi d4x = {1, 0, -1, 0}; vi d4y = {0, 1, 0, -1};
//---------------------------------------

int main(){
    ll l,r; cin>>l>>r;
    if(r-l>=2019){
        cout<<0<<endl;
        return 0;
    }
    ll ans=INF;
    for(ll i=l; i<=r; i++){
        for(ll j=i+1; j<=r; j++){
            ans=min(ans, i*j%2019);
        }
    }
    cout<<ans<<endl;
    return 0;
}

Measured memory_bytes: 256
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		String N;
		String ans;

		N = sc.next();

		if(N.charAt(0) == N.charAt(2)){
			ans = "Yes";
		}else{
			ans = "No";
		}

		System.out.println(ans);

	}

}

Measured memory_bytes: 21844
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


const ull B1 = 9973;
const ull B2 = MOD;

int W,H,P;
ull bin_table[64][6],image_table[1000][1000],pattern_table[8][1000][1000],hash_table[1000][1000],tmp[1000][1000];
char buf[1000];
map<ull,bool> MAP;


int getNUM(char ch){

	if(ch >= 'A' && ch <= 'Z'){
		return ch-'A';
	}else if(ch >= 'a' && ch <= 'z'){
		return ch-'a'+26;
	}else if(ch >= '0' && ch <= '9'){
		return ch-'0'+52;
	}else if(ch == '+'){
		return 62;
	}else{
		return 63;
	}
}

void compute_hash(ull a[1000][1000], int n, int m){

	ull t1 = 1;
	for(int j = 0; j < P; j++)t1 *= B1;

	for(int i = 0; i < n; i++){
		ull e = 0;
		for(int j = 0; j < P; j++)e = e*B1+a[i][j];

		for(int j = 0; j+P <= m; j++){
			tmp[i][j] = e;
			if(j+P < m)e = e*B1-t1*a[i][j]+a[i][j+P];
		}
	}

	ull t2 = 1;
	for(int i = 0; i < P; i++)t2 *= B2;

	for(int j = 0; j+P <= m; j++){
		ull e = 0;
		for(int i = 0; i < P; i++)e = e*B2 + tmp[i][j];

		for(int i = 0; i+P <= n; i++){
			hash_table[i][j] = e;
			if(i+P < n)e = e*B2-t2*tmp[i][j]+tmp[i+P][j];
		}
	}
}

void func(){

	MAP.clear();

	int col;

	for(int row = 0; row < H; row++){
		scanf("%s",buf);
		col = 0;
		for(int num = 0; num < (W+5)/6; num++){
			for(int i = 0; i < 6; i++){
				image_table[row][col++] = bin_table[getNUM(buf[num])][5-i];
			}
		}
	}

	for(int row = 0; row < P; row++){
		scanf("%s",buf);
		col = 0;
		for(int num = 0; num < (P+5)/6; num++){
			for(int i = 0; i < 6; i++){
				pattern_table[0][row][col++] = bin_table[getNUM(buf[num])][5-i];
			}
		}
	}

	for(int i = 1; i <= 3; i++){
		for(int row = 0; row < P; row++){
			for(int col = 0; col < P; col++){
				pattern_table[i][col][(P-1)-row] = pattern_table[i-1][row][col];
			}
		}
	}

	for(int i = 0; i <= 3; i++){
		for(int row = 0; row < P; row++){
			for(int col = 0; col < P; col++){
				pattern_table[4+i][row][(P-1)-col] = pattern_table[i][row][col];
			}
		}
	}

	for(int i = 0; i < 8; i++){

		compute_hash(pattern_table[i],P,P);

		auto at = MAP.find(hash_table[0][0]);
		if(at != MAP.end())continue;

		MAP[hash_table[0][0]] = true;
	}

	int ans = 0;
	compute_hash(image_table,H,W);
	for(int row = 0; row+P <= H; row++){
		for(int col = 0; col+P <= W; col++){

			auto at = MAP.find(hash_table[row][col]);
			if(at != MAP.end())ans++;
		}
	}

	printf("%d\n",ans);
}


void make_bin_table(){

	for(int num = 0; num <= 63; num++){
		for(int loop = 0; loop < 6; loop++){
			if(num & (1 << loop)){
				bin_table[num][loop] = 1;
			}else{
				bin_table[num][loop] = 0;
			}
		}
	}
}


int main(){

	make_bin_table();

	while(true){
		scanf("%d %d %d",&W,&H,&P);
		if(W == 0 && H == 0 && P == 0)break;

		func();
	}

	return 0;
}



Measured memory_bytes: 30052
import Data.List
import Data.Char
import Data.Functor
import qualified Data.ByteString.Char8 as B

main = do
  xs <- getInts
  putStr . unlines $ map show $ take 3 (reverse . sort $ xs)

getInts :: IO[Int]
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getContents

Measured memory_bytes: 3484
# https://atcoder.jp/contests/abc099/tasks/abc099_d
# さまざまな合わせ技
# ダイクストラ、全探索

import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため



# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations

# from scipy.sparse.csgraph import dijkstra
# from scipy.sparse import csr_matrix, lil_matrix
# 0 まずはダイクストラでX→Yの最小コストを求めておく #えーーーーこれ想定されてないの？
# 1 座標ごとに3つのグループわけができる(n=1のときだけ場合分け
# 2 グループごとに色をカウント
# 3 各グループの色を仮定して全探索

N, C = read_ints()
D = read_matrix(C)
# D = csr_matrix(D)
# D = dijkstra(D)


# 1 座標のグループわけ
Cmap = read_matrix(N)

if N == 1:
    print(0)
    exit()

lsbymod = defaultdict(lambda: defaultdict(lambda: 0))
for i in range(N):
    for j in range(N):
        lsbymod[(i + j + 2) % 3][Cmap[i][j] - 1] += 1

# グループごとに色のカウント
# for k, v in lsbymod.items():
#     lsbymod[k] = Counter(v)

# 各グループの色を仮定して全探索


def ret_score(*arg):
    # 各仮定から違和感を計算
    ret = 0
    for i in range(3):
        for k, v in lsbymod[i].items():
            ret += v * D[k][arg[i]]
    return ret


ans = 2**63
for a, b, c in permutations(range(C), 3):
    # print(a, b, c, ret_score(a, b, c))
    ans = min(ans, ret_score(a, b, c))

print(ans)


Measured memory_bytes: 45404
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define repone(i,n) for(int i=1;i<(int)(n);++i)
#define repo(i,o,n) for(int i=o;i<(int)(n);++i)
#define Rep(j,n) for(int j=0;j<(int)(n);++j)
#define Repo(j,o,n) for(int j=o;j<(int)(n);++j)
#define Repone(j,n) for(int j=1;j<(int)(n);++j)
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()
#define int long long
#define pb(a) push_back(a)
#define eraser(v,i) (v).erase(v.begin()+(i))
#define pbpair(a,b) push_back(make_pair(a,b))
#define MOD 1000000007
#define INF 9223372036854775807
#define pairint pair<int,int>
int euclidean_gcd(int a, int b) {
  if(a < b) return euclidean_gcd(b, a);
  int r;
  while ((r=a%b)) {
    a = b;
    b = r;
  }
  return b;
}
signed main()
{
int x=0,y=0,z=0,w=0,n=0,m=0,a=0,b=0;
std::cin >> x>>y>>z>>w;
std::cout << z-(w-y)<<" "<<w+(z-x)<<" "<<x-(w-y)<<" "<<y+(z-x) << '\n';
}



Measured memory_bytes: 384
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<string>
#include<sstream>
#include<vector>
#define inf 2147483647
#define cin1(x) scanf("%d",&x)
#define cin2(x,y) scanf("%d%d",&x,&y)
#define cin3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define rep(i,a,b) for(int i=a;i<b;i++)
#define repb(i,a,b) for(int i=a;i<=b;i++)
#define rr read()
#define ll long long
#define CloseIo ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define ll  long long 
using namespace std;
const int N = 1e5 +5;
int a[N];
int main() {
	int n;
	int mark=1;
	int maxx=0;
	cin>>n;
	rep(i,0,n){
		cin>>a[i];
		if(!i)
			maxx=a[i];
		if(a[i]>maxx)
			maxx=a[i];
		else if(maxx-a[i]>=2)
			mark=0;
	}
	if(mark)
		cout<<"Yes\n";
	else
		cout<<"No\n";
    return 0;
}

Measured memory_bytes: 640
import java.io.PrintStream;
import java.util.Scanner;
import java.util.stream.LongStream;

public class Main {

	static int F(long A, long B) {
		return Math.max(Long.toString(A).length(), Long.toString(B).length());
	}

	static void exec(Scanner in, PrintStream out) {
		long N = in.nextLong();
		int min = LongStream.rangeClosed(1, (long) Math.sqrt(N))
				.filter(A -> N % A == 0).mapToInt(A -> F(A, N / A)).min()
				.getAsInt();
		out.println(min);
	}

	public static void main(String[] args) {
		exec(new Scanner(System.in), System.out);
	}

}


Measured memory_bytes: 28628
L = int(input())
r = 0
answer = []

while 2**r <= L:
    r += 1
N = r

for i in range(1,r):
    answer.append([i,i+1,0])
    answer.append([i,i+1,2**(i-1)])


for t in range(N-1,0,-1):
    if L - 2**(t-1) >= 2**(r-1):
        answer.append([t,N,L-2**(t-1)])
        L -= 2**(t-1)

answer.insert(0,[N,len(answer)])

for ans in answer:
    print(*ans)

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

using namespace std;

int main()
{
    int N, K, A = 2, B = 1, Sum = 1;
    cin >> N >> K;

    for (int i = 0; i < N; i++)
    {
        A = Sum * 2;
        B = Sum + K;

        Sum = min(A, B);
    }

    cout << Sum;
}

Measured memory_bytes: 256
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
    ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}
use std::collections::HashMap;
use std::cmp::{max,min};
fn main(){
    input!{
        n:usize,
        an:[i64;n],
    }
    let mut left = vec![0;n+1];
    let mut right = vec![0;n+1];
    for j in 0..n {left[j+1] = gcd(left[j],an[j]);}
    for j in (0..n).rev() {right[j] = gcd(right[j+1],an[j]);} 
    let mut ans = 0;
    for j in 0..n {
        ans = max(ans,gcd(left[j],right[j+1]));
    }
    println!("{}",ans);
}
fn gcd(a:i64,b:i64) -> i64 {
    if b == 0 {
        return a;
    }
    if a % b == 0 {
        b 
    } else {
        gcd(b,a%b)
    }
}

Measured memory_bytes: 6396
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    int n;
    cin >> n;
    
    vector<int> d = vector<int>(n, 0);
    for (int i = 0; i < n; ++i)
    {
        cin >> d[i];
    }
    
    sort(d.begin(), d.end());
    int now = d[0];
    int ret = 1;
    for (int i = 0; i < n; ++i)
    {
        if (d[i] > now)
        {
            now = d[i];
            ret++;
        }
    }
    
    cout << ret << endl;
    
    return 0;
}

Measured memory_bytes: 256
arr = list(map(int,input().split()))

arr.sort(reverse=True)

arr2 = list(arr)
count = 0

for i in range(3):
    arr2[i] = arr[0] - arr2[i] 

for j in range(3):
    if (arr2[j] != 0) and (arr2[j] % 2 == 1):
        count += 1

if (count == 0) or (count == 2):
    print(int(sum(arr2) / 2))
else:
    print(int(sum(arr2) // 2 + 2))

Measured memory_bytes: 3064
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define pii pair<int, int>
#define F first
#define S second
#define pb push_back

const int P = 1e9+7;

using namespace std;

int n, h, w;
pii p[3030];
int dp[3030], f[202020];

int add(int a, int b){
	a += b;
	if(a>=P) return a-P;
	return a;
}
int sbt(int a, int b){
	a -= b;
	if(a<0) return a+P;
	return a;
}
int mul(int a, int b){
	return (ll)a*b%P;
}

int pow(int a, int b){
	if(b==0) return 1;
	if(b&1) return mul(a, pow(a, b-1));
	return pow(mul(a, a), b/2);
}

int abCb(int a, int b){
	return mul(f[a+b], mul(pow(f[b], P-2), pow(f[a], P-2)));
}

int main(){


	cin >> h >> w >> n;
	for(int i=1; i<=n; i++) cin >> p[i].F >> p[i].S;
	p[n+1] = {h, w};
	sort(p, p+n+2);

	f[0] = 1;
	for(int i=1; i<=h+w; i++) f[i] = mul(f[i-1], i);

	dp[0] = 1;

	for(int i=1; i<n+2; i++){
		dp[i] = abCb(p[i].F-1, p[i].S-1);
		for(int j=1; j<i; j++){
			if(p[j].S <= p[i].S){
				int pth = mul(dp[j], abCb(p[i].F-p[j].F, p[i].S-p[j].S));
				dp[i] = sbt(dp[i], pth);
			}
		}
	}

	cout << dp[n+1] << endl;

	return 0;
}


Measured memory_bytes: 1024
#include<bits/stdc++.h>
using namespace std;
#define FOR(i,l,r) for(size_t i=(l);i<(r);++i)
#define REP(i,n) FOR(i,0,n)
#define int long long

signed main(){
    int X,Y,A,B,C;
    cin >>X>>Y>>A>>B>>C;
    int ans =0;
    vector<int>pvec(A);
    vector<int>qvec(B);
    REP(i,A){
        cin >>pvec[i];
    }
    REP(i,B){
        cin >>qvec[i];
    }
    sort(pvec.rbegin(),pvec.rend());
    sort(qvec.rbegin(),qvec.rend());
    vector<int>memo;
    REP(i,X){
        memo.push_back(pvec[i]);
    }
    REP(i,Y){
        memo.push_back(qvec[i]);
    }
    REP(i,C){
        int a;
        cin >>a;
        memo.push_back(a);
    }
    sort(memo.rbegin(),memo.rend());
    REP(i,X+Y){
        ans+=memo[i];
    }
    cout<<ans<<endl;
}

Measured memory_bytes: 8048
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;
int INF=1<<29;

class Weighted_Unionfind{
public:
	vector<int> par;
	vector<int> size;
    vector<int> diff_weight;

	Weighted_Unionfind(int n){
		par=vector<int>(n);
		size=vector<int>(n,1);
        diff_weight=vector<int>(n);
		for(int i=0;i<n;i++) par[i]=i;
	}

	int root(int x){
		if(par[x]==x){
            return x;
        }else{
            int r=root(par[x]);
            diff_weight[x]+=diff_weight[par[x]];
            return par[x]=r;
        }
	}

    //ノードxの重みを求める
    int weight(int x){
        root(x);
        return diff_weight[x];
    }

    //x,y間を求める
    int diff(int x,int y){
        if(root(x)!=root(y)) return 0;  //x,yが異なるグループに属す場合
        return weight(y)-weight(x);
    }

    //x→yのコストがw
	bool merge(int x,int y,int w){
        w+=weight(x);
        w-=weight(y);
		x=root(x);
		y=root(y);
		if(par[x]==par[y]){
			if(diff(x,y)!=w) return false;
		}
		if(size[y]>size[x]){
            swap(x,y);
            w=-w;
        }
		par[y]=x;
		size[x]+=size[y];
        diff_weight[y]=w;
		return true;
	}
};

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int N,M; //(頂点数)
	cin>>N>>M;
	vector<int> L(M),R(M),D(M);
	for(int i=0;i<M;i++) cin>>L[i]>>R[i]>>D[i];
	Weighted_Unionfind Uni(N+1);
	for(int i=0;i<M;i++){
		if(!Uni.merge(L[i],R[i],D[i])){
			cout<<"No\n";
			return 0;
		}
	}
	cout<<"Yes\n";
	return 0;
}

Measured memory_bytes: 3840