akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <algorithm> // next_permutation
#include <iomanip>
#include <cmath>
#include <vector>
#include <sstream>
#include <string>
#include <cstdio>
#include <stack>
#include <queue>
#include <list>
#include <numeric> //accumulate
//#include <unordered_map> //ハッシュ関数
#include <fstream> //ifstream, ofstream

//#define NDEBUG //NDEBUGが#include <cassert>より前に定義されている場合assertは無効になる。提出時はNDEBUGを定義しておいたほうがいいかも
#include <cassert> //assert


using namespace std;

//デバッグ時はTESTを定義する。本番時はこの行をコメントアウトする
#define TEST //*******************************************************************************************************************************************
//そうすることで、以下に定義する、デバッグ時にのみ標準出力する、doutコマンドが実現できる。本番時はダミーストリームに出力
//ただダミーストリームに出力する処理も結構CPU時間食うようなので、TLEを引き起こす原因になる可能性には注意                           ・・・もしかしてcerrを使ったほうがいいのかな？？？
#ifdef TEST
#define dout cout
#define din cin
#else
stringstream dummy; //デバッグ時のdoutコマンドのダミー出力先
#define dout dummy.str(""); dummy.clear(stringstream::goodbit); dummy //dummyを毎回リセットしておかないとメモリ溢れちゃう。
//どうせ表示しないからgoodbitしなくていいけど、表示する場合はこれしておかないとバグるらしいので、勉強のために。詳しくは http://d.hatena.ne.jp/linden/20060427/p1
#endif

//標準出力先をテキストファイルにしたい場合はOUTPUTFILEを定義する。本番時はこの行をコメントアウトする
//#define OUTPUTFILE "output.txt" //*******************************************************************************************************************************************
#ifdef OUTPUTFILE
#define dout outputfile //というのはTLE問題でどうせdoutを全部コメントアウトしなくちゃいけなくなるので上記方式は却下して、代わりに出力先を標準出力からファイルに切り替えできるようにする
ofstream outputfile(OUTPUTFILE);
#define OutputFilePath "/Users/Nag/Documents/Prgm/Test/DerivedData/Test/Build/Products/Debug/output.txt"
#endif

//標準入力元をテキストファイルにしたい場合はINPUTFROMTEXTFILEを定義する。本番時はこの行をコメントアウトする
//#define INPUTFILE "input.txt" //*******************************************************************************************************************************************
#ifdef INPUTFILE
#define din inputfile
ifstream inputfile(INPUTFILE);
#endif


#define disp(A) dout << #A << " = " << (A) << endl
#define disP(A) dout << setw(3) << (A) << " " // << setw(3) をたまに入れるかも
#define rep(i,a,n) for(int (i)=(a); (i)<(n); (i)++)
#define dispAll(A,n) dout << #A << " = "; rep(j, 0, (n)) {disP(A[j]);} dout << endl

typedef pair<int,int> pii;
typedef vector<int> vi;
typedef unsigned long long ll;


const int INF = 1e9-1;


int main() {
    string s; din>>s;
    int ans = 0;
    rep(i,0,6) {
        ans += (s[i]=='1'? 1 : 0);
    }
    
    dout << ans << endl;
    
    
    
    
#ifdef INPUTFILE
    inputfile.close();
#endif
    
#ifdef OUTPUTFILE
    outputfile.close();
    cout << "\"" << OutputFilePath << "\"" << endl;
#endif
    
    return 0;
}

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

void solve(std::istream &in, std::ostream &out);

int main() {
#ifdef LOCAL
  freopen("../IO/d.in", "r", stdin);
//  freopen("../IO/d.out", "w", stdout);
#else
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(nullptr);
  std::cout.tie(nullptr);
#endif
  solve(std::cin, std::cout);
  return 0;
}

constexpr int N = (int)2e5 +15496;
constexpr int mod = (int)1e9 + 7;
vector<int> g[N];
int fac[N+1],ifac[N+1], ans[N], dp[N], sz[N],n;

int powmod(int64_t a, int64_t b) {
  int64_t res = 1;
  for (; b; b >>= 1) {
    if (b & 1) res = res * a % mod;
    a = a * a % mod;
  }
  return res;
}

void init() {
  fac[0] = ifac[0] = 1;
  for (int i = 1; i < N; ++i) {
    fac[i] = (int64_t) fac[i - 1] * i % mod;
  }
  ifac[N - 1] = powmod(fac[N - 1], mod - 2);
  for (int i = N - 2; i >= 1; --i) {
    ifac[i] = (int64_t) ifac[i + 1] * (i + 1) % mod;
  }
}

void dfs1(int v, int p = -1) {
  int prod = 1;
  for (int u : g[v]) if (u != p) {
    dfs1(u, v);
    prod = (int64_t) prod * dp[u] % mod * ifac[sz[u]] % mod;
    sz[v] += sz[u];
  }
  sz[v] += 1;
  dp[v] = (int64_t) prod * fac[sz[v] - 1] % mod;
}

void dfs2(int v, int a, int p = -1) {
  ans[v] = (int64_t) dp[v] * a % mod * ifac[sz[v] - 1] % mod;
  for (int u : g[v]) {
    if (u != p) {
      dfs2(u, (int64_t) ans[v] * fac[sz[u]] % mod * powmod(dp[u], mod - 2) % mod * powmod(n - sz[u], mod - 2) % mod, v);
    }
  }
}

void solve(std::istream &in, std::ostream &out) {
  init();
  in >> n;
  for (int i = 0, a, b; i < n - 1; ++i) {
    in >> a >> b;
    --a;
    --b;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  dfs1(0);
  dfs2(0, 1);
  for (int i = 0; i < n; ++i) {
    out << (int64_t)ans[i]*fac[n-1]%mod << '\n';
  }
}



Measured memory_bytes: 18420
H, W = map(int, input().split())
S = [input() for h in range(H)]

H = H-1
W = W-1

res = []
for h in range(H+1):
    res_w = ""
    for w in range(W+1):
        count = 0
        if S[h][w] == "#":
            res_w += "#"
        else:
            if h - 1 >= 0:
                count += S[h - 1][w] == "#"
                if w - 1 >= 0:
                    count += S[h - 1][w - 1] == "#"
                if w + 1 <= W:
                    count += S[h - 1][w + 1] == "#"
            if h + 1 <= H:
                count += S[h + 1][w] == "#"
                if w - 1 >= 0:
                    count += S[h + 1][w - 1] == "#"
                if w + 1 <= W:
                    count += S[h + 1][w + 1] == "#"
            if w - 1 >= 0:
                count += S[h][w - 1] == "#"
            if w + 1 <= W:
                count += S[h][w + 1] == "#"
            res_w += str(count)
    res.append(res_w)

for r in res:
    print(r)


Measured memory_bytes: 3064
import numpy as np
n, m = list(map(int, input().split()))
ans = 0
pair = []
for i in range(n):
    pair.append(list(map(int, input().split())))

pair.sort()
i = 0
drinks = 0
while(True):
    if drinks + pair[i][1]  < m:
        drinks = drinks + pair[i][1]
        ans = ans + pair[i][0] * pair[i][1]
    else:
        ans = ans + pair[i][0] * (m - drinks)
        break
    i = i + 1
print(ans)


Measured memory_bytes: 36828
#include <iostream>
#include <unordered_map>
#include <map>
#include <vector>
#include <stack>
#include <algorithm>
#include <list>
#include <set>
#include <climits>
#include <cmath>
#define lli long long int
using namespace std ;

int eval(vector<vector<int> > &adjacency, int vertex, vector<int> &dp)
{
	if(dp[vertex] != -1) return dp[vertex] ;

	dp[vertex] = 0 ;
	for(auto i : adjacency[vertex])
	{
		dp[vertex] = max(dp[vertex], 1 + eval(adjacency,i,dp)) ;
	}

	return dp[vertex] ;
}

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

	vector<vector<int> > adjacency(n) ;
	vector<int> dp(n,-1) ;

	for(int i = 0 ; i < m ; i++)
	{
		int x,y ;
		cin>>x>>y ;
		--x ;
		--y ;
		adjacency[x].push_back(y) ;
	}

	int ans = 0 ;
	for(int i = 0 ; i < n ; i++)
	{
		if(dp[i] == -1) eval(adjacency,i,dp) ;
		ans = max(ans,dp[i]) ;
	}

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

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

using namespace std;
 
//#define int long long
using ll = long long;
#define all(v) (v).begin(), (v).end()
#define rep(i,n) for(ll i=0;i<n;i++)
#define reps(i,n) for(ll i=0;i<=n;i++)

ll MOD = 1000000007;
const long long L_INF = 1LL << 60;
const int INF = 2147483647; // 2^31-1
const double PI = acos(-1);
 
const ll dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const ll dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};

int main(){
    ios_base::sync_with_stdio(false);
    ll N,K,ans=0,s;
    cin >> N >> K;
    vector<ll> H(N,0);
    rep(i,N){
        cin >> H[i];
    }
    sort(all(H));
    
    s = N-K;
    
    rep(i,s){
        ans += H[i];
    }

    cout << ans << endl;

    return 0;
}


Measured memory_bytes: 4832
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;

int main()
{
	string s;
	cin >> s;
	int len = s.length();
	int zero = 0, one = 0;
	for( int i = 0; i < len; ++i )
	{
		if( s[i] == '0' ) zero++;
		else one++;
	}
	cout << len-abs(zero-one) << endl;

	return 0;
}

Measured memory_bytes: 512
N = int(input())
P = [int(i) for i in input().split(' ')]
Q = [int(i) for i in input().split(' ')]

fact = [1] * 8
for i in range(1,8):
    fact[i] = fact[i-1] * i

a = 0
remain = list(range(1,N+1))

for i , v  in enumerate(P):
    num = remain.index(v)
    remain.remove(v)
    a += num * fact[(N - i - 1)]

b = 0
remain = list(range(1,N+1))

for i , v  in enumerate(Q):
    num = remain.index(v)
    remain.remove(v)
    b += num * fact[(N - i - 1)]

print(abs(b-a))


Measured memory_bytes: 3064
#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define countof(array) (sizeof(array) / sizeof(array[0]))
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define rrep(i,n) for(int i = (n)-1; i >= 0; --i)
#define rep2(i,n) for(int i = 1; i <= (n); ++i)
#define rrep2(i,n) for(int i = (n); i > 0; --i)
#define srep(i,s,n) for(int i = s; i < (n); ++i)
#define rsrep(i,s,n) for(int i = (n)-1; i >= s; --i)
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define aall(a) (a), (a)+countof(a)//for array sorting
#define raall(a) (a), (a)+countof(a), greater<>()
#define show(x) cout<<#x<<" = "<<(x)<<endl;
#define vfind(v, a) find(all(v), a) != v.end()
#define yn(f) { if (f) puts("YES"); else puts("NO"); }
#define yns(f) { if (f) puts("Yes"); else puts("No"); }
#define show_ary(...) { cout<<#__VA_ARGS__<<" = "; for (const auto& x : (__VA_ARGS__)) { cout<<x<<" "; } cout<<endl; }
#define show_pair(...) cout<<#__VA_ARGS__<<" = "<<endl; for (const auto& x : (__VA_ARGS__)) { cout<<"  "<<x.fi<<" : "<<x.se<<endl; }
#define out_ary(...) { int n = (__VA_ARGS__).size(); rep(i, n) printf("%d%s", (__VA_ARGS__)[i], i != n-1 ? " " : "\n"); }
#define argmax(v) distance((v).begin(), max_element(all(v)))
#define argmin(v) distance((v).begin(), min_element(all(v)))
#define vmax(v) *max_element(all(v))
#define vmin(v) *min_element(all(v))
typedef long long int ll;
typedef pair<int, int> P;
typedef vector<P> vpair;
typedef vector<int> vint;
typedef vector<ll> vll;
typedef vector<double> vdouble;
typedef vector<string> vstr;
typedef vector<bool> vbool;
typedef vector<vint> vvint;
typedef vector<vll> vvll;
typedef vector<vstr> vvstr;
typedef vector<vbool> vvbool;
const ll LINF = 2000000000000000000ll;
const int INF = 1000000100;
const ll MOD = 1e9+7;


int main() {
    int n;
    cin >> n;
    vint a(n);
    rep(i, n) {
        cin >> a[i];
        --a[i];
    }

    int ans = 0;
    rep(i, n) {
        if (a[a[i]] == i) ans++;
    }

    cout << (ans>>1) << endl;
    return 0;
}

Measured memory_bytes: 640
#[allow(unused_macros)]
macro_rules! debug {
    ($($arg:tt)*) => (if cfg!(debug_assertions) {print!("[DEBUG] "); println!($($arg)*)});
}

const MOD: i64 = 1e9 as i64 + 7;

pub fn mod_pow(mut x: i64, mut n: i64) -> i64 {
    let mut res = 1i64;
    while n > 0 {
        if n % 2 == 1 {
            res = res * x % MOD;
        }
        x = x * x % MOD;
        n /= 2;
    }
    res
}

pub fn inv(x: i64) -> i64 {
    mod_pow(x, MOD - 2)
}

fn f(x: usize, y: usize, fact: &Vec<i64>) -> i64 {
    debug!("x = {}, y = {}", x, y);
    fact[x + y] * inv(fact[x]) % MOD * inv(fact[y]) % MOD
}

const N: usize = 200000;

fn main() {
    let mut rd = reader::Reader::new();

    let mut fact: Vec<i64> = vec![0; N];
    fact[0] = 1;
    for i in 1..N {
        fact[i] = fact[i - 1] * i as i64 % MOD;
    }
    debug!("{:?}", &fact[0..10]);

    let h: usize = rd.next();
    let w: usize = rd.next();
    let a: usize = rd.next();
    let b: usize = rd.next();

    debug!("h = {}, w = {}, a = {}, b = {}", h, w, a, b);
    let mut ans = 0;
    for i in 0..w - b {
        let f1 = f(h - a - 1, b + i, &fact);
        let f2 = f(a - 1, w - b - 1 - i, &fact);
        debug!("f1 = {}", f1);
        debug!("f2 = {}", f2);
        debug!("i = {}, f1 * f2 = {}\n", i, f1 * f2);
        ans += f1 * f2;
        ans %= MOD;
    }
    print!("{}", ans);
    //    ans = f(H-A, B+1) * f(A, W-B), f(H-A, B+2) * f(A, W-B-1), ... f(H-A, W) * f(A, 1)

}

mod reader {
    use std::fmt::Debug;
    use std::str::FromStr;
    use std::collections::VecDeque;
    use std::io::{self, Read};

    fn _read_line() -> String {
        let mut buf = String::new();
        let _ = io::stdin().read_to_string(&mut buf);
        buf
    }

    fn _read_vec_deque_string() -> VecDeque<String> {
        _read_line()
            .split_whitespace()
            .map(|s| s.to_string())
            .collect()
    }

    #[allow(dead_code)]
    pub struct Reader {
        buf: VecDeque<String>,
    }

    #[allow(dead_code)]
    impl Reader {
        pub fn new() -> Reader {
            Reader { buf: VecDeque::new() }
        }

        fn update_buf(&mut self) {
            if self.buf.is_empty() {
                self.buf = _read_vec_deque_string();
            }
        }

        pub fn next<T>(&mut self) -> T
            where
                T: FromStr,
                T::Err: Debug,
        {
            self.update_buf();
            self.buf.pop_front().unwrap().parse::<T>().unwrap()
        }

        pub fn next_n<T>(&mut self, n: usize) -> Vec<T>
            where
                T: FromStr,
                T::Err: Debug,
        {
            let mut vec: Vec<T> = Vec::with_capacity(n);

            for _ in 0..n {
                vec.push(self.next());
            }
            vec
        }
    }
}


Measured memory_bytes: 6396
#include <bits/stdc++.h>
using namespace std;
struct UnionFind{
  int n;
  vector<int> r,p;
  UnionFind(){}
  UnionFind(int sz):n(sz),r(sz,1),p(sz,0){iota(p.begin(),p.end(),0);}
  int find(int x){
    return (x==p[x]?x:p[x]=find(p[x]));
  }
  bool same(int x,int y){
    return find(x)==find(y);
  }
  void unit(int x,int y){
    x=find(x);y=find(y);
    if(x==y) return;
    if(r[x]<r[y]) swap(x,y);
    r[x]+=r[y];
    p[y]=x;
  }
};
int F[1009];
void fib(){
  F[0]=2;
  F[1]=3;
  for(int i=2;i<1009;i++){
    F[i]=F[i-1]+F[i-2];
    F[i]%=1001;
  }
}
int main(){
  int n,d;
  fib();
  while(cin>>n>>d){
    UnionFind U(n);
    for(int i=0;i<n;i++){
      for(int j=i+1;j<n;j++){
        if(abs(F[i]-F[j])<d){
          U.unit(i,j);
        }
      }
    }
    set<int>s;
    for(int i=0;i<n;i++)s.insert(U.find(i));
    cout<<s.size()<<endl;
  }
}


Measured memory_bytes: 3016
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
     
using namespace std;
     
typedef long long ll;
typedef pair<int, int> pii;
     
#define fi first
#define se second
#define mp make_pair
#define fastIO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
     
mt19937 rnd(chrono::steady_clock().now().time_since_epoch().count());

const int N = (int)2e5 + 9;

struct Data{
    int start;
    int rig;
    bool operator<(const Data &D) const {
        if(start == D.start)
            return rig > D.rig;
        else
            return start < D.start;
    }
};

int main(){
    fastIO;
    int n, m;
    cin >> n >> m;
    vector<Data> dd;
    Data cur;
    for(int i = 0 ; i < n; i ++ ){
        cin >> cur.start >> cur.rig;
        dd.push_back(cur);
    }
    sort(dd.begin(), dd.end());
    priority_queue<int, vector<int>, greater<int>> dat;
    int p = 0;
    while(p < dd.size()){
        if(dd[p].start > 0)
            break;
        dat.push(dd[p].rig);
        p ++ ;
    }
    int res = 0;
    for(int i = 1; i <= m ; i ++ ){
        while(p < dd.size() && dd[p].start < i){
            dat.push(dd[p].rig);
            p ++ ;
        }
        if(p < dd.size()){
            p ++ ;
            continue;
        }
        if(!dat.empty() && dat.top() <= i){
            dat.pop();
            continue;
        }
    }
    while(p < dd.size()){
        dat.push(dd[p].rig);
        p ++ ;
    }
    cout << dat.size() << "\n";
    return 0;
}

Measured memory_bytes: 3696
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>

#define ll long long
#define inf 1e9
#define eps 1e-10
#define md
using namespace std;
struct yts { int x,t,ne;} e[2010];
int f[1010],g[5010][2];
int num,v[1010],a[1010];
void put(int x,int y)
{
	num++; e[num].x=x; e[num].t=y;
	e[num].ne=v[x]; v[x]=num;
}

void dfs(int x)
{
	for (int i=v[x];i;i=e[i].ne)
	{
		dfs(e[i].t);
	}
	int now=0,pre=1;
	g[0][now]=0;
	for (int i=1;i<=a[x];i++) g[i][now]=inf;
	for (int i=v[x];i;i=e[i].ne)
	{
		int y=e[i].t;
		now^=1; pre^=1;
		for (int j=0;j<=a[x];j++) g[j][now]=inf;
		for (int j=a[x]-a[y];j>=0;j--)
			g[j+a[y]][now]=min(g[j][pre]+f[y],g[j+a[y]][now]);
		for (int j=a[x]-f[y];j>=0;j--)
			g[j+f[y]][now]=min(g[j][pre]+a[y],g[j+f[y]][now]);
	}
	f[x]=inf;
	for (int i=0;i<=a[x];i++) f[x]=min(f[x],g[i][now]);	
}

int main()
{
	int n; scanf("%d",&n);
	for (int i=2;i<=n;i++)
	{
		int x;
		scanf("%d",&x);
		put(x,i);
	}
	for (int i=1;i<=n;i++) scanf("%d",&a[i]);
	dfs(1);
	//for (int i=1;i<=n;i++) printf("%d ",f[i]); printf("\n");
	for (int i=1;i<=n;i++) if (f[i]==inf) { printf("IMPOSSIBLE\n"); return 0;}
	printf("POSSIBLE\n");
	return 0;
}



Measured memory_bytes: 256
# coding:utf-8

import sys

INF = float('inf')
MOD = 10 ** 9 + 7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()


a, b, c, d = LI()
print(max(a * b, c * d))


Measured memory_bytes: 3060
from collections import deque
import sys
input = sys.stdin.readline

MOD = 1000000007

class Factorial():
    def __init__(self,n,mod):
        self.mod = mod
        self.factorial = [0 for _ in range(n+1)]
        self.inv = [0 for _ in range(n+1)]
        self.factorial[0] = 1
        self.inv[0] = 1
        for i in range(n):
            self.factorial[i+1] = self.factorial[i]*(i+1)%mod
            self.inv[i+1] = self.inv[i]*pow(i+1,mod-2,mod)%mod
    def comb(self,m,k):
        return self.factorial[m]*self.inv[k]*self.inv[m-k]%self.mod
    def fact(self,m):
        return self.factorial[m]
    def perm(self,m,k):
        return self.factorial[m]*self.inv[m-k]%self.mod
    def invfact(self,m):
        return self.inv[m]

N,K = map(int,input().split())

tree = [[] for _ in range(N)]

for _ in range(N-1):
    a,b = map(int,input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)
    
visited = [0 for _ in range(N)]
visited[0] = 1
queue = deque([0])
ans = K

f = Factorial(K+1,MOD)

while queue:
    node = queue.popleft()
    count = 0
    for adj in tree[node]:
        if not visited[adj]:
            visited[adj] = 1
            queue.append(adj)
            count += 1
    if node==0:
        if K-1 < count:
            print(0)
            break
        ans *= f.perm(K-1,count)
    else:
        if K-2 < count:
            print(0)
            break
        ans *= f.perm(K-2,count)
    ans %= MOD
            
else:
    print(ans)

Measured memory_bytes: 65008
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;



class Main{

    static class Pair{
        long p1,p2;
        Pair(long p1,long p2){this.p1=p1;this.p2=p2;}
    }
    static class Edge{
        int to;
        Edge(int to){this.to=to;}
    }
    static List<Integer> edges[];
    static Edge edge[];
    static long base;
    static long invtwo;
    static int n;
    static long mod = (long)1e9+7;

    static ArrayDeque<Pair> dfs(int v){
        long p1 = base;
        long p2 = base;
        ArrayDeque<Pair> res;
        if(edges[v].size()==0){
            res = new ArrayDeque<>();
        }else{
            res = dfs(edges[v].get(0));
            List<Long> pp = new ArrayList<>();
            for(int i=1;i<edges[v].size();++i){
                ArrayDeque<Pair> que = dfs(edges[v].get(i));
                if(que.size()>res.size()){
                    ArrayDeque<Pair> tmp = res;
                    res =que;que=tmp;
                }
                Iterator itr = res.iterator();
                while(pp.size() < que.size())pp.add(0L);
                int index = 0;
                while(!que.isEmpty()){
                    Pair pj = que.pollFirst();
                    Pair pi = (Pair)itr.next();
                    long p = ((((pi.p1*pj.p2)%mod + (pi.p2*pj.p1)%mod)%mod) *invtwo)%mod;
                    pp.set(index, (pp.get(index) + (((pi.p2*pj.p2)%mod)*invtwo%mod)%mod)%mod );
                    ++index;
                    pi.p1 = ((pi.p1*pj.p1)%mod*invtwo)%mod;
                    pi.p2 = p;
                }
            }
            Iterator itr = res.iterator();
            for(Long p : pp){
                Pair pi = (Pair)itr.next();
                pi.p1 = (pi.p1 + p)%mod;
            }
        }
        res.addFirst(new Pair(p1,p2));
        return res;
    }

    static long inverse(long m, long mod){
        long res =1;
        for(int i=0;i<32;++i){
            if((((mod-2)>>i)&1)==1)res=(res*m)%mod;
            m=(m*m)%mod;
        }
        return res;
    }

    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        n = scan.nextInt();
        edges = new ArrayList[n+1];
        edge = new Edge[n+1];
        for(int i=0;i<n+1;++i)edges[i]=new ArrayList<>();
        for(int i=0;i<n;++i)edges[scan.nextInt()].add(i+1);
        long ans = 0;
        invtwo=1;
        for(int i=1;i<=n+1;++i)invtwo=(invtwo*2)%mod;
        invtwo=inverse(invtwo, mod);
        base = 1;
        for(int i=0;i<n;++i)base=(2*base)%mod;

        ArrayDeque<Pair> mp = dfs(0);
        Iterator itr = mp.iterator();
        while(itr.hasNext()){
            Pair p = (Pair)itr.next();
            ans = (ans + p.p2)%mod;
        }
        System.out.println(ans);
    }
}

Measured memory_bytes: 169616
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>

using namespace std;

int main() {
  int N;
  cin >> N;
  vector<pair<int, int>> v(N);  // B, A
  for (int i = 0; i < N; i++) {
    int a, b;
    cin >> a >> b;
    v[i] = make_pair(b, a);
  }
  sort(v.begin(), v.end());
  bool ok = true;
  int now = 0;
  for (auto p : v) {
    now += p.second;
    if (now > p.first) {
      ok = false;
      break;
    }
  }
  cout << (ok ? "Yes" : "No") << endl;
  return 0;
}


Measured memory_bytes: 1792
import java.util.*;

class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] L = new int[2*N];
        for(int i=0;i<L.length;i++){
            L[i]=sc.nextInt();
        }
        int ans = 0;
        Arrays.sort(L);
        for(int i=0;i<L.length;i+=2){
            ans += L[i];
        }
        System.out.println(ans);
    }
}


Measured memory_bytes: 21844
#include <bits/stdc++.h>
using namespace std;
 
int main(){
     long long n,k;
     cin>>n>>k;
     
	
	 	if(n%k==0)
     {
     	cout<<"0"<<endl;
	 }
	 else
	 {
	 	cout<<min(abs(n-(n/k)*k),abs(n-(n/k+1)*k))<<endl; 
	  }
	  
      
    return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cassert>
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,n) FOR(i,0,n)
#define rep(i,n) FOR(i,0,n)
#define DEBUG(x) cout<<#x<<": "<<x<<endl
#define vint vector<int>
#define vdouble vector<double>
#define vstring vector<string>
using namespace std;

#include<map>
#include<set>
#include<queue>

typedef long long ll;
typedef unsigned long long ull;

// const int MAX_N = 1000000;
const int INFTY = (1 << 21); // 2097152
// const ll INFTY = (1LL << 60);
const ll MD = 1000000007LL;
// fprintf(stderr, "%d %lld \n", x, xll);

class SegTree{

public:

	int n;
	vector<int> dat;
	vector<int> _kl;
	vector<int> _kr;

	int dummy = 2147483647;

	SegTree(int _n){
		init(_n);
	}

	void init(int n_){
		// set n
		n = 1;
		while(n < n_) n *=2;
		int n_cells = 2 * n - 1;

		// initialize vectors
		dat = vector<int>(n_cells);
		_kl = vector<int>(n_cells);
		_kr = vector<int>(n_cells);

		// initialize kl, kr
		rep(k, n_cells){
			if(is_root(k)){
				_kl[k] = 0;
				_kr[k] = n;
			}
			else{
				if(is_cl(k)) {
					_kl[k] = _kl[pa(k)];
					_kr[k] = (_kl[pa(k)] + _kr[pa(k)]) / 2;
				}
				else{
					_kl[k] = (_kl[pa(k)] + _kr[pa(k)]) / 2;
					_kr[k] = _kr[pa(k)];
				}
			}
		}

		// initialize values
		rep(k, n_cells) dat[k] = 0;

		/*
		rep(k, n_cells){
			fprintf(stderr, "%d %d %d %d\n", k, _kl[k], _kr[k], dat[k]);
		}
		*/
	}

	int pos(int i){ return i + n - 1; }
	int pa(int k){ return (k - 1) / 2; }
	int cl(int k){ return k * 2 + 1; }
	int cr(int k){ return k * 2 + 2; }
	bool is_root(int k){ return k == 0; }
	bool is_cl(int k){
		if(is_root(k)) return false;
		return cl(pa(k)) == k;
	}

	void update(int i, int a){
		int k = pos(i);
		dat[k] += a;
		while(!is_root(k)){
			k = pa(k);
			dat[k] += a;
		}
	}

	int query(int il, int ir){
		return _query(il, ir, 0);
	}

	int _query(int il, int ir, int k){
		int kl = _kl[k];
		int kr = _kr[k];
		if(kr <= il || ir <= kl) return 0;
		if(il <= kl && kr <= ir) return dat[k];
		else{
			int vl = _query(il, ir, cl(k));
			int vr = _query(il, ir, cr(k));
			return vl + vr;
		}
	}
};

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

	SegTree ST(N);

	rep(q, Q){
		int c, x, y;
		cin >> c >> x >> y;

		if(c == 0){
			// update
			x--;
			ST.update(x, y);
		}
		else{
			// find
			x--; y--;
			cout << ST.query(x, y+1) << endl;
		}
	}

}

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

int main(){ 
    int a=0;
int n;
cin>>n;
    vector<int> vec(n);
for (int i = 0; i < n; i++) {
  cin >> vec.at(i);
}
for(int i=0;i<n-2;i++){
if(vec.at(i+1)<vec.at(i)&&vec.at(i+1)>vec.at(i+2)||vec.at(i+1)>vec.at(i)&&vec.at(i+1)<vec.at(i+2)){
    a++;
}
}


cout<<a;
    return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
#define mod 1000000007
#define mod1 998244353
#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
typedef long long int li;
typedef unsigned long long int ull;
using namespace std;
bool sortbysec(const pair<li,li>&a,const pair<li,li>&b)
{
    return (a.second<b.second);
}
int main()
{
fast_io
li n,i,j;
cin>>n;
string s;
cin>>s;
map<char,vector<li>>m;
for(i=0;i<n;i++)
  m[s[i]].push_back(i);
  li ans=0;
  li x=m['G'].size();
  li y=m['R'].size();
  li z=m['B'].size();
  // for(i=0;i<m['R'].size();i++)
  // cout<<m['R'][i]<<" ";
  // cout<<endl;
  // for(i=0;i<m['B'].size();i++)
  // cout<<m['B'][i]<<" ";
  // cout<<endl;
  // for(i=0;i<m['G'].size();i++)
  // cout<<m['G'][i]<<" ";
  ans=x*y*z;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
  li k=2*j-i;
  if(k<n)
  {
    if(s[i]!=s[j]&&s[j]!=s[k]&&s[i]!=s[k])
    ans--;
  }
}
cout<<ans;
  return 0;
}


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

int main(){
    int n,x;

    while(scanf("%d%d",&n,&x)==2){
        int val, mn = INT_MAX, total=0;

        for(int i=0; i<n; i++){
            scanf("%d",&val);
            total+=val;
            mn = min(mn, val);
        }
        int ans = n;

        x-=total;
        ans += x/mn;

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

    return 0;
}


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

using Lint=long long;
using Graph=vector<vector<int>>;

int main()
{
   int N,M; cin>>N>>M;
   Graph G(N);
   for(int i=0;i<N-1;i++){
      int a,b; cin>>a>>b;
      a--; b--;
      G[a].push_back(b);
      G[b].push_back(a);
   }

   vector<int> dp(N);
   function<int(int,int)> dfs=[&](int v,int p)
   {
      int res=1;
      for(int u:G[v]) if(u!=p) res=(Lint)res*(dfs(u,v)+1)%M;
      return dp[v]=res;
   };
   vector<int> ans(N);
   function<void(int,int)> reroot=[&](int v,int p)
   {
      int N=G[v].size();
      vector<int> L(N+1,1),R(N+1,1);
      for(int i=0;i<N;i++){
         int u=G[v][i];
         L[i+1]=(Lint)L[i]*(dp[u]+1)%M;
      }
      for(int i=N-1;i>=0;i--){
         int u=G[v][i];
         R[i]=(Lint)(dp[u]+1)*R[i+1]%M;
      }
      ans[v]=R[0];
      for(int i=0;i<N;i++) if(G[v][i]!=p){
         int u=G[v][i]; int tmp=dp[v];
         dp[v]=(Lint)L[i]*R[i+1]%M;
         reroot(u,v);
         dp[v]=tmp;
      }
   };
   dfs(0,-1); reroot(0,-1);
   for(int i=0;i<N;i++) cout<<ans[i]<<endl;
   return 0;
}


Measured memory_bytes: 19840
#include <bits/stdc++.h>
#define REP(i, n) for (int i = 0, max_i = (n); i < max_i; i++)
#define REPI(i, a, b) for (int i = (a), max_i = (b); i < max_i; i++)
#define ALL(obj) (obj).begin(), (obj).end()
#define RALL(obj) (obj).rbegin(), (obj).rend()
#define fi first
#define se second
#define int long long
using namespace std;
using ll = long long;
using II = pair<int, int>; using VII = vector<II>; using VVII = vector<VII>;
using VI = vector<int>; using VVI = vector<VI>; using VVVI = vector<VVI>;
template <class T = int> inline bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; }
template <class T = int> inline bool chmin(T &a, const T &b) { if (a > b) { a = b; return true; } return false; }
template <class T> ostream& operator<<(ostream &s, const vector<T>& d) { REP (i, d.size()) s << d[i] << (i == d.size() - 1 ? "" : " "); return s; }
template <class T> ostream& operator<<(ostream &s, const vector<vector<T>>& d) { REP (i, d.size()) s << d[i] << (i == d.size() - 1 ? "" : "\n"); return s; }
template <class T, class S> ostream& operator<<(ostream &s, const pair<T, S>& p) { s << "{" << p.first << ", " << p.second << "}"; return s; }
template <class T, class S> ostream& operator<<(ostream& s, const map<T, S> m) { for (auto it = m.begin(); it != m.end(); it++) { s << *it << (next(it) == m.end() ? "" : "\n"); } return s; }
#ifdef _MY_DEBUG
  #define dump(...) cerr << "/* " << #__VA_ARGS__ << " :[" << __LINE__ << ":" << __FUNCTION__ << "]" << endl, dump_func(__VA_ARGS__), cerr << "*/\n\n";
#else
  #define dump(...)
#endif
void dump_func() { cerr << endl; }
template <class Head, class... Tail> void dump_func(Head&& h, Tail&&... t) { cerr << h << (sizeof...(Tail) == 0 ? "" : ", "), dump_func(forward<Tail>(t)...); }
struct Fast { Fast() { cin.tie(0); ios::sync_with_stdio(false); } } fast;
constexpr int MOD = 1e9 + 7;

signed main() {
  int n; cin >> n;
  VVI a(n, VI(n));
  REP (i, n) {
    REP (j, n) {
      cin >> a[i][j];
    }
  }
  VI dp(1 << n, -1);
  dp[0] = 1;
  function<int(int, int)> dfs = [&](int i, int rem) {
    if (dp[rem] != -1) return dp[rem];
    int acc = 0;
    REP (j, n) {
      if (rem >> j & 1 && a[i][j]) {
        int r = rem ^ 1 << j;
        acc += dfs(i + 1, r);
        acc %= MOD;
      }
    }
    return dp[rem] = acc;
  };
  cout << dfs(0, (1 << n) - 1) << endl;
}


Measured memory_bytes: 16640
n,m=map(int,input().split())
l=[{} for k in range(n)]
for i in range(m):
    p,y=map(int,input().split())
    l[p-1][y]=i
for k in range(n):
    l[k]=sorted(l[k].items(), key=lambda x:x[0])
s=[0]*m
for k in range(n):
    for r, p in enumerate(l[k]):
        s[p[1]]=str(k+1).zfill(6)+str(r+1).zfill(6)
for i in s:
    print(i)

Measured memory_bytes: 54856
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;

#define MOD 1000000007

string t, b;
int dp[1001][1001];

int rec(int n, int m) {
    if(m == b.size()) return 1;
    if(n >= t.size() || m >= b.size()) return 0;
    if(~dp[n][m]) return dp[n][m];

    int ret = 0;
    for(int i = n; i < t.size(); i++) {
        if(t[i] == b[m]) {
            ret = (ret + rec(i + 1, m + 1)) % MOD;
        }
    }
    return dp[n][m] = ret;
}

int main() {

    cin >> t >> b;
    memset(dp, -1, sizeof(dp));
    cout << rec(0, 0) << endl;
}

Measured memory_bytes: 7172
class Solver(object):
    def __init__(self):
        self.n, self.m, self.x, self.y = list(map(int, input().split(" ")))
        self.x_s = list(map(int, input().split(" ")))
        self.y_s = list(map(int, input().split(" ")))

    def solve(self):
        self.x_s.append(self.x)
        self.x_s.sort()
        self.y_s.append(self.y)
        self.y_s.sort()
        max_x = max(self.x_s)
        min_y = min(self.y_s)

        for z in range(self.x+1, self.y+1):  # z = x+1 .. y
            if (max_x < z) and (min_y >= z):
                print("No War")
                return
        
        print("War")


if __name__ == "__main__":
    s = Solver()
    s.solve()

Measured memory_bytes: 3064
#include <stdio.h>

char pn[1000000];

int prime(int x)
{
	int i;
	
	if (x < 2){
		return (0);
	}
	if (x == 2){
		return (1);
	}
	if (x % 2 == 0){
		return (0);
	}
	
	for (i = 3; i * i <= x; i += 2){
		
		if (x % i == 0){
			return (0);
		}
	}
	return (1);
}


int main(void)
{
	int n, i, ps;
	
	for (i = 0; i < 1000000; i++){
		if (prime(i) == 1){
			pn[i] = 1;
		}
	}
	
	
	while (scanf("%d", &n) != EOF){
		
		ps = 0;
		
		for (i = 0; i <= n; i++){
			ps += pn[i];
		}
		printf("%d\n", ps);
	}
	
	return (0);
}

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

using namespace std;

#define FOR(i,k,n) for(int i=k;i<n;i++)
#define FORR(i,k,n) for(int i=k;i<=n;i++)
#define scan(a) scanf("%d",&a)
#define scann(a,b) scanf("%d%d",&a,&b)
#define scannn(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define mst(a,n)  memset(a,n,sizeof(a))
#define ll long long
#define N 100005
#define mod 1000000007
#define INF 0x3f3f3f3f

const double eps=1e-8;
const double pi=acos(-1.0);

ll a[N];

int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);

    ll n,k,cnt;
    while(cin>>n)
    {
        ll sum=0;
        for(int i=0;i<n;i++)
            cin>>a[i],sum+=a[i];
        int flag=0;
        if(sum%(n*(n+1)/2))
            flag=1;
        else
        {
            k=sum/(n*(n+1)/2);
            cnt=0;
            for(int i=0;i<n-1;i++)
            {
                if((k-(a[i+1]-a[i]))<0||(k-(a[i+1]-a[i]))%n)
                {
                    flag=1;
                    break;
                }
                else
                    cnt+=(k-(a[i+1]-a[i]))/n;
            }
            if((k-(a[0]-a[n-1]))<0||(k-(a[0]-a[n-1]))%n)
                flag=1;
            else
                cnt+=(k-(a[0]-a[n-1]))/n;
        }
        if(flag)
            puts("NO");
        else
        {
            if(cnt==k)
                puts("YES");
            else
                puts("NO");
        }
    }
    return 0;
}


Measured memory_bytes: 1152
#include<bits/stdc++.h>
using namespace std;
int main(){
  int x,y,z,w;
  cin>>x>>y>>z;
  if(y-x+1<=2*z){
    for(w=x;w<=y;w++){
      cout<<w;
      if(w<y) cout<<' ';
      else cout<<endl;
    }
  }
  else{
    for(w=0;w<z;w++) cout<<x+w<<' ';
    for(w=z-1;w>=0;w--){
      cout<<y-w;
      if(w>0) cout<<' ';
      else cout<<endl;
    }
  }
}

Measured memory_bytes: 3560
#include <bits/stdc++.h>
using namespace std;
using lint     = long long;
const lint inf = 1LL << 60;
const lint mod = 1000000007;

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int h, w;
    cin >> h >> w;
    vector<string> s(h);
    for (int i = 0; i < h; ++i) {
        cin >> s[i];
    }
    vector<vector<int>> a(h, vector<int>(w, 0));
    const int dx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
    const int dy[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
    auto inside     = [&](int y, int x) { return 0 <= y && y < h && 0 <= x && x < w; };
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            if (s[i][j] == '#') {
                for (int k = 0; k < 8; ++k) {
                    int ny = i + dy[k];
                    int nx = j + dx[k];
                    if (inside(ny, nx))
                        a[ny][nx]++;
                }
            }
        }
    }
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            if (s[i][j] != '#')
                s[i][j] = '0' + a[i][j];
        }
    }
    for (int i = 0; i < h; ++i) {
        cout << s[i] << "\n";
    }
    return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define INF 2e9
#define ALL(v) (v).begin(), (v).end()
using namespace std;
typedef long long ll;

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

int main()
{
	int a, b;
	cin >> a >> b;

	cout << a - b + 1 << endl;
}


Measured memory_bytes: 256
N, M = map(int, input().split())
X = list(map(int, input().split()))
if M <= N:
    print(0)
    exit()

X.sort()
D = [X[i+1] - X[i] for i in range(0, len(X)-1)]
D = [X[i+1] - X[i] for i in range(0, len(X)-1)]
D.sort(reverse=True)
E = D[min(N-1, len(D)):]
print(sum(E))

Measured memory_bytes: 13968
import java.util.Scanner;

class Main {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int tate = in.nextInt();
        int yoko = in.nextInt();
        int menseki = tate*yoko;
        int syu = tate*2+yoko*2;
        System.out.println(menseki + " " + syu);
    }
}

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

int main(){
    int n;
    cin >> n;
    if(n%2) cout << (n-1)*(n-1)/2 << endl;
    else    cout << (n-2)*n/2 << endl;
    int sum = n%2 == 1 ? n : n+1;
    for(int i = 1; i < n/2*2; i++){
        for(int j = i+1; j <= n/2*2; j++){
            if(i+j != sum)  cout << i << " " << j << endl;
        }
    }
    if(n%2) for(int j = 1; j < n; j++)  cout << n << " " << j << endl;
    return 0;
}

Measured memory_bytes: 256
import bisect

n=int(input())
s=input()
fpos=[-1]*10
npos=[[-1] for _ in range(10)]
for i in range(n):
  if fpos[int(s[i])]==-1:
    fpos[int(s[i])]=i
  npos[int(s[i])].append(i)
lpos=[len(npos[i]) for i in range(10)]
ans=0
for i in range(10):
  if fpos[i]==-1:
    continue
  for j in range(10):
    spos=bisect.bisect_right(npos[j],fpos[i])
    if spos>=lpos[j]:
      continue
    spos=npos[j][spos]
    for k in range(10):
      tpos=bisect.bisect_right(npos[k],spos)
      if tpos>=lpos[k]:
        continue
      ans+=1
print(ans)

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

int main(){
    int N, K, X, Y;
    cin >> N >> K >> X >> Y;

    int total = 0;

    if(N < K){
        cout << N * X << endl;
        return 0;
    }

    total += K * X;
    total += (N - K) * Y;

    cout << total << endl;
}

Measured memory_bytes: 3624
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;

typedef tree<int, null_type, less<int>, rb_tree_tag,
        tree_order_statistics_node_update>
        PBDS;

#define int long long
#define endl "\n"


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

#ifndef ONLINE_JUDGE
	freopen("prac_input.txt", "r", stdin);
	freopen("prac_output.txt", "w", stdout);
#endif

	int t; cin >> t;

	cout << t + (t * t) + (t * t * t);


	return 0;

}

Measured memory_bytes: 3608
array = gets.split(" ").map { |e| e.to_i }

guki = [0,0,0] #三つの偶奇を調べる
ki = 0
for i in 0..2 do
  if array[i]%2 == 1
    guki[i] = 1
    ki += 1
  end
end

count = 0

if ki == 1 #偶奇を揃える
  for i in 0..2 do
    if guki[i] == 0
      array[i] += 1
    end
  end
  count += 1
elsif ki == 2
  for i in 0..2 do
    if guki[i] == 1
      array[i] += 1
    end
  end
  count += 1
end

max = array.max #いちばん大きいのに合わせる
for i in 0..2 do
  if array[i] < max
    count += (max - array[i]) / 2
  end
end

puts count


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

#ifdef TESTING
  #include "dump.hpp"
#else
  #define DUMP(...)
  #define DEBUG(...)
#endif

typedef unsigned int ui;
typedef long long ll;
typedef unsigned long long ull;
#define SZ(a) int((a).size())
#define _REP(_1,_2,_3,_4,name,...) name
#define _REP4(i,b,e,s) for(decltype(e) _b=(b),_e=(e),i=_b+(0<(s)?0:(s));(0<(s)?i<_e:_e<=i);i+=(s))
#define _REP3(i,b,e) for(decltype(e) _b=(b),_e=(e),i=(_b<_e?_b:_b-1);(_b<_e?i<_e:_e<=i);(_b<_e?i++:i--))
#define _REP2(i,n) for(decltype(n) i=0,_n=(n);i<_n;i++)
#define _REP1(n) for(decltype(n) _i=0,_n=(n);_i<_n;_i++)
#define REP(...) _REP(__VA_ARGS__,_REP4,_REP3,_REP2,_REP1)(__VA_ARGS__)
#define EB emplace_back
#define PB push_back
#define MP make_pair
#define MT make_tuple
#define INT(n) int n;assert(0<scanf("%d",&n))

class union_find {
public:
  vector<unsigned int> par, rank;
  union_find(unsigned int n) {
    for(unsigned int i = 0; i < n; i++){
      par.push_back(i);
      rank.push_back(1);
    }
  }
  unsigned int root(unsigned int x){
    return par[x] == x ? x : par[x] = root(par[x]);
  }
  bool same(unsigned int x, unsigned int y){
    return root(x) == root(y);
  }
  void unite(unsigned int x, unsigned int y){
    x = root(x);
    y = root(y);
    if (x == y){return;}
    if (rank[x] < rank[y]){
      par[x] = y;
      rank[y] += rank[x];
    }
    else {
      par[y] = x;
      rank[x] += rank[y];
    }
  }
};

int main(){
  INT(n); INT(m);
  vector<pair<int, int>> vp;
  REP(m){INT(a); INT(b); vp.EB(a, b);}
  vector<ll> ans(m, 0);
  union_find uf(n + 1);
  ll tmp = (ll) n * (n - 1) / 2;
  REP(i, m){
    ans[m - i - 1] = tmp;
    int a, b;
    a = vp[m - i - 1].first, b = vp[m - i - 1].second;
    if (!uf.same(a, b)){
      tmp -= (ll) uf.rank[uf.root(a)] * uf.rank[uf.root(b)];
    }
    uf.unite(a, b);
  }
  REP(i, m){printf("%lld\n", ans[i]);}
  return 0;
}



Measured memory_bytes: 4084
N, M, K = [int(x) for x in input().split(' ')]
A = [int(x) for x in input().split(' ')]
B = [int(x) for x in input().split(' ')]

# N, M, K = [int(x) for x in [2e3, 2e3, 1e9]]
# A = [int(x) for x in range(N)]
# B = [int(x) for x in range(M)]

A_deep = 0
B_deep = 0
time = 0
while A_deep < N:
  if K >= time + A[A_deep]:
    time += A[A_deep]
    A_deep += 1
  else:
    break 
while B_deep < M:
  if K >= time + B[B_deep]:
    time += B[B_deep]
    B_deep += 1
  else:
    break 

i = A_deep - 1
j = B_deep
ans = i + j + 1
while i >= 0 and j < M:
  while i >= 0:
    time -= A[i]
    i -= 1
    if K - time >= B[j]:
      break 
  while j < M:
    if K >= time + B[j]:
      time += B[j]
      j += 1
      ans = max(ans, i + j + 1)
    else: 
      break 


print(ans)

Measured memory_bytes: 42200
#include <iostream>
#include <string>
#include <cstdio>
#include <math.h>
using namespace std;
int main(){
    int h,m;
    char c;
    string str,sum="";
    while(cin>>str&&str!="-"){
        cin>>m;
        sum=str+str;
        for(int i=1;i<=m;i++){
            cin>>h;
            string ans;
            for(int j=h;j<str.size()+h;j++){
                c=sum[j];
                ans+=c;
            }
                sum=ans+ans;
            if(i==m){
                cout<<ans<<endl;
                break;
            }
        }
    }
    return 0;
}

Measured memory_bytes: 3200
#include <bits/stdc++.h>
#include <algorithm>
#include <queue>

using namespace std;

int main(){
    int N;
    cin >> N;
    int X[N];
    int min = 101;
    int max = 0;
    for(int i=0; i<N; i++){
        cin >> X[i];
        if (min > X[i]){min=X[i];}
        if (max < X[i]){max=X[i];}
    }

    int nums = int(max-min+1);
    int dp[nums];
    int dp_linear[nums];

    dp[0] = 0;
    dp_linear[0]=0;
    for(int j=0; j<N; j++){
        dp[0] += pow((X[j] -min),2);
        dp_linear[0] += (X[j] -min);
    }

    priority_queue<long, vector<long>, greater<long>> que;
    que.push(dp[0]);
    for(int k=1; k<nums; k++){
        dp[k] = dp[k-1] - 2*dp_linear[k-1] + N;
        dp_linear[k] = dp_linear[k-1] - N;
        que.push(dp[k]);
    }

    int ans = que.top();
    cout << ans << endl;
}

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

#define f(x, y, z) for (int x = (y), __ = (z); x < __; ++x)
#define _rep(i, a, b) for (int i = (a); i <= (b); ++i)
#define mst(x, a) memset(x, a, sizeof(x))

typedef long long ll;
typedef pair<int, int> P;
typedef tuple<int, int, int> T;
const int INF = 1 << 27;
const ll LLINF = (ll)1 << 60;
const int MOD = 1e9+7;

inline int mod(int x, int y) {
  return (x % y + y) % y;
}

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

int D, K;
vector<int> dim;
int dp[10010][100][2] = {};

int main() {
  dim.push_back(-1);
  do {
    char ch;
    scanf("%c", &ch);
    if (ch == '\n') break;
    dim.push_back(ch - '0');
  } while (true);
  scanf("%d", &D);

  // dp[i][mod][eq]
  dp[0][0][1] = 1;
  K = dim.size() - 1;
  for (int i = 1; i <= K; i++) {
    for (int state = 0; state < D; state++) {
      dp[i][state][1] = dp[i-1][(state - dim[i] + D) % D][1];

      int sum = 0;
      for (int j = 0; j <= 9; j++) {
        sum = (sum + dp[i-1][mod(state - j, D)][0]) % MOD;
      }
      for (int j = 0; j < dim[i]; j++) {
        sum = (sum + dp[i-1][mod(state - j, D)][1]) % MOD;
      }
      dp[i][state][0] = sum;
    }
  }
  printf("%d\n", mod(dp[K][0][0] + dp[K][0][1] - 1, MOD));
}


Measured memory_bytes: 8192
fun main(args: Array<String>) {
    val mod = 1e9.toLong() + 7
    val (n, m) = readLine()!!.split(' ').map { it.toInt() }
    val ans = when {
        n == m -> {
            var x = 1L
            for (l in 1L..n) {
                x *= l
                x %= mod
            }
            x * x % mod * 2 % mod
        }
        Math.abs(n - m) == 1 -> {
            var x = 1L
            for (l in 1L..Math.min(n, m)) {
                x *= l
                x %= mod
            }
            x * x % mod * Math.max(n, m) % mod
        }
        else -> {
            0
        }
    }
    println(ans)
}


Measured memory_bytes: 38256
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#define rep(i,n) for (int i = 0; i < n; ++i)
using namespace std;
using ll = long long;
using P = pair<int,int>;

int main() {
  int a, b;
  cin >> a >> b;
  if (b == 1) {
    cout << 0 << endl;
    return 0;
  }
  int hole = a;
  int tap = 1;
  while (hole < b) {
    hole += a-1;
    ++tap;
  }
  cout << tap << endl;
  return 0;
}

Measured memory_bytes: 3132
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<math.h>
#include<iomanip>
#include<set>
#include<numeric>
#include<cstring>
#include<cstdio>
#include<functional>
#include<bitset>
#include<limits.h>
#include<cassert>
#include<iterator>
#include<complex>
#include<stack>
#include<sstream>
#include<iterator>
using namespace std;
typedef  long long int lint;
typedef pair<int, int> IP;
typedef pair<lint, lint> LLP;
typedef pair<char, char>CP;
#define rep(i, n) for (int i = 0; i < n; i++)
#define repr(i, n) for (int i = n; i >= 0; i--)
#define sort(v) sort((v).begin(), (v).end())
#define reverse(v) reverse((v).begin(), (v).end())
#define upper(v,hoge) upper_bound(v.begin(),v.end(),hoge)
#define lower(v,hoge) lower_bound(v.begin(),v.end(),hoge)
#define llower(v,hoge) *lower_bound(v.begin(), v.end(), hoge)
#define lupper(v,hoge) *upper_bound(v.begin(), v.end(), hoge)

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

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
 
int main(){
  int N,M,X;
  cin>>N>>M>>X;
  vector<int> n(N+1);
  vector<int> m(M);
  for(int i=0;i<M;i++){
    cin>>m[i];
  }
  for(int i=0;i<=N;i++){
    n[i]=0;
  }
  int ans1=0;
  int ans2=0;
  for(int i=0;i<M;i++){
    n[m[i]]=1;
  }
  for(int i=X;i<=N;i++){
    ans1+=n[i];
  }
  for(int i=0;i<=X;i++){
    ans2+=n[i];
  }
  if(ans1>=ans2){
    cout<<ans2<<endl;
  }
  if(ans1<ans2){
    cout<<ans1<<endl;
  }
}

Measured memory_bytes: 3616
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define INF 0x3f3f3f3f
#define MOD 1000000007
using namespace std;
int dx[4]={0,0,-1,1};
int dy[4]={-1,1,0,0};

int main(){
	char S[100001];
	int count=0;
	cin>>S;
	for(int i=1;S[i]!='\0';i++){
		if(S[i]!=S[i-1])
			count++;
	}
	cout<<count<<endl;
	return 0;
}

Measured memory_bytes: 384
#include<cstdio>
#include<algorithm>
using namespace std;
int main(){
    int n;
    for(;;){
        scanf("%d\n",&n);
        if(n==0) break;
        int n2=0,n5=0;
        for(long long i=2;i<=2000000000;i*=2){
            n2+=n/i;
        }
        for(long long i=5;i<=2000000000;i*=5){
            n5+=n/i;
        }
        printf("%d\n",min(n2,n5));
    }
}

Measured memory_bytes: 0
n,m=map(int,input().split())
a=[input() for _ in range(n)]
b=[input() for _ in range(m)]

for i in range (n-m+1):#行
  for j in range(n-m+1):#列
    g=1
    for k in range(m):#m
      
      if a[i+k][j:j+m]!=b[k]:
        g*=0
        break
    if g==1:
      print("Yes")
      import sys
      sys.exit()
else:
  print("No")
    
  

Measured memory_bytes: 9200