akhauriyash/Code-Regression huggingface dataset:
#include<iostream>
#include<map>
#include<set>
#include<string>
#include<algorithm>
#include<cmath>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;

const int inf = 999999999;
const double pi = acos(-1);

#define rep(i,m,n) for(int i = (m); i < (int)(n); i++)
#define mod(i) (i%(ll)(1e9 + 7))


int main(){
	int a,b,c;
	cin >> a >>b >> c;
    ll sum = a,cnt = 0;
    
	while(sum % b != c){
        sum += a;
        cnt++;
        if(cnt > 100000){
            cout << "NO" << endl;
            return 0;
        }
	}
	cout << "YES" << endl;
	return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <array>
#include <functional>
#include <algorithm>
using namespace std;

int main() {
  int64_t n;
  array<int64_t, 3> abc;
  cin >> n >> abc[0] >> abc[1] >> abc[2];
  string out, s[n];
  for (int i = 0; cin >> s[i]; ++i) {}
  function<bool(string*, array<int64_t, 3>, int)> solve = [&](string* s, auto abc, int i) {
    if (i == n) {
      return true;
    }
    --abc[s[i].front() - 'A'];
    ++abc[s[i].back() - 'A'];
    if (abc[0] >= 0 && abc[1] >= 0 && abc[2] >= 0 && solve(s, abc, i + 1)) {
      out.push_back(s[i].back());
      out.push_back('\n');
      return true;
    }
    abc[s[i].front() - 'A'] += 2;
    abc[s[i].back() - 'A'] -= 2;
    if (abc[0] >= 0 && abc[1] >= 0 && abc[2] >= 0 && solve(s, abc, i + 1)) {
      out.push_back(s[i].front());
      out.push_back('\n');
      return true;
    }
    --abc[s[i].front() - 'A'];
    ++abc[s[i].back() - 'A'];
    return false;
  };
  if (solve(s, abc, 0)) {
    reverse(begin(out), end(out));
    cout << "Yes\n" << out;
  } else {
    cout << "No\n";
  }
  return 0;
}


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

using namespace std;

int main(){
    char s[100001];
    int ans=0;
    scanf("%s",s);
    for (int i=0;i<strlen(s);i++) {
        if (i%2==0) ans+=(s[i]=='g'?0:-1);
        if (i%2 && s[i]=='g') ans++;
    }
    printf("%d\n",ans);
    return 0;
}


Measured memory_bytes: 384
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def ep(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        ep(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N):
    c = Counter()
    for i in range(1, N+1):
        s = str(i)
        c[int(s[0])*10+int(s[-1])] += 1

    ans = 0
    for i, j in product(range(1, 10), repeat=2):
        ans += c[10*i+j] * c[10*j+i]

    return ans


def main():
    N = read_int()
    print(slv(N))


if __name__ == '__main__':
    main()


Measured memory_bytes: 78508
# n = int(input())
n, k = map(int, input().split())
# l = list(map(int, input().split()))
d = []
a = []
for i in range(k):
    d.append(int(input()))
    a.append(list(map(int, input().split())))

snuke = [0] * (n+1)

for i in range(k):
    for j in range(d[i]):
        snuke[a[i][j]] += 1
ans = -1
for s in snuke:
    if s==0:
        ans += 1

print(ans)

Measured memory_bytes: 9284
N,W=map(int,input().split())
w,v=[0]*N,[0]*N

for i in range(N):
    w[i],v[i]=map(int,input().split())
V=sum(v)
dp=[[float('inf') for i in range(V+1)] for j in range(N+1)]

dp[0][0]=0
for i in range(N):
    for j in range(V+1):
        if j-v[i]>=0:
            dp[i+1][j]=dp[i][j-v[i]]+w[i]
        dp[i+1][j]=min(dp[i][j],dp[i+1][j])

for j in range(V+1):
    if dp[N][j]<=W:
        res=j
print(res)

Measured memory_bytes: 318704
package main

import (
	"fmt"
	"strconv"
)

func isPalindrom(x int) bool {
	s := strconv.Itoa(x)
	n := len(s)
	for i := 0; i < n/2; i++ {
		if s[i] != s[n-1-i] {
			return false
		}
	}
	return true
}

func main() {
	var a, b int
	fmt.Scan(&a, &b)
	ans := 0
	for i := a; i <= b; i++ {
		if isPalindrom(i) {
			ans++
		}
	}
	fmt.Println(ans)
}


Measured memory_bytes: 1024
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cctype>
#include<math.h>
#include<string>
#include<string.h>
#include<stack>
#include<queue>
#include<vector>
#include<utility>
#include<set>
#include<map>
#include<stdlib.h>
#include<iomanip>
#include<deque>

using namespace std;

#define ll long long
#define ld long double
#define EPS 0.0000000001
#define INF 1e9
#define LINF (ll)INF*INF
#define MOD 1000000007
#define rep(i,n) for(int i=0;i<(n);i++)
#define loop(i,a,n) for(int i=a;i<(n);i++)
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)

#define int ll //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int,int> pii;
typedef vector<pii> vp;
typedef deque<int> di;

int gcd(int a, int b){
    if(b==0) return a;
    return gcd(b,a%b);
}
int lcm(int a, int b){
    return a*b/gcd(a,b);
}

signed main(void) {
    int i,j;
    int n;
    cin >> n;
    string s;
    cin >> s;
    int ans = 0;
    rep(_,n){
        string in;
        cin >> in;
        rep(i,in.size())if(in[i] == s[0]){
            loop(j,i+1,in.size())if(in[j] == s[1]){
                int ind = j + j-i;
                bool c = true;
                loop(k,2,s.size()){
                    if(ind >= in.size() || in[ind] != s[k]){
                        c = false;
                        break;
                    }else{
                        ind += j-i;
                    }
                }
                if(c){
                    ans++;
                    i = INF;
                    break;
                }
            }
        }
    }
    cout << ans << endl;
}



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

int main(int argc, char const *argv[])
{
	int n,q;
	string s;
	cin>>n>>q>>s;
	int ans1[s.size()+5]={},ans2[s.size()+5]={};
	for (int i = 1; i < n; ++i)
	{
		ans1[i]=ans1[i-1];
		if (s.at(i-1)=='A'&&s.at(i)=='C')
		{
			++ans1[i];
		}
	}
	for (int i = 2; i <= n; ++i)
	{
		ans2[i]=ans2[i-1];
		if (s.at(i-2)=='A'&&s.at(i-1)=='C')
		{
			++ans2[i];
		}
	}
	int l,r;
	for (int i = 0; i < q; ++i)
	{
		cin>>l>>r;
		cout<<ans2[r]-ans1[l-1]<<endl;
	}
	return 0;
}


Measured memory_bytes: 1792
def solve(string):
    s, k = string.split()
    k = int(k)
    chars = sorted(set(s))
    exists = []

    def dfs(base):
        exists.append(base)
        if len(exists) >= k:
            return
        for c in chars:
            if base + c in s:
                dfs(base + c)

    for c in chars[:3]:
        dfs(c)

    return exists[k - 1]


if __name__ == '__main__':
    print(solve('\n'.join([input(), input()])))


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

#define REP(i,s,n) for(int i=s;i<n;++i)
#define rep(i,n) REP(i,0,n)
#define ALL(x) x.begin(),x.end()
#define EPS (1e-8)
#define equals(a,b) (fabs((a)-(b))<EPS)

using namespace std;

typedef long long ll;
bool LTE(double a,double b) { return equals(a,b) || a < b; }
bool LT(double a,double b) { return !equals(a,b) && a < b; }

void compute() {

}

int main() {
  int n;
  cin >> n;
  vector<int> a(n);
  rep(i,n) cin >> a[i];
  int maxi = 0;
  rep(i,n) {
    int cnt = 0;
    while( a[i] % 2 == 0 ) {
      a[i] /= 2;
      ++cnt;
    }
    maxi += cnt;
  }
  cout << maxi << endl;
  compute();
  return 0;
}

Measured memory_bytes: 256
#include <cstdio>
#include <utility>
#include <bitset>
#include <iostream>
using namespace std;

#define gcu getchar_unlocked
#define pcu putchar_unlocked
#define _T template <typename T>
#define _HT template <typename H, typename... T>
#define _il inline
#define _in _il int in
#define _sc _il bool scan
_T T in(int c){T n=0;bool m=false;if(c=='-')m=true,c=gcu();
	do{n=10*n+(c-'0'),c=gcu();}while(c>='0');return m?-n:n;} //&&c<='9'
_in() {return in<int>(gcu());}
_T T scan(T &n){int c=gcu();return c==EOF?false:(n=in<T>(c),true);}
_sc(char &c){c=gcu();gcu();return c!=EOF;}
#ifdef _GLIBCXX_STRING
_sc(string &s){int c;s="";
	for(;;){c=gcu();if(c=='\n'||c==' ')return true;else if(c==EOF)return false;s+=c;}}
#endif
_HT _sc(H &h, T&&... t){return scan(h)&&scan(t...);}
#define _vo _il void out
#define _vl _il void outl
_vo(const char *s){while(*s)pcu(*s++);}
_vo(char c){pcu(c);}
#ifdef _GLIBCXX_STRING
_vo(string s){for(char c:s)pcu(c);}
#endif
_T _vo(T n){static char buf[20];char *p=buf;
	if(n<0)pcu('-'),n*=-1;if(!n)*p++='0';else while(n)*p++=n%10+'0',n/=10;
	while (p!=buf)pcu(*--p);}
_vl(){out('\n');}
#ifdef _GLIBCXX_VECTOR
_T _vo(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);outl();}
#endif
_HT _vo(H&& h, T&&... t){out(h);out(move(t)...);}
template <typename... T> _vl(T&&... t){out(move(t)...);outl();}

int main() {
	bitset<32> a = in(), b = in();
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout << (a & b) << endl << (a | b) << endl << (a ^ b) << endl;
}


Measured memory_bytes: 3228
fun main(args: Array<String>) {
    val (n, m) = readLine()!!.split(' ').map { it.toInt() }
    val parent = IntArray(n) { it }

    fun find(x: Int): Int {
        if (x != parent[x]) {
            parent[x] = find(parent[x])
        }
        return parent[x]
    }

    repeat(m) {
        val (a, b) = readLine()!!.split(' ').map { it.toInt() - 1 }
        val px = find(a)
        val py = find(b)
        if (px < py) {
            parent[py] = px
        } else {
            parent[px] = py
        }
    }
    val ans = HashMap<Int, Int>()
    for (i in 0 until n) {
        val key = find(i)
        ans[key] = ans.getOrDefault(key, 0) + 1
    }
    println(ans.map { it.value }.max())
}

Measured memory_bytes: 67184
#include <iostream>

using namespace std;

int main() {
	double n;
	while (cin >> n) {
		if (n <= 48.0) cout << "light fly" << endl;
		else if (n <= 51.0) cout << "fly" << endl;
		else if (n <= 54.0) cout << "bantam" << endl;
		else if (n <= 57.0) cout << "feather" << endl;
		else if (n <= 60.0) cout << "light" << endl;
		else if (n <= 64.0) cout << "light welter" << endl;
		else if (n <= 69.0) cout << "welter" << endl;
		else if (n <= 75.0) cout << "light middle" << endl;
		else if (n <= 81.0) cout << "middle" << endl;
		else if (n <= 91.0) cout << "light heavy" << endl;
		else{cout << "heavy" << endl;}
	}
return 0;
}

Measured memory_bytes: 0
#include<stdio.h>
#define NUMBER 10

int main(void){
        int i,j,temp,num[NUMBER],count=0;

        for(i = 0;i < NUMBER;i++){
                scanf("%d",&num[i]);
        }
        for(i = 0;i < NUMBER;i++){
                for(j = 0;j < (NUMBER-1)-i;j++){
                        if(num[j] > num[j+1]){
                                temp = num[j];
                                num[j] = num[j+1];
                                num[j+1] = temp;
                        }
                }
        }

        for(i = 0;i < NUMBER/2;i++){
                temp = num[i];
                num[i] = num[(NUMBER-1)-i];
                num[(NUMBER-1)-i] = temp;
        }

        for(j = 0;j < 3;j++){
                printf("%d\n",num[j]);
        }

        return 0;
}

Measured memory_bytes: 600
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>

#include <iostream>
#include <complex>
#include <string>
#include <algorithm>
#include <numeric>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>

#include <functional>
#include <cassert>

typedef long long ll;
using namespace std;

#ifndef LOCAL
#define debug(x) ;
#else
#define debug(x) cerr << __LINE__ << " : " << #x << " = " << (x) << endl;

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

template <typename T>
ostream &operator<<(ostream &out, const vector<T> &v) {
  out << '{';
  for (const T &item : v) out << item << ", ";
  out << "\b\b}";
  return out;
}
#endif

#define mod 1000000007 //1e9+7(prime number)
#define INF 1000000000 //1e9
#define LLINF 2000000000000000000LL //2e18
#define SIZE 200010


int main(){
  int N, M, Q;
  ll s[SIZE], t[SIZE];

  scanf("%d%d%d", &N, &M, &Q);

  for(int i=1;i<=N;i++) scanf("%lld", s+i);
  for(int i=1;i<=M;i++) scanf("%lld", t+i);
  s[0] = -LLINF;
  t[0] = -LLINF;
  s[N+1] = LLINF;
  t[M+1] = LLINF;

  N += 2;
  M += 2;

  for(int i=0;i<Q;i++){
    ll x;
    ll ans = LLINF;

    scanf("%lld", &x);

    ll *p = lower_bound(s, s+N, x);
    ll *q = lower_bound(t, t+M, x);

    ll a = abs(x - *p);
    ll b = abs(x - *(p-1));
    ll c = abs(x - *q);
    ll d = abs(x - *(q-1));

    ans = min(ans, max(a, c));
    ans = min(ans, max(b, d));
    ans = min(ans, min(a, b) + min(c, d) + min({a, b, c, d}));

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

  return 0;
}


Measured memory_bytes: 4096
n, k = map(int, input().split())
dict = {}
for _ in range(k):
    d = int(input())
    a = list(map(int, input().split()))
    # print(d)
    for i in a:
        # print(i)
        if i in dict:
            dict[i] = dict[i] + 1
        else:
            dict[i] = 1
# print(dict)
# print(len(dict.keys()))
print(n - len(dict.keys()))


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

int main(){
  int T[1010][1010], r, c;
    
  cin >> r >> c;
  for ( int i = 0; i < r; i++ )
    for ( int j = 0; j < c; j++ ) cin >> T[i][j];
      
  for ( int i = 0; i <= r; i++ ) T[i][c] = 0;
  for ( int j = 0; j <= c; j++ ) T[r][j] = 0;
      
      for ( int i = 0; i < r; i++ ){
      for ( int j = 0; j < c; j++ ){
       T[i][c] += T[i][j];
       T[r][j] += T[i][j];
       T[r][c] += T[i][j];
      }
  }
    
    for ( int i = 0; i <= r; i++ ){
        for ( int j= 0; j <= c; j++ ){
            if ( j ) cout << " ";
            cout << T[i][j];
        }
        cout << endl;
    }
    return 0;
}   

Measured memory_bytes: 1560
import java.util.Arrays;
import java.util.Scanner;

//City Merger
public class Main{

	int n;
	String[] s;
	int[][] cut;
	int[][] dp;
	
	int get(int S, int last){
		if(dp[S][last]!=-1)return dp[S][last];
		int res = 1<<29;
		int ns = S-(1<<last);
		for(int j=0;j<n;j++){
			if(((ns>>j)&1)==0)continue;
			res = Math.min(res, get(ns, j)+s[last].length()-cut[j][last]);
		}
		return dp[S][last] = res;
	}
	
	void run(){
		Scanner sc = new Scanner(System.in);
		for(;;){
			n = sc.nextInt();
			if(n==0)break;
			String[] t = new String[n];
			for(int i=0;i<n;i++)t[i]=sc.next();
			boolean[] del = new boolean[n];
			for(int i=0;i<n;i++)for(int j=0;j<n;j++)if(i!=j&&t[i].contains(t[j]))del[j] = true;
			int N = 0;
			for(boolean f:del)if(!f)N++;
			s = new String[N];
			int id = 0;
			for(int i=0;i<n;i++)if(!del[i])s[id++]=t[i];
			n = N;
			cut = new int[n][n];
			for(int i=0;i<n;i++)for(int j=0;j<n;j++){
				for(int k=0;k<s[i].length();k++){
					if(s[j].startsWith(s[i].substring(k))){
						cut[i][j] = s[i].length()-k; break;
					}
				}
			}
			dp = new int[1<<n][n];
			for(int[]a:dp)Arrays.fill(a, -1);
			for(int i=0;i<n;i++)dp[1<<i][i] = s[i].length();
			int res = 1<<29;
			for(int i=0;i<n;i++)res = Math.min(res, get((1<<n)-1, i));
			System.out.println(res);
		}
	}
	
	public static void main(String[] args) {
		new Main().run();
	}
}

Measured memory_bytes: 17000
#include <iostream>

using namespace std;

int main(void)
{
  bool able=false;
  int N,Y;
  int k,kmin,kmax;
  
  cin>>N>>Y;
  Y/=1000;

  int X=Y-N;
  kmin=X/(-4);
  kmax=(-2)*X/9;

  /*  cout<<"X="<<X<<endl;
      cout<<kmin<<"<=k<="<<kmax<<endl;*/
  
  int l,m,n;
  for(k=kmin;k<=kmax;k++){
     l=4*k+X;
     m=-9*k-2*X;
     n=N-l-m;
     if(l>=0 && m>=0 && n>=0){
       able=true;
       /*cout<<"k="<<k<<endl;*/
       break;
     }
  }

  if(able)
    cout<<l<<' '<<m<<' '<<n<<endl;
  else
    cout<<"-1 -1 -1"<<endl;

    
  return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define FRE freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define all(v) (v).begin(),(v).end()
#define endl "\n"
#define int long long
#define rep(i,a,b) for(int i=a;i<b;i++)
#define per(i,a,b) for(int i=a;i>b;i--)
#define vi vector<int>
#define pii pair<int,int>
#define mii map<int,int>
#define SET(A,VAL) memset(A, VAL, sizeof(A))
#define ff first
#define ss second
#define pb push_back
#define eb emplace_back
#define trace1(x)                cerr<<#x<<": "<<x<<endl
#define trace2(x, y)             cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl
#define trace3(x, y, z)          cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl
#define trace4(a, b, c, d)       cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl
#define trace5(a, b, c, d, e)    cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl
#define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl
const int MAX = 1e6+8;
const int sz = 1e5+5;
void f_io(){
    IOS;
}
int32_t main(){
    f_io();
    int t = 1;
    //cin>>t;
    while(t--){
        int sx,sy,tx,ty; cin>>sx>>sy>>tx>>ty;
        int dx = (tx - sx) ,dy = (ty - sy);
        cout<<string(dx,'R')<<string(dy,'U')<<string(dx,'L')<<string(dy,'D');
        cout<<'D'<<string(dx+1,'R')<<string(dy+1,'U')<<"LU"<<string(dx+1,'L')<<string(dy+1,'D')<<'R';
    }
}

Measured memory_bytes: 256
#define _USE_MATH_DEFINES
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <deque>
#include <climits>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
//#include <tuple>

#define INF INT_MAX>>1 
#define SIZE 100010
#define MOD 1000000007
#define rep(i, n) for(int i=0; i<(int)(n); i++)
#define rep2(i, from, to) for(int i=(from); i<(int)(to); i++)
#define all(obj) (obj).begin(), (obj).end()
#define lpair pair<ll, ll>
#define vint vector<ll>
#define vinput(name) for(int i=0; i<(int)(name.size()); i++) cin >> name[i];
#define voutput(name) for(int i=0; i<(int)(name.size()); i++) cout << name[i] << endl;
typedef long long ll;

using namespace std;

ll ans = 0;

int main(void){
	ll h, w; cin >> h >> w;
	if(h == 1 || w == 1){
		cout << 1 << endl;
		return 0;
	}
	ans = (w*h+1)/2;
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 256
n=int(input())
a=[0]*n
a=list(map(int,input().split()))
L={}
R={}
ans=0
for i in range(n):
    L.setdefault(i-a[i],0)
    R.setdefault(i+a[i],0)
    L[i-a[i]]+=1
    R[i+a[i]]+=1
    
    if (i-a[i] in R):
        ans+=R[i-a[i]]
        #print(ans,L[i-a[i]])
    if (i+a[i] in L):
        ans+=L[i+a[i]]

print(ans)
#print(L)
#print(R)

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

const int coin[4] = {10,50,100,500};
int cost,ans,a[4];
int ans_coin[4];

int check(int total){
  int res = 0;

  for(int i = 3 ; i >= 0 ; i--){
    res += total / coin[i];
    total %= coin[i];
  }

  return res;
}

void judge(){
  int ans = 1<<28;
  
  for(int i = 0 ; i <= a[0] ; i++){
    for(int j = 0 ; j <= a[1] ; j++){
      for(int k = 0 ; k <= a[2] ; k++){
	for(int l = 0 ; l <= a[3] ; l++){

	  int sum = coin[0]*i+coin[1]*j+coin[2]*k+coin[3]*l;
	  if(sum < cost) continue;

	  int want = sum - cost;
	  int tmp = check(want) - i - j - k - l;

	  if(tmp < ans){
	    ans_coin[0] = i; ans_coin[1] = j;
	    ans_coin[2] = k; ans_coin[3] = l;
	    ans = tmp;
	  }

	}
      }
    }
  }

}

int main(){  
  bool flg = false;
  while(cin >> cost ,cost){
    if(flg) cout << endl;
    for(int i = 0 ; i < 4 ; i++) cin >> a[i];
    judge();
    for(int i = 0 ; i < 4 ; i++){
      if(ans_coin[i]){
	cout << coin[i] << " " << ans_coin[i] << endl;
      }
    }
    flg = true;
  }

  return 0;
}

Measured memory_bytes: 1160
// J'aime
// Chemise Blanche

#include <bits/stdc++.h>
using namespace std;

#define int long long

#define ii pair<int,int>
#define fi first
#define sc second

#define all(x) (x).begin(),(x).end()
#define dbg(x) cerr << __LINE__ << " > " << #x << " = " << (x) << endl

void MAIN() {
  int n; cin >> n;
  set<int> s;
  for (int i = 0; i < n; i++) {
    int t; cin >> t;
    s.insert(t);
  }
  cout << s.size() << '\n';
}

signed main() {
#ifdef _DEBUG
  // freopen("in" , "r", stdin );
  // freopen("out", "w", stdout);
#endif
  ios::sync_with_stdio(0); cin.tie(0);
  int T = 1;
  // cin >> T;
  while (T--) MAIN();
}


Measured memory_bytes: 3664
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;

namespace AtCorder
{
	public class Program
	{
		static void Main(string[] args)
		{
			int n = int.Parse(Console.ReadLine());
			var a = Console.ReadLine().Split(' ').Select(long.Parse).ToArray();

			Array.Sort(a);
			long max = a.Max();
			var done = new bool[n];

			long target = 1;
			while (target < max) {
				target *= 2;
			}

			int ans = 0;
			while (target > 0) {
				var dic = new Dictionary<long, Queue<int>>();
				for (int i = 0; i < n; i++) {
					if (a[i] > target * 2) {
						break;
					}

					if (done[i]) {
						continue;
					}

					if (a[i] == target) {
						if (dic.ContainsKey(0) && dic[0].Count > 0) {
							ans++;
							int c = dic[0].Dequeue();
							done[c] = true;
							done[i] = true;
						} else {
							if (dic.ContainsKey(0) == false) {
								dic[0] = new Queue<int>();
							}

							dic[0].Enqueue(i);
						}
					} else if (a[i] < target) {
						long num = target - a[i];
						if (dic.ContainsKey(num) == false) {
							dic[num] = new Queue<int>();
						}

						dic[num].Enqueue(i);
					} else {
						long num = a[i] - target;
						if (dic.ContainsKey(num) && dic[num].Count > 0) {
							ans++;
							int c = dic[num].Dequeue();
							done[c] = true;
							done[i] = true;
						}
					}
				}

				target /= 2;
			}

			Console.WriteLine(ans);
		}
	}
}

Measured memory_bytes: 75204
//#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast,no-stack-protector") 
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//#pragma GCC optimize("unroll-loops")

#include <bits/stdc++.h>


#define ll long long
#define int ll
#define ull unsigned long long
#define ld long double
#define rep(i, l, r) for (int i = l; i < r; i++)
#define repb(i, r, l) for (int i = r; i > l; i--)
#define sz(a) (int)a.size()
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define pb push_back
#define mp(a, b) make_pair(a, b)
#define ret(a) {cout << a; exit(0);}

using namespace std;

mt19937 mrand(random_device{}()); 
const ll mod=1000000007;
int rnd(int x) { return mrand() % x;}
ll powmod(ll a,ll b,ll mod) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}

typedef pair < int , int > pii ;
typedef pair < long long  , long long > pll ;

const int N = 3e5 + 1;

int n, m, k;
int a[N], f[N];

main(){
	ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
	int a , b;
	cin >> a >> b;
	set < int > st;
	a = __gcd(a,b);
	for(int i = 2 ; i * i <= a ; i++){
		if(a % i == 0){
			st.insert(i);
			while(a % i == 0)
				a /= i;
		}
	}
	st.insert(1) ; st.insert(a);
	cout << sz(st);
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<bool> vb;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef map<int,int> mii;
typedef map<ll,ll> mll;
typedef vector<pii> vii;
typedef vector<pll> vll;
#define fi first
#define se second
#define pi 3.141592653589793
#define mod 998244353
#define pb push_back
#define all(v) v.begin(),v.end()
#define tc int t;cin>>t;while(t--)
#define pqmax priority_queue<int>
#define pqmin priority_queue<int,vi,greater<int>>
#define fast_io ios_base::sync_with_stdio(0), cin.tie(NULL)
#define tc_g int tt;cin>>tt;for(int ti=1;ti<=tt;ti++)
#define case_g "Case #"<<ti<<": "
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_multiset;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
typedef tree<int, int, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_map;

int main() {
	fast_io;
	ll n;
	cin >> n;
	vl a(n);
	for (int i = 0;i < n;i++)
		cin >> a[i];
	mii b;
	ll ans = 0;
	for (int i = n - 1;i >= 0;i--) {
		ans += b[a[i] + i];
		b[i - a[i]]++;
	}
	cout << ans << '\n';
}


Measured memory_bytes: 21856
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0; i<(n); i++)
#define rrep(i,n) for(int i=n-1; i>=0; i--)
#define reps(i,a,n) for(int i=a; i<(n); i++)

using namespace std;

typedef double R;
typedef pair<R, pair<R,R>> P;

#define X first
#define Y second.first
#define Z second.second

P add(P a, P b){
	return P({a.X+b.X, {a.Y+b.Y, a.Z+b.Z}});
}

P sub(P a, P b){
	return P({a.X-b.X, {a.Y-b.Y, a.Z-b.Z}});
}

P mul(P a, R b){
	return P({a.X*b, {a.Y*b, a.Z*b}});
}

R norm(P a){
	return a.X*a.X + a.Y*a.Y + a.Z*a.Z;
}

R dist(P a, P b){
	return sqrt(norm(sub(a,b)));
}


R f(P pa, P va, R ra, R rva,
	P pb, P vb, R rb, R rvb, R t){
	P a = add(pa, mul(va, t));
	P b = add(pb, mul(vb, t));

	R d = dist(a, b);
	R r = ra + rb - (rva+rvb)*t;
	return d-r;
}

P sp[203];
P sv[203];
R sr[203];
R srv[203];

R T[203][203];

const R INFR = 1e21;

R ret[203];


int main(){
	for(;;){
		int n;
		cin >> n;
		if(n==0) break;
		
		rep(i, n){
			R x,y,z, xx,yy,zz , r,rr;
			cin >> x >> y >> z >> xx >> yy >> zz >> r >> rr;
			sp[i] = {x,{y,z}};
			sv[i] = {xx,{yy,zz}};
			sr[i] = r;
			srv[i] = rr;
		}
		
		rep(i,n)reps(j,i,n){
			if(i==j){
				T[i][i] = sr[i]/srv[i];
				continue;
			}
			
			R a = 0, b = min(sr[i]/srv[i], sr[j]/srv[j]);
			R C,D;
			rep(TT, 99){
				R c = (a*2+b)/3;
				R d = (a+b*2)/3;

				C = f(sp[i], sv[i], sr[i], srv[i], sp[j], sv[j], sr[j], srv[j], c);
				D = f(sp[i], sv[i], sr[i], srv[i], sp[j], sv[j], sr[j], srv[j], d);
			
				if(C>D){
					a = c;
				}else{
					b = d;
				}
			}
			if(C>0){
				T[i][j] = T[j][i] = INFR;
				continue;
			}

			a = 0; b = b;
			rep(TT, 60){
				R c = (a+b)/2;
				C = f(sp[i], sv[i], sr[i], srv[i], sp[j], sv[j], sr[j], srv[j], c);
				if(C>0){
					a = c;
				}else{
					b = c;
				}
			}
			T[i][j] = T[j][i] = a;
		}
		/*
		rep(i,n){
			rep(j,n){
				if(T[i][j] >= INFR) printf("   #   ");
				else                printf("%6.3lf ", T[i][j]);
			}
			puts("");
		}puts(""); //*/

		rep(i,n) ret[i] = -INFR;
		for(;;){
			int I=-1, J=-1;
			R mi = INFR;
			rep(i,n)reps(j,i,n){
				if(ret[i] >=0 )continue;
				if(ret[j] >=0 )continue;

				if(mi > T[i][j]){
					mi = T[i][j];
					I=i; J=j;
				}
			}
			if(mi >= INFR) break;
			ret[J] = ret[I] = T[I][J];
		}
		rep(i,n) printf("%.10lf\n", ret[i]);
			

	}
	return 0;
}

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

N,M,S = Ints()
from collections import defaultdict
Graph  = defaultdict(list)

for i in range(M):
    u,v,a,b = Ints()
    Graph[u-1].append([v-1,a,b])
    Graph[v-1].append([u-1,a,b])

City = [0]*N
for i in range(N):
    c,d = Ints()
    City[i] = [c,d]

import heapq
que = []
# [time, nowhere, money, flag, visited]
heapq.heappush(que, [0, 0, min(S,5000)])
ans = [[10**16]*5001 for i in range(N)]
#Min = [[10**16]*5001 for i in range(N+1)]
#print(Graph)
while que != []:
    time, nowhere, money = heapq.heappop(que)
    #print('here',time,nowhere,money)
    if time <= ans[nowhere][money]:
        ans[nowhere][money] = time
        c,d = City[nowhere]
        if time+d < ans[nowhere][min(5000,money+c)]:
            ans[nowhere][min(5000,money+c)] = time+d
            #print('to',time+d, nowhere, min(5000,money+c))
            heapq.heappush(que, [time+d, nowhere, min(5000,money+c)])
        for (to,a,b) in Graph[nowhere]:
            if 0 <= money - a and time+b < ans[to][min(5000,money-a)]:
                ans[to][min(5000,money-a)] = time+b
                #print('to',time+b, to, min(5000,money-a))
                heapq.heappush(que, [time+b, to, min(5000,money-a)])

for i in range(1,N):
    print(min(ans[i]))

Measured memory_bytes: 116092
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define pb push_back
#define v vector
#define mp make_pair
#define repr(i,n) for(ll i=n-1;i>=0;i--)
#define rep(i,n) for(ll i=0;i<n;i++)
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
const int M = 1e9+7;
int ll_max=1e6;
int main() {
	// your code goes here
	IOS;
	ll n,x;
	
	ll i,j,m,k,sum=0;
      cin>>n>>k;
      ll a[n];
      rep(i,n){
            cin>>a[i];
      }
      sort(a,a+n);
      
      rep(i,k){
            sum+=a[i];
      }
      cout<<sum;
	return 0;
}

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

set < long long > divs (long long x) {
	set < long long > res;
	if (x != 1)
		res.insert(x);
	for (long long i = 2; i * i <= x; ++i) {
		if (x % i == 0) {
			res.insert(i);
			res.insert(x / i);
		}
	}
	return res;
}

signed main () {
	long long n;
	cin >> n;
	set < long long > a = divs(n);
	set < long long > ans = divs(n - 1);
	for (long long x: a) {
		long long t = n;
		while (t % x == 0) 
			t /= x;
		if (t % x == 1)
			ans.insert(x);
	}
	cout << int(ans.size()) << '\n';
}


Measured memory_bytes: 512
#!/usr/bin/env python3
import sys
    
def solve(N:str):
    print("A" if str.isupper(N) else "a")
    return 

# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = next(tokens)
    solve(N)

if __name__ == '__main__':
    main()

Measured memory_bytes: 9080
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;
typedef long long ll;
#define ALL(v) (v).begin(), (v).end()

ll calc(ll x) {
		if (x / 10 == 0) return 1;
		return calc(x / 10) + 1;
}

int main() {
		ll N;
		cin >> N;

		ll ans = 1e18;
		for (ll a = 1; a * a <= N; a++) {
				if (N % a != 0) continue;
				ans = min(ans, calc(N / a));
		}

		cout << ans << endl;
		return 0;
}


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


int main() {
    int N, M; cin >> N >> M;
    
    vector<vector<int>> A(M, vector<int>(2));
	   for (int i = 0; i < M; i++) {
        for (int j = 0; j < 2; j++) {
          cin >> A.at(i).at(j);
        }
      }
    
  multiset<int> total;
  	
  	for (int i = 0; i < M; i++){
      total.insert(A.at(i).at(0));
      total.insert(A.at(i).at(1));
    }
  
  	for (int i = 1; i <= N; i++){
      cout << total.count(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)
#define rep2(i, s, n) for (int i = (s); i < (int)(n); ++i)
#define chmax(a, b) a = max(a, b)
#define chmin(a, b) a = min(a, b)
#define fi first
#define se second
#define INF 1000000009
#define LLINF 1000000000000000009LL
using ll = long long;

int main(){
  int mp[19];
  mp[1]=mp[3]=mp[5]=mp[7]=mp[8]=mp[10]=mp[12]=1;
  mp[4]=mp[6]=mp[9]=mp[11]=2;
  mp[2]=3;
  int x,y;
  cin>>x>>y;
  if(mp[x]==mp[y])puts("Yes");
  else puts("No");
  return(0);
}


Measured memory_bytes: 256
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <queue>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <iostream>
#include <functional>
#include <unordered_map>
#include <unordered_set>
#include <list>
#include <bitset>

using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
#define Fi first
#define Se second
#define pb(x) push_back(x)
#define sz(x) ((int)(x).size())
#define rep(i, n) for(int i=0;i<n;i++)
#define all(x) (x).begin(), (x).end()
typedef tuple<int, int, int> t3;
typedef pair<ll, ll> pll;
typedef long double ldouble;
typedef pair<double, double> pdd;

int n, p[200020];

void solve(){
	scanf("%d", &n);
	for(int i=1;i<=n;i++) {
		scanf("%d", p+i);
		p[i] = p[i] == i;
	}
	int ans = 0;
	for(int i=1;i<=n;i++) {
		if(p[i]) p[i] = p[i+1] = 0, ++ans;
	}
	printf("%d\n", ans);
}

int main(){
	int Tc = 1; //scanf("%d\n", &Tc);
	for(int tc=1;tc<=Tc;tc++){
		// printf("Case #%d: ", tc);
		solve();
	}
	return 0;
}

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

#define rep(i,N) for(int i=0;i<N;i++)
#define rep2(i,N) for(int i=1;i<=N;i++)
using namespace std;
long long  INF=1e18;
long long mod=1e9+7;

//status unsolved

int main(){
    int n;
    cin>>n;
    cout<<(1000-n%1000)%1000<<endl;
    return 0;

}
/*


*/


Measured memory_bytes: 3596
N, K = map(int, input().split())
A = list(map(int, input().split()))
sumA = sum(A)

# 約数の全列挙
def divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)
    divisors.sort(reverse = True)  # ソート
    return divisors

ansList = divisors(sumA)
ans = 1

for div in ansList :
    res = [a % div for a in A]
    res.sort(reverse=True)

    sumCount = sum(res)
    b = 0
    for r in res :
        sumCount -= r
        b += div - r
        if sumCount == b :
            if sumCount <= K :
                ans = div
                break
    else :
        continue
    break

print(ans)

Measured memory_bytes: 3064
#include<stdio.h>
int main()
{
    int n;
    scanf("%d", &n);
    int i;
    int h[102];
    for (i = 0; i < n; i++)
        scanf("%d", &h[i]);
    int ans = 0;
    int k = 0, x;
    while (k == 0)
    {
        k = 1;
        x = 0;
        for (i = 0; i < n; i++)
        {
            if (h[i] > 0)
            {
                k = 0;
                if (x == 0)
                {
                    ans++;
                    x = 1;
                }
                h[i]--;
            }
            else
                x = 0;
        }
    }
    printf("%d\n", ans);
    return 0;
}

Measured memory_bytes: 128
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil
    #from operator import itemgetter

    #inf = 10**17
    #mod = 10**9 + 7

    k,x = map(int, input().split())
    l = x-k+1
    r = x+k-1
    res = []
    for i in range(l, r+1):
        if -1000000<=i<=1000000:
            res.append(i)
    print(*res)

if __name__ == '__main__':
    main()

Measured memory_bytes: 3316
import sys
input = sys.stdin.readline

base = 1999849216943526259
mod = (1 << 61) - 1

N = int(input())
S = [input().rstrip()[::-1] for _ in range(N)]
S.sort(key=lambda s: -len(s))
cnt = {}
ans = 0
one = [0] * 26
for s in S:
    n = len(s)
    if n == 1:
        ans += one[ord(s[0]) - ord('a')]
        continue
    hashes = [0] * (n - 1)
    hashes[0] = ord(s[0])
    for i in range(1, n - 1):
        hashes[i] = (hashes[i-1] * base + ord(s[i])) % mod
    if hashes[-1] in cnt:
        ans += cnt[hashes[-1]][ord(s[-1]) - ord('a')]
    found = [0] * 26
    found[ord(s[-1]) - ord('a')] = 1
    for i in range(n - 2, 0, -1):
        found[ord(s[i]) - ord('a')] = 1
        if hashes[i-1] not in cnt:
            cnt[hashes[i-1]] = [0] * 26
        for c in range(26):
            cnt[hashes[i-1]][c] += found[c]
    found[ord(s[0]) - ord('a')] = 1
    for c in range(26):
        one[c] += found[c]
print(ans)


Measured memory_bytes: 545044
#include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <math.h>
#include <sstream>
#include <numeric>
#include <string>
#include <cassert>
#include <bitset>

using namespace std;
typedef long long ll;

int main() {
  int N;
  cin >> N;
  map<string, int> counts;
  for (int i = 0; i < N; ++i) {
    string S;
    cin >> S;
    counts[S]++;
  }
  int max_v = 0;
  for (auto x : counts) {
    int v = x.second;
    max_v = max(max_v, v);
  }
  for (auto x : counts) {
    string k = x.first;
    int v = x.second;
    if (v == max_v) {
      cout << k << endl;
    }
  }
  return 0;
}


Measured memory_bytes: 25216
from collections import deque

class mf_graph:
    def __init__(self,N):
        self.N = N
        self.graph = [[] for _ in range(N)]
    
    def add_edge(self,v,w,cap):
        edge = [w,cap,None]
        edge[2] = rev_edge = [v,0,edge]
        self.graph[v].append(edge)
        self.graph[w].append(rev_edge)
    
    def bfs(self,s,t):
        self.level = [None]*self.N
        dq = deque([s])
        self.level[s] = 0
        while dq:
            v = dq.popleft()
            nlevel = self.level[v]+1
            for w,cap,_ in self.graph[v]:
                if cap and self.level[w] is None:
                    self.level[w] = nlevel
                    dq.append(w)
        return self.level[t] is not None
    
    def dfs(self,s,v,f):
        if v == s:
            return f
        for rev in self.it[v]:
            w,_,e = rev
            cap = e[1]
            if cap and self.level[w] is not None:
                if self.level[v] > self.level[w]:
                    d = self.dfs(s,w,min(f,cap))
                    if d:
                        e[1] -= d
                        rev[1] += d
                        return d
        return 0
    
    def flow(self,s,t,flow_limit=float('inf')):
        flow = 0
        while self.bfs(s,t):
            *self.it, = map(iter,self.graph)
            f = flow_limit
            while f:
                f = self.dfs(s,t,flow_limit-flow)
                flow += f
        return flow

    def min_cut(self,s):
        visited = [False]*self.N
        dq = deque([s])
        while dq:
            v = dq.pop()
            visited[v] = True
            for w,cap,_ in self.graph[v]:
                if cap and not visited[w]:
                    dq.append(w)


N,M = map(int, input().split())
S = [list(input()) for i in range(N)]
dc = mf_graph(N*M+2)

s =N*M
t = N*M+1
for i in range(N):
    for j in range(M):
        if (i+j) % 2 == 0:
            dc.add_edge(s,M*i+j,1)
        else:
            dc.add_edge(M*i+j,t,1)

for i in range(N):
    for j in range(M):
        if j+1 < M and S[i][j] == "." and S[i][j+1] == ".":
            u,v = M*i+j,M*i+j+1
            if (i+j) % 2 == 1:
                u,v = v,u
            dc.add_edge(u,v,1)
        if i+1 < N and S[i][j] == "." and S[i+1][j] == ".":
            u,v = M*i+j, M*(i+1)+j
            if (i+j) % 2 == 1:
                u,v = v,u
            dc.add_edge(u,v,1)

print(dc.flow(s,t,10**9))
for u in range(N*M+2):
    for v,cap,_ in dc.graph[u]:
        ui,uj = divmod(u,M)
        vi,vj = divmod(v,M)
        if (ui+uj) % 2 == 0 and cap == 0 and u != s and u != t and v != s and v!= t:
            if ui+1 == vi:
                S[ui][uj] = "v"
                S[vi][vj] = "^"
            elif ui == vi+1:
                S[ui][uj] = "^"
                S[vi][vj] = "v"
            elif uj+1 == vj:
                S[ui][uj] = ">"
                S[vi][vj] = "<"
            elif uj == vj+1:
                S[ui][uj] = "<"
                S[vi][vj] = ">"

for res in S:
    print("".join(res))

Measured memory_bytes: 18796
//https://atcoder.jp/contests/abc148/tasks/abc148_f
//F - Playing Tag on Tree
#include <bits/stdc++.h>
#if LOCAL
#include "dump.hpp"
#else
#define dump(...)
#endif
using namespace std;
using ll=long long;
#define FOR(i,a,b) for(ll i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
template<class T>bool chmax(T &a, const T &b) {if (a<b) { a=b; return 1; } return 0;}
template<class T>bool chmin(T &a, const T &b) {if (b<a) { a=b; return 1; } return 0;}

template< typename T >
struct edge {
	int src, to;
	T cost;
	edge(int _to, T _cost) : src(-1), to(_to), cost(_cost) {}
	edge(int _src, int _to, T _cost) : src(_src), to(_to), cost(_cost) {}
	edge &operator=(const int &x) {
		to = x;
		return *this;
	}
	operator int() const { return to; }
};

template< typename T>
struct node {
	vector<edge<T>> edges;
    ll dist[2]={};
};

template< typename T >
using Edges = vector< edge< T > >;
template< typename T >
using WeightedGraph = vector< node< T > >;
using UnWeightedGraph = vector< vector< int > >;
template< typename T >
using Matrix = vector< vector< T > >;

//木の直径,aoj_grl_5_a
template< typename T >
pair< T, int > tree_dfs(WeightedGraph< T > &g, int idx, int par, int fmsm=0) {
    assert(fmsm==0||fmsm==1);
    pair< T, int > ret(0, idx);
    for(auto &e : g[idx].edges) {
        if(e.to == par) continue;
        g[e.to].dist[fmsm]=g[idx].dist[fmsm]+e.cost; //...
        auto cost = tree_dfs(g, e.to, idx, fmsm);
        cost.first += e.cost;
        ret = max(ret, cost);
    } 
    return ret;
}

int main() {
#if LOCAL&01
    std::ifstream in("./test/sample-1.in"); //input.txt
    std::cin.rdbuf(in.rdbuf());
#else
    cin.tie(0);
    ios::sync_with_stdio(false);
#endif
    ll N,u,v; cin>>N>>u>>v;    
    WeightedGraph<ll> graph(N+1);
    FOR(i,0,N){
        ll a,b; cin>>a>>b;
        graph.at(a).edges.emplace_back(a,b,1);
        graph.at(b).edges.emplace_back(b,a,1);
    }
    auto p = tree_dfs(graph, u, -1, 0);
    auto q = tree_dfs(graph, v, -1, 1);
    ll ans=0;
    FOR(i,1,N+1){
        const auto &g = graph.at(i);
        if (g.dist[0]<g.dist[1]) {
            chmax(ans,g.dist[1]-1);
            dump(i,g.dist[0],g.dist[1]);
        }
    }
    cout<<ans<<endl;
    return 0;
}

Measured memory_bytes: 18560
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define FORD(i,a,b) for(int i=a;i>=b;i--)
#define FORL(i,x) for(int i=head[x];i;i=nxt[i])
#define ALL(a)  (a).begin(),(a).end()
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())
#define PB push_back
#define MP make_pair
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; }

int N,Q;
vector<vector<int>> graph(200010);
vector<bool> visited(200100,false);
ll ans[200010];



void dfs(int v) {
  visited[v] = true;
  for (int v2 : graph[v]) {
   if (visited[v2] == true) continue;
   ans[v2] += ans[v];
   dfs(v2);
  }
 }

int main() {
  cin >> N >> Q;
  int a[N-1],b[N-1];
  FOR(i,0,N-2){
      cin >> a[i] >> b[i];
      graph[a[i]].PB(b[i]);
      graph[b[i]].PB(a[i]);
  }
  ll p[Q],x[Q];
  FOR(i,0,Q-1){
      cin >> p[i] >> x[i];
      ans[p[i]] += x[i];
  }

  dfs(1);

  FOR(i,1,N) cout << ans[i] << " ";
  cout << endl;





}



Measured memory_bytes: 28928
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iomanip>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
// #define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>

#define ll long long
#define Size(v) (int)v.size()

using namespace std;
// using namespace __gnu_pbds;

int n;
int ans = 0;
vector<vector<int>> adjlist;

vector<pair<int, int>> edge;

map<pair<int, int>, int> color;

void dfs(int v, int p = -1) {
	if (p != -1) {
		ans = max(ans, Size(adjlist[v]));
	}
	else ans = max(ans, Size(adjlist[v]));

	int now = 0;

	for (auto &c : adjlist[v]) {
		if (c == p) continue;
		++now;

		if (p != -1) if (color[{min(v, p), max(v, p)}] == now) ++now;

		color[{min(c, v), max(c, v)}] = now;

		dfs(c, v);
	}
}

void solve() {
	cin >> n;

	adjlist.resize(n + 1);

	for (int i = 1; i < n; ++i) {
		int u, v;
		cin >> u >> v;

		edge.push_back({min(u, v), max(u, v)});

		adjlist[u].push_back(v);
		adjlist[v].push_back(u);
	}

	dfs(1);


	cout << ans << '\n';

	for (int i = 0; i < n - 1; ++i) cout << color[edge[i]] << '\n';
}

signed main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);

	int t = 1;
	while (t--) 
		solve();
	return 0;
}

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

typedef long long ll;
typedef pair<int,int> pii;

long long MOD = 10000000000 + 7;


// modint
const ll mod = 1e9+7;
template< int mod >
struct ModInt {
  int x;
  ModInt() : x(0) {}
  ModInt(int64_t y) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}
  ModInt &operator+=(const ModInt &p) {
    if((x += p.x) >= mod) x -= mod;
    return *this;
  }
  ModInt &operator-=(const ModInt &p) {
    if((x += mod - p.x) >= mod) x -= mod;
    return *this;
  }
  ModInt &operator*=(const ModInt &p) {
    x = (int) (1LL * x * p.x % mod);
      return *this;
  }
  ModInt &operator/=(const ModInt &p) {
    *this *= p.inv();
    return *this;
  }
  ModInt operator-() const { return ModInt(-x); }
  ModInt operator+(const ModInt &p) const { return ModInt(*this) += p; }
  ModInt operator-(const ModInt &p) const { return ModInt(*this) -= p; }
  ModInt operator*(const ModInt &p) const { return ModInt(*this) *= p; }
  ModInt operator/(const ModInt &p) const { return ModInt(*this) /= p; }
  bool operator==(const ModInt &p) const { return x == p.x; }
  bool operator!=(const ModInt &p) const { return x != p.x; }
    
  ModInt inv() const {
    int a = x, b = mod, u = 1, v = 0, t;
    while(b > 0) {
      t = a / b;
      swap(a -= t * b, b);
      swap(u -= t * v, v);
    }
    return ModInt(u);
  }
  
  ModInt pow(int64_t n) const {
    ModInt ret(1), mul(x);
    while(n > 0) {
      if(n & 1) ret *= mul;
      mul *= mul;
      n >>= 1;
    }
    return ret;
  }
  
  friend ostream &operator<<(ostream &os, const ModInt &p) {
    return os << p.x;
  }
  
  friend istream &operator>>(istream &is, ModInt &a) {
    int64_t t;
    is >> t;
    a = ModInt< mod >(t);
    return (is);
  }
  
  static int get_mod() { return mod; }
};
 
using mint = ModInt<mod>;

ll mypow(ll x, ll n){
  if(n == 0)
    return 1;
 
  if(n % 2 == 0)
    return mypow(x * x, n / 2);
  else
    return x * mypow(x, n - 1);

}
vector<mint> fact;

mint P(int a,int b){
  if(a<b){
    return 0;
  }
  mint ret = fact[a];
  ret *= fact[a-b].inv();

  return ret;
}

mint C(int a,int b){
  if(a<b){
    return 0;
  }

  mint ret = fact[a];
  ret *= fact[b].inv();
  ret *= fact[a-b].inv();

  return ret;
}


int main(){
  cout << setprecision(10);
  int N,M; cin >> N >> M;

  fact.assign(M+1,1);

  for(ll i = 1; i <= M; i++){
    fact[i] = fact[i-1] * i;
  }


  mint ans = P(M,N)*P(M,N);

  for(int k = 1; k <= N; k++){
    // k箇所が同じ、他は知らない

    mint tmp = P(M,k) * C(N,k);
    tmp *= P(M-k, N-k);
    tmp *= P(M-k, N-k);
    if(k%2==0){
      ans += tmp;
    } else { 
      ans -= tmp;
    }
  }

  cout << ans << endl;

}

Measured memory_bytes: 5024