akhauriyash/Code-Regression huggingface dataset:
def main():
    MOD = 10**9+7
    N, M = (int(i) for i in input().split())
    if abs(N - M) > 1:
        print(0)
    elif N == M:
        from math import factorial
        print(factorial(N) * factorial(M) * 2 % MOD)
    else:
        from math import factorial
        print(factorial(N) * factorial(M) % MOD)


if __name__ == '__main__':
    main()


Measured memory_bytes: 55152
#include<stdio.h>

int main(){
	char s[100];
	scanf("%s",s);
	int i;
	for(i = 0;i < 4;i++)
		printf("%c",s[i]);
	printf(" ");
	for(;i < 12;i++)
		printf("%c",s[i]);
	puts("");
	return 0;
}

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

int n, x, c;

std::vector<int> vec, l;

int main() {
    std::cin >> n >> x;
    vec.assign(n+2, 0);
    l.assign(n+1, 0);
    vec[1] = 0;
    for (int i = 1; i <= n; i++) {
        std::cin >> l[i];
    }
    for (int i = 2; i <= n+1; i++) {
        vec[i] = vec[i-1] + l[i-1];
    }
    for (int i = 1; i < vec.size(); i++) {
        if (vec[i] <= x) {
            c++;
        }
    }
    std::cout << c << std::endl;
}


Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <string>
#include <queue>
#include <stack>

using namespace std;

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

const ll mod = 1000000007;

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

  int n;
  cin >> n;
  vector<int> a(n);
  for (auto &x: a) cin >> x;

  ll ans = 1;
  vector<int> c(3);
  for (int i = 0; i < n; i++) {
    ll match = 0;
    for (int j = 0; j < 3; j++) {
      if (a[i] == c[j]) match++;
    }
    ans = (ans * match) % mod;
    for (int j = 0; j < 3; j++) {
      if (a[i] == c[j]) {
        c[j]++;
        break;
      }
    }
  }

  cout << ans << endl;

  return 0;
}


Measured memory_bytes: 640
s = raw_input()
easy = True
#odd RUD
#even LUD
for i in xrange(len(s)):
  if s[i] == 'R' and (i+1)%2 == 0:
    easy = False
  elif s[i] == 'L' and (i+1)%2 == 1:
    easy = False
if easy:
  print 'Yes'
else:
  print 'No'

Measured memory_bytes: 2568
# include <bits/stdc++.h>
# define ll long long
# define f first
# define s second
const ll N = 3e5 + 10 , mod = 1e9 + 7 , INF = 1e9 + 100;
using namespace std;
int main(){
	int n;
	cin >> n;
	cout << n * n << '\n';
}

Measured memory_bytes: 256
import java.util.*;

public class Main {

	static Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {
		String[] words = sc.nextLine().split(" ");
		TreeMap<String, Integer> dic = new TreeMap<String, Integer>();
		String mode = "", longest = "";
		int max = 0, maxlen = 0;
		for(int i = 0; i < words.length; i++) {
			int cnt = 1;
			String key = words[i];
			if(dic.containsKey(key)) {
				cnt = dic.get(words[i]);
				dic.remove(words[i]);
			}
			dic.put(key, ++cnt);
			if(max < cnt) {
				max = cnt;
				mode = key;
			}
			if(maxlen < key.length()) {
				maxlen = key.length();
				longest = key;
			}
		}
		System.out.println(mode + " " + longest);
	}

}

Measured memory_bytes: 12000
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int brc(int x){
    int y = 0;
    while(x){
        y += x%10;
        x /= 10;
    }
    return y;
}
int main(){
    ios_base::sync_with_stdio(false),cin.tie(0),cerr.tie(0),cout.tie(0);
    cout.precision(10);
    cout<<fixed;

    int n;
    cin >> n;
    int mini = 1000000;
    for(int i=1; i<n; i++){
        mini = min(mini, brc(i)+brc(n-i));
    }
    cout << mini;
    return 0;
}


Measured memory_bytes: 256
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<tuple>
#include<map>
#include<queue>
#include<math.h>
#include<iomanip>
#define rep(i, n) rep2(i,0,n)
#define rep2(i, s, n) for (int i = (s); i < (int)(n); i++)
#define PI acos(-1);
typedef long long ll;
using namespace std;
const int MAX = 510000;
const int MOD=1000000007;
//scanf("%d", &a) '\n'

long long binExp(long long a, long long e) {
	if (e == 0) {
		return 1;
	}

	if (e % 2 == 1) {
		return (binExp(a, e - 1) * a) % MOD;
	}

	long long b = binExp(a, e / 2);
	return (b * b) % MOD;
}

long long f(long long a) {
	long long r = 1;
	for (long long i = 2; i <= a; ++i) {
		r = (r * i) % MOD;
	}

	return r;
}

long long inv(long long a) {
	return binExp(a, MOD - 2);
}

long long c(long long k, long long n) {
	long long a = f(k);
	long long b = inv(f(n));
	long long d = inv(f(k - n));

	return ((a * b) % MOD * d) % MOD;
}

int main() {
	ll x, y;
	cin >> x >> y;
	ll a = 2 * x - y;
	ll b = 2 * y - x;
	if (a % 3 != 0 || b % 3 != 0 || a < 0 || b < 0) {
		cout << 0 << endl;
		return 0;
	}
	ll count = (a + b) / 3;
	cout << c(count, a/3);
	
	
}
	

Measured memory_bytes: 256
import sys
read = sys.stdin.readline
import time
import math
import itertools as it
def inpl():
    return list(map(int, input().split()))
st = time.perf_counter()
# ------------------------------

N = int(read())
ans = 0
for i in range(1, N+1):
    n = N // i
    ans += 0.5 * n * (2*i + i * (n-1))
print(int(ans))

# ------------------------------
ed = time.perf_counter()
print('time:', ed-st, file=sys.stderr)


Measured memory_bytes: 9188
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
#include <cstdio>
using namespace std;
typedef long long ll;

#define _SI(arr) (sizeof(arr)/sizeof(arr[0])

int main() {
	ll A, B;
	cin >> A >> B;
	string S;
	cin >> S;

	for (ll i = 0; i < A; i++) {
		if (S[i] < '0' || S[i] > '9') {
			cout << "No" << endl;
			exit(0);
		}
	}
	if (S[A] != '-') {
		cout << "No" << endl;
		exit(0);
	}
	for (ll i = A + 1; i < A + B + 1; i++) {
		if (S[i] < '0' || S[i] > '9') {
			cout << "No" << endl;
			exit(0);
		}
	}

	cout << "Yes" << endl;
}

Measured memory_bytes: 256
D,G=map(int,input().split())
p=[]
c=[]
for i in range(D):
    a,b=map(int,input().split())
    p.append(a)
    c.append(b)

ans=100000

for i in range(2**D):
    ten=0
    mondaisu=0
    for j in range(D):
        if ((i>>j)&1):
            ten+=(j+1)*100*p[j]+c[j]
            mondaisu+=p[j]
        else:
            k=j
    if ten>=G:
        if ans>mondaisu:
            ans=mondaisu
    else:
        if G-ten<=(k+1)*100*p[k]:
            mondaisu+=(G-ten-1)//((k+1)*100)+1
            if ans>mondaisu:
                ans=mondaisu
print(ans)


Measured memory_bytes: 3064
#include <bits/stdc++.h>
using namespace std;
int main () {
	long long N;
	cin >> N;
	vector<long long> A(N);
	for (int i = 0; i < N; i++) cin >> A[i];
	long long mod = 1000000007;
	vector<int> v[100000];
	for (int i = 0; i < N; i++) {
		v[A[i]].push_back(i);
	}
	long long d;
	switch(v[0].size()) {
		case 0:
			d = 0;
        	break;
		case 1:
			d = 3;
			break;
		case 2:
			d = 6;
			break;
		case 3:
			d = 6;
			break;
		default:
			d = 0;
        	break;
	}
	for (int i = 1; i < N; i++) {
		long long dd = 1;
		for (int j = 0; j < (v[i].size()); j++) {
			dd *= (lower_bound(v[i-1].begin(), v[i-1].end(), v[i][j]) - v[i-1].begin()) - j;
		}
		d = (d * dd) % mod;
	}
	cout << d << endl;
}

Measured memory_bytes: 6528
#include<bits/stdc++.h>
#define inf 1000000000
#define N 5005
using namespace std;
char s[N];
int n,m,l[N][N],a[N][N],up[N][N],r[N][N],R[N][N],L[N][N];
int main(){
	scanf("%d%d",&n,&m);
	for (int i=1;i<=n;i++){
		scanf("%s",s+1);
		for (int j=1;j<=m;j++){
			if (s[j]=='#') a[i][j]=1;
			else a[i][j]=0;
		}
	}
	int ans=max(n,m);n--;m--;
	for (int i=1;i<=n;i++)
		for (int j=1;j<=m;j++) a[i][j]=a[i][j]^a[i][j+1]^a[i+1][j]^a[i+1][j+1];
	for (int i=1;i<=n;i++){
		for (int j=1;j<=m;j++){
			if (a[i][j]) l[i][j]=0;
			else l[i][j]=l[i][j-1]+1;
		}
		for (int j=m;j;j--){
			if (a[i][j]) r[i][j]=0;
			else r[i][j]=r[i][j+1]+1;
		}
	}
	for (int i=1;i<=m;i++) L[0][i]=R[0][i]=inf;
	for (int i=1;i<=n;i++){
		for (int j=1;j<=m;j++){
			if (a[i][j]) up[i][j]=0,L[i][j]=R[i][j]=inf;
			else {
				up[i][j]=up[i-1][j]+1;
				L[i][j]=min(l[i][j],L[i-1][j]);
				R[i][j]=min(R[i-1][j],r[i][j]);
			}
		}
	}
	for (int i=1;i<=n;i++)
		for (int j=1;j<=m;j++)
			if (!a[i][j]) ans=max(ans,(up[i][j]+1)*(R[i][j]+L[i][j]));
	printf("%d\n",ans);
	return 0;
}

Measured memory_bytes: 245248
max_n500 = int(input())
max_n100 = int(input())
max_n50 = int(input())
amount = int(input())

count = 0
for n500 in range(max_n500 + 1):
    for n100 in range(max_n100 + 1):
        for n50 in range(max_n50 + 1):
            if n500 * 500 + n100 * 100 + n50 * 50 == amount:
                count += 1
print(count)


Measured memory_bytes: 3060
#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define LD long double
#define all(x) x.begin(), x.end()
const int inf = 2e9, mod = 1e9 + 7;
const int N = 15 + 3, N2 = 5000 + 3, LOGN = 20;
LL a,b,c,d;
bool forever(){
	if(min(a,d) < b) return false;
	if(c >= b - 1) return true;
	LL k = (b - a % b + __gcd(b,d) - 1) / __gcd(b,d) - 1;
	return !(k > (c - a % b) / (__gcd(b,d)) || k < 0 || c < a % b);
}
int32_t main() {
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int tc; cin >> tc;
	while(tc--) {
		cin >> a >> b >> c >> d;
		cout << (forever() ? "Yes" : "No") << "\n";
	}
	return 0;
}

Measured memory_bytes: 256
import java.util.Scanner;

public class Main {

 public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        StringBuilder str = new StringBuilder(sc.nextLine());
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            String com = sc.next();
            int a = sc.nextInt();
            int b = sc.nextInt()+1;
            if ("replace".equals(com)) {
                String str2 = sc.next();
 
                str = str.replace(a,b, str2);
            } else if ("reverse".equals(com)) {
 
                StringBuilder temp  = new StringBuilder(str.substring(a, b));
                temp.reverse();
                str.replace(a, b, temp.toString());
 
            } else if ("print".equals(com)) {
 
                System.out.println(str.substring(a, b));
            }
        }
        sc.close();
    }
    
}


Measured memory_bytes: 29008
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e6+10;
int a[N],n,b;
char c[N];
int main()
{cin>>n;
	for(int i=1;i<=n;i++)scanf("%d",&a[i]);
	sort(a+1,a+n+1);
	for(int i=1;i<=n-2;i++)
	{
		int k=i+1;if(a[i]+a[k]<=a[i+2])k++;
		for(int j=i+2;j<=n;j++)
		{
			b+=j-k;
			while(a[i]+a[k]<=a[j+1])k++;
		}
	}cout<<b;
}


Measured memory_bytes: 256
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(a)  (a).begin(),(a).end()
#define pb push_back
#define INF (1e9+1)
//#define INF (1LL<<59)

int main(){
	int n;
	cin>>n;
	vector<int> v(n);
	rep(i,n)cin>>v[i];
	int ans = v[0]*v[1]/__gcd(v[0],v[1]);
	for(int i=2;i<n;i++)ans = ans*v[i]/__gcd(ans,v[i]);
	cout<<ans<<endl;
}

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

#ifndef M_PI
#define M_PI 3.14159265358979
#endif
#define deg_to_rad(deg) (((deg) / 360) * 2 * M_PI)
#define rad_to_deg(rad) (((rad) / 2 / M_PI) * 360)

using namespace std;

typedef long long ll;
typedef vector<long long> vll;
typedef pair<long long, long long> pll;

const ll INF = 1e15;
const ll MOD = 1e9 + 7;

vector<vll> dp;
vll A, C;

void init(ll N, ll M) {
    dp = vector<vll>(M + 1, vll(1 << N, -1));
    dp[0][0] = 0;
    ll i;
    for(i = 1; i < 1 << N; i++) {
        dp[0][i] = INF;
    }
}

ll sub(ll m, ll S) {
    if(dp[m][S] != -1) {
        return dp[m][S];
    }
    dp[m][S] = min(sub(m - 1, S), sub(m - 1, S & ~C[m - 1]) + A[m - 1]);
    return dp[m][S];
}

int main() {
    ll i, j, k;
    ll N, M;
    cin >> N >> M;
    init(N, M);
    for(i = 0; i < M; i++) {
        ll a, b;
        cin >> a >> b;
        A.push_back(a);
        ll ci = 0;
        for(j = 0; j < b; j++) {
            ll c;
            cin >> c;
            c--;
            ci = ci | 1 << c;
        }
        C.push_back(ci);
    }
    ll ans = sub(M, (1 << N) - 1);
    if(ans == INF) {
        cout << -1 << endl;
    } else {
        cout << ans << endl;
    }

    return 0;
}


Measured memory_bytes: 35464
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <bitset>
#include <cmath>
#include <iomanip>
#include <stack>
#include <set>
#include <queue>
#include <algorithm>
#include <deque>
#include <map>
#include <cmath>
#include <iomanip>
using namespace std;

#define INF 1e18
#define int long long
#define MAX 200010

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

    int cnt = 1;
    int ans = 0;
    while(cnt < b) {
        cnt += a - 1;
        ans++;
    }

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


Measured memory_bytes: 256
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define bug1( x ) {cerr << (#x) <<"="<< x << endl;}
#define bug2( x , y ) {cerr << (#x) <<"="<< (x) << "    " << (#y) << "="<< (y) << endl;}
#define bug3( x , y , z ) {cerr << (#x) <<"="<<(x) << "    " << (#y) <<"="<< (y) << "    " << (#z) <<"="<< (z) << endl;}
#define bug4( x , y , z , w) {cerr << (#x) <<"="<<(x) << "    " << (#y) <<"="<< (y) << "    " << (#z) <<"="<< (z) << "    " << (#w) <<"="<< w << endl;}
#define bug5( x , y , z , w ,p) {cerr << (#x) <<"="<<(x) << "    " << (#y) <<"="<< (y) << "    " << (#z) <<"="<< (z) << "    " << (#w) <<"="<< w << "    " << (#p) <<"="<< p << endl;}
#define bug6( x , y , z , w ,p , q) {cerr << (#x) <<"="<<(x) << "    " << (#y) <<"="<< (y) << "    " << (#z) <<"="<< (z) << "    " << (#w) <<"="<< w << "    " << (#p) <<"="<< p << "    " << (#q) <<"="<< q << endl;}
#define bugn( x , n ) {cerr << (#x) <<":";for(int i=0;i<n;i++)cerr << x[i] <<"  "; cerr << endl;}
#define bugnm( x , n , m ) {cerr << (#x)<<endl;for(int i=0;i<n;i++){cerr << "Row #" << i<< ":";for(int j=0;j<m;j++)cerr << x[i][j] << "   ";cerr << endl;}}
typedef long long ll;
typedef long double ld;
using namespace std;

const int maxn = 1e5+10, mod = 1e9+7;
int dp[maxn][13];
int32_t main(){
	IOS
	memset(dp,0,sizeof(dp));
	dp[0][0]=1;
	string s;cin>>s;
	int n = s.length();
	s = '$' + s;
	for(int i=1;i<=n;i++){
		for(int d = 0; d<10;d++){
			if( s[i] == '?' || s[i] -'0' == d ){
				for(int r = 0;r<13;r++){
					dp[i][(r*10+d)%13]+=dp[i-1][r];
					dp[i][(r*10+d)%13]%=mod;
				}
			}
		}
	}
	cout << dp[n][5];
	
	
 }
/*
 * long long or int?
 * index out of bound? 
 * Tested on own test case?corner?
 * Make more general solution.
 * Read Read Read Read ....
 */


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

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

  for (int i = 0; i <= 20; i++)
    for (int j = 0; j <= 14; j++) {
      if (4 * i + 7 * j == N) {
        puts("Yes");
        return 0;
      }
    }

  puts("No");
}

Measured memory_bytes: 256
#include "bits/stdc++.h"5 7 5
using namespace std;
typedef long long int ll;
typedef vector<ll> vl;
typedef pair<ll, ll> PP;
#define rep(i,n) for(ll i = 0; i < ll(n); i++)
#define all(v) v.begin() , v.end()
#define inputv(v,n) rep(i,n){\
    ll x;\
    cin>>x;\
    v.push_back(x);\
    }
const ll INF = 999999999999999;
const ll MOD = 1000000007;
ll a, b, c, d, e, f, p, t, x, y, z, q, m, n, r, h, k, w, l, ans = 0;
int main() {
	cin >> n;
	vl A(61, 0),B;
	rep(i, n) {
		cin >> x;
		rep(j, 61) {
			if (((1LL << j) & x) > 0)A[j]++;
		}
	}

	B.push_back(1);
	rep(i, 61) {
		B.push_back((B.back() * 2) % MOD);
	}

	rep(i, 61) {
		ans+=(((A[i] * (n - A[i])) % MOD)*B[i])%MOD;
	}

	cout << ans%MOD << endl;
}

Measured memory_bytes: 384
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define inf 1001001001
#define mod 1000000007
#define pi 3.141592653589793
#define all(v) v.begin(),v.end()
typedef vector<int> vi;
typedef vector<ll> vl;
ll gcd(ll a,ll b){
    if(b>a) swap(a,b);
    if(b==0) return a;
    return gcd(b,a%b);
}
ll lcm(ll a,ll b){
    ll g=gcd(a,b);
    return a/g*b;
}
ll rep_jijo(ll n,ll x){
    if(x==0) return 1;
    if(x%2==0){
        ll t=rep_jijo(n,x/2);
        return t*t%mod;
    }
    return n*rep_jijo(n,x-1)%mod;
}
ll com(ll n,ll r){
    ll x=1,y=1;
    ll tmp=n;
    while(tmp>=n-r+1){
        x=x*tmp%mod;
        tmp--;
    }
    while(r>0){
        y=y*r%mod;
        r--;
    }
    return x*rep_jijo(y,mod-2)%mod;
}

int main (){
    int n,k;
    cin >> n >> k;
    string s;
    cin >> s;
    int now=0;
    rep(i,k){
        if(s[now]=='R'){
            while(now<n&&s[now]=='R')now++;
            while(now<n&&s[now]=='L'){
                s[now]='R';
                now++;
            }
        }
        else{
            while(now<n&&s[now]=='L')now++;
            while(now<n&&s[now]=='R'){
                s[now]='L';
                now++;
            }
        }
        if(now==n) break;
    }
    int x=0;
    int ans=0;
    while(x<n){
        int tmp=x;
        if(s[x]=='R'){
            while(x<n&&s[x]=='R')x++;
        }
        else{
            while(x<n&&s[x]=='L')x++;
        }
        ans+=x-tmp-1;
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 512
#include <iostream>
#include <cctype>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <utility>
#include <string>
#include <functional>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <bitset>

#define PB push_back
#define MP make_pair
#define YES cout<<"YES"<<endl
#define Yes cout<<"Yes"<<endl
#define NO cout<<"NO"<<endl
#define No cout<<"No"<<endl
#define INF (1<<30)
#define LLINF (1<<60)
#define MOD 1000000007
#define REP(i, n) for(int i=0;i<n;i++)
using ll = long long;
using namespace std;

int main() {
    int a, b, c;
    cin >> a >> b >> c;
    if (a*b*c == 175)YES;
    else NO;
    return 0;
}


Measured memory_bytes: 256
#!/usr/bin/env python2
"""
This file is part of https://github.com/cheran-senthil/PyRival
Copyright 2019 Cheran Senthilkumar <hello@cheran.io>

"""
from __future__ import division, print_function

import itertools
import os
import sys
from atexit import register
from io import BytesIO


class dict(dict):
    """dict() -> new empty dictionary"""

    def items(self):
        """D.items() -> a set-like object providing a view on D's items"""
        return dict.iteritems(self)

    def keys(self):
        """D.keys() -> a set-like object providing a view on D's keys"""
        return dict.iterkeys(self)

    def values(self):
        """D.values() -> an object providing a view on D's values"""
        return dict.itervalues(self)


def gcd(x, y):
    """greatest common divisor of x and y"""
    while y:
        x, y = y, x % y
    return x


range = xrange

filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip

sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))

input = lambda: sys.stdin.readline().rstrip('\r\n')


def main():
    n = int(input())
    worth = 0

    for _ in range(n):
        x, u = input().split()
        if u == 'JPY':
            worth += float(x)
        else:
            worth += 380000 * float(x)

    print(worth)


if __name__ == '__main__':
    main()


Measured memory_bytes: 28652
#include<bits/stdc++.h>
#include<bits/extc++.h>
using namespace std;
int main(){
	//ios_base::sync_with_stdio(false);
	//cin.tie(NULL);
	//cout.tie(NULL);
	int T;
	cin>>T;
	while(T--){
		int n;
		cin>>n;
		long long sum=0;
		vector<pair<int, int>>v, v2;
		set<int>s, s2;
		for(int i=1;i<=n;i++){
			int k, l, r;
			cin>>k>>l>>r;
			if(l<r) v.push_back({l-r, k});
			else v2.push_back({l-r, k});
			sum+=r;
		}
		for(int i=1;i<=v2.size();i++) s2.insert(i);
		for(int i=v2.size()+1;i<=n;i++) s.insert(i);
		sort(v.begin(), v.end());
		sort(v2.begin(), v2.end());
		reverse(v2.begin(), v2.end());
		for(auto [x, y]:v){
			auto it=s.upper_bound(y);
			if(it==s.end()) sum+=x;
			else s.erase(it);
		}
		for(auto [x, y]:v2){
			auto it=s2.upper_bound(y);
			if(it!=s2.begin()){
				it--;
				s2.erase(it);
				sum+=x;
			}
		}
		cout<<sum<<"\n";
	}
}

Measured memory_bytes: 14152
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include <algorithm>
#include <functional>

using namespace std;
const double PI = 3.14159265358979323846;

int main()
{
	int R;
	double L;
	cin >> R;

	L = double(PI * R * 2);

	cout << L;
	return 0;
}

Measured memory_bytes: 3776
n,k,q=map(int,input().split())
a=[int(input()) for i in range(q)]

kaisuu=[0 for i in range(n)]

for i in a:
  kaisuu[i-1]+=1

for i in kaisuu:
  if k-q+i>0:
    print("Yes")
  else:
    print("No")

Measured memory_bytes: 8644
N=int(input())
L=list(map(int,input().split()))
L.sort()
cnt=0
for i in range(len(L)-2):
  for j in range(i+1,len(L)-1):
    for k in range(j+1,len(L)):
      if L[k]<L[j]+L[i]:
        if L[k]!=L[j] and L[j]!=L[i]:
          cnt+=1
print(cnt)

Measured memory_bytes: 9188
import java.util.*;

public class Main{

    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);

        // input
        long n = scan.nextLong();    // s
        long m = scan.nextLong();   // c
        
        // output
        if(m < 2){
            System.out.println(0);
        } else if(m < n * 2){
            System.out.println(Math.min(m / 2, n));
        } else {
            System.out.println(n + (m - n * 2) / 4);
        }
    }
}

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

typedef long long ll;
typedef vector<ll> vint;
typedef vector< vector<ll> > vvint;

#define rep(i,n) for(ll i=0;i<n;i++)
#define repf(i,f,n) for(ll i=f;i<n;i++)
#define repr(i,n) for(ll i=n-1;i>=0;i--)
#define mp make_pair
#define mt make_tuple
#define ALL(obj) (obj).begin(), (obj).end()
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; }

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


ll h,w,k;

ll x1,x2,Y1,y2;

using P = pair<ll,ll>;
vector<vector<P>> dist[4];

vector<vector<char>> c;

P getDist(ll x, ll y, ll dir){
    // puts("getDist");
    return dist[dir][x][y];
}

void setDist(ll x, ll y, ll dir, P d){
    // puts("setDist");
    dist[dir][x][y] = d;
}

int main() {
    cout<<fixed<<setprecision(10);

    cin>>h>>w>>k;
    cin>>x1>>Y1;
    cin>>x2>>y2;

    c.resize(h+2, vector<char>(w+2, '@'));
    rep(i,h)rep(j,w) cin>>c[i+1][j+1];

    rep(i,4) dist[i].resize(h+2, vector<P>(w+2, make_pair(LLONG_MAX, 0ll)));

    // for(auto row:c){
    //     for(auto e:row) cout<<e; cout<<endl;
    // }

    using T = tuple<P, ll, ll, ll>; // dist, dir, x, y
    priority_queue<T, vector<T>, greater<T>> pq;

    rep(dir, 4) pq.push(make_tuple(make_pair(1ll, -k), dir, x1, Y1));



    while(!pq.empty()){
        P d;
        ll dir, x, y;
        tie(d, dir, x, y) = pq.top(); pq.pop();

        // cout<<d.first<<" "<<d.second<<": ";
        // for(auto e:{dir,x,y}) cout<<e<<" "; cout<<endl;


        if(getDist(x, y, dir) <= d) continue;
        setDist(x, y, dir, d);

        ll nx, ny;
        nx = x + dx[dir];
        ny = y + dy[dir];


        P nd = d;
        nd.second++;
        if(nd.second>0){
            nd.first++;
            nd.second -= k;
        }
        if(c[nx][ny] != '@' and getDist(nx, ny, dir) > nd){
            pq.push(make_tuple(nd, dir, nx, ny));
        }


        rep(i,4){
            if(dir == i) continue;
            P nd = d;
            nd.first++;
            nd.second = -k;
            if(getDist(x, y, i) <= nd) continue;
            pq.push(make_tuple(nd, i, x, y));
        }
    }

    ll ans = LLONG_MAX;

    rep(i,4){
        // cout<<getDist(x2,y2,i)<<endl;
        chmin(ans, getDist(x2, y2, i).first);
    }

    if(ans == LLONG_MAX) cout<<-1<<endl;
    else cout<<ans<<endl;



    return 0;

}

Measured memory_bytes: 209204
A = int(input())
B = int(input())
C = int(input())
X = int(input())

count = 0


for i in range(A + 1):
    for j in range(B + 1):
        for k in range(C + 1):
            total = 500 * i + 100 * j + 50 * k
            if X == total:
                count += 1
print(count)

Measured memory_bytes: 9164
#include <iostream>
#include <vector>

using namespace std;
typedef long long ll;

int main(){
    ll n, m;
    cin >> n >> m;
    vector<ll> count(m, 0);
    for(int i = 0; i < n; ++i){
        ll k;
        cin >> k;
        for(int j = 0; j < k; ++j){
            ll a;
            cin >> a;
            a--;
            count.at(a)++;
        }
    }
    ll ans = 0;
    for(ll x : count){
        ans += (x == n);
    }
    cout << ans << endl;
    return 0;
}


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

using ll = long long;
using Vi = vector<int>;
using Vl = vector<ll>;
using Pii = pair<int, int>;
using Pll = pair<ll, ll>;

constexpr int I_INF = numeric_limits<int>::max();
constexpr ll L_INF = numeric_limits<ll>::max();

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

class Prints {
private:
    class __Prints {
    public:
        __Prints(const char* sep, const char* term) : sep(sep), term(term) {}
        template <class... Args>
        void operator()(const Args&... args) const { print(args...); }

    private:
        const char *sep, *term;
        void print() const { std::cout << term; }
        void print_rest() const { std::cout << term; }
        template <class T, class... Tail>
        void print(const T& head, const Tail&... tail) const { std::cout << head, print_rest(tail...); }
        template <class T, class... Tail>
        void print_rest(const T& head, const Tail&... tail) const { std::cout << sep << head, print_rest(tail...); }
    };

public:
    Prints() {}
    __Prints operator()(const char* sep = " ", const char* term = "\n") const { return __Prints(sep, term); }
};

Prints prints;

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Pll dp[81][2];

void solve() {
    ll N;
    cin >> N;
    Vl A(N);
    for (ll i = 0; i < N; i++) {
        cin >> A[i];
    }
    dp[0][0] = {1000, 0};
    for (ll i = 0; i < N; i++) {
        ll t1 = dp[i][0].first + dp[i][0].second * A[i];
        ll t2 = dp[i][1].first + dp[i][1].second * A[i];
        ll mx = max(t1, t2);
        dp[i + 1][0] = {mx, 0};
        ll u = mx / A[i];
        dp[i + 1][1] = {mx - u * A[i], u};
    }
    prints()(dp[N][0].first);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

int main() {
#ifdef FASTIO
    cin.tie(nullptr), cout.tie(nullptr);
    ios::sync_with_stdio(false);
#endif
#ifdef FILEINPUT
    ifstream ifs("./in_out/input.txt");
    cin.rdbuf(ifs.rdbuf());
#endif
#ifdef FILEOUTPUT
    ofstream ofs("./in_out/output.txt");
    cout.rdbuf(ofs.rdbuf());
#endif
    cout << setprecision(18) << fixed;
    solve();
    cout << flush;
    return 0;
}

Measured memory_bytes: 3656
#include <iostream>
using namespace std;
int main(void){
    long n,min,max,sum,a;
    cin >> n;
    cin >> a;
    sum=a;
    min=a;
    max=a;
    for(int i=1;i<n;i++){
    cin >> a;
    sum=sum+a;
        if(min>a){
        min=a;
        }
        if(max<a){
        max=a;
        }
    }
    cout << min <<" "<< max <<" "<< sum << endl;
}


Measured memory_bytes: 3096
import bisect

N, M = map(int, input().split())
P = [0 for _ in range(M)]
Y = [0 for _ in range(M)]
y_p = [[] for _ in range(N+1)]
for i in range(M):
    P[i], Y[i] = map(int, input().split())
    y_p[P[i]].append(Y[i])

for p in set(P):
    y_p[p].sort()

for p, y in zip(P, Y):
    order = bisect.bisect_left(y_p[p], y)+1
    ans = str(p).zfill(6) + str(order).zfill(6)
    print(ans)

Measured memory_bytes: 28932
n, m = input().split(" ")
n = int(n)
m = int(m)
k = []
for i in range(n):
    k.append([])
    tmp = input().split(" ")
    for j in range(1, len(tmp)):
        k[i].append(int(tmp[j]))

dict = {}
for i in range(1, m+1):
    dict[i] = 0

for i in k:
    for j in i:
        dict[j] += 1

cnt = 0
for i in range(1, m+1):
    if dict[i] == n:
        cnt += 1

print(cnt)



Measured memory_bytes: 3064
/*

 Remember, Hope is a good thing... May be the best of things... and No Good thing ever Dies !!!

*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define IOS ios::sync_with_stdio(0); cout.tie(0);
#define endl "\n"
#define MOD 1000000007
const ll inf=(1LL<<60)-1;
int dx[]= {-1,1,0,0};
int dy[]= {0,0,-1,1};
void solve()
{
    //freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
  ll n;
  cin>>n;
  ll l=n/100;
  ll r=n%100;
  if(1<=l && l<=12)
  {
      if(1<=r && r<=12)
        cout<<"AMBIGUOUS"<<endl;
      else
        cout<<"MMYY"<<endl;
  }
  else
  {
      if(1<=r && r<=12)
        cout<<"YYMM"<<endl;
      else
        cout<<"NA"<<endl;
  }

}
int main()
{
    IOS;
    //ll t;
    //cin>>t;
    //while(t--)
    solve();
    return 0;
}


Measured memory_bytes: 3636
/* ex4_3
   kento_titech*/
#include<stdio.h>
int snow_height(int h_west,int h_east);//積雪を求める関数のプロトタイプ宣言
int main(void){
    int a,b;//a,bはそれぞれ西と東に見える高さ
    scanf("%d %d",&a,&b);
    printf("%d\n",snow_height(a,b));

    return 0;
}
int snow_height(int h_west,int h_east){//h_west,h_eastはそれぞれ西と東に見える部分の高さ
    int height;
    height=(h_east-h_west)*(h_east-h_west+1)/2-h_east;//1からh_east-h_westまでの総和が東側の塔の高さ。
                                                      //積雪heightはそこからh_eastを引いたもの.
    return(height);

    }

Measured memory_bytes: 128
#include <bits/stdc++.h>
#define REP(i, s, n) for (int i = s; i < (int)(n); i++)
#define ALL(a) a.begin(), a.end()
#define MOD 1000000007
using namespace std;
using ll = long long;

int main() {
    int N, K; cin >> N >> K;
    vector<ll> A(N);
    REP(i, 0, N) cin >> A[i];

    vector<ll> S;
    REP(i, 0, N) {
        S.push_back(A[i]);
        REP(j, i + 1, N) {
            S.push_back(S.back() + A[j]);
        }
    }

    vector<vector<int>> sbits(S.size(), vector<int>(40, 0));
    REP(i, 0, S.size()) {
        ll tmp = S[i];
        REP(j, 0, 40) {
            sbits[i][j] = tmp & 1;
            tmp >>= 1;
            if (tmp == 0) break;
        }
    }

    ll ans = 0;
    vector<int> idxs(S.size());
    iota(ALL(idxs), 0);
    for (int i = 39; i >= 0; i--) {
        // cout << "# bit : " << i << endl;
        vector<int> next;
        for (auto j : idxs) if (sbits[j][i]) {
            next.push_back(j);
            // cout << "--> " << S[j] << endl;
        }
        if ((int)next.size() >= K) {
            // cout << "--> found more than K" << endl;
            idxs = next;
            ans += (1LL << i);
        } else {
            continue;
        }
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 107688
maxn = 0
minn = 0
f = 0
while True:
    try:

        a = float(raw_input())

        if f == 0:
            maxn = a
            minn = a
            f = 1

        if a > maxn:
            maxn = a

        if a < minn:
            minn = a

    except EOFError:
        break

print maxn-minn

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

using namespace std;

int main()
{
	// 入力
	int N;
	cin >> N;
	vector<int> d(N);
	for (int i = 0; i < N; i++)
	{
		cin >> d[i];
	}
	// 昇順にソート
	sort(d.begin(), d.end());
	
	int answer = 0;
	// ABC問題の最大値 < K <= ARC用問題の最小値
	// K = ARC用問題の最小値 - ABC問題の最大値
	answer = d[d.size() / 2] - d[d.size() / 2 - 1];
	
	// 出力
	cout << answer << endl;
	
	return 0;
}

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

#define ll long long
#define mod 1000000007
#define what_is(x) cerr << #x << " is " << x << endl;

ll t, N, D, MAXX = 127;

int main() {
	cin>>t;
	while(t--) {
		cin>>N>>D;
		ll ans = 0;
		for(int i=0;i<N-1;i++) {
			ans += MAXX;
			D = MAXX ^ D;
		}
		ans += D;
		cout<<ans<<"\n";
	}
	return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
#define ll  long long
#define endl '\n'
const ll mod = 1000000007;
const double PI = 3.141592653589793238463;
using namespace std;
int main()
{
    ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
    int x;
    cin>>x;
    int y[x+1];
    ll sum=0;
    for (int i=1;i<=x;i++){
        cin>>y[i];
        sum+=y[i];
    }
    int m;
    cin>>m;
    int r,l;
    for (int i=0;i<m;i++){
        cin>>r>>l;
        cout<<sum-(y[r]-l)<<endl;
    }
    return 0;
}


Measured memory_bytes: 256
#include <stdio.h>
#include <algorithm>

int A[4], B[4];

int main(void) {
	for (int i = 0; i < 4; ++i) { scanf("%d", &A[i]); }
	for (int i = 0; i < 4; ++i) { scanf("%d", &B[i]); }

	printf("%d\n", std::max(A[0] + A[1] + A[2] + A[3], B[0] + B[1] + B[2] + B[3]));
	return 0;
}

Measured memory_bytes: 2620
ide = 2**31-1
def func(a,b):
  return min(a,b)
class SegmentTree:
  def __init__(self,ls,commutative = True):
    if commutative:
      self.n = len(ls)
      self.tree = [ide for i in range(self.n)]+ls
    else:
      self.n = 2**((len(ls)-1).bit_length())
      self.tree = [ide for i in range(self.n)]+ls+[ide for i in range(self.n-len(ls))]
    for i in range(1,self.n)[::-1]:
      self.tree[i] = func(self.tree[i<<1|0],self.tree[i<<1|1])
  def getall(self):
    return self.tree[1]
  def get(self,l,r):
    ret = ide
    l += self.n
    r += self.n
    while l < r:
      if l&1:
        ret = func(self.tree[l],ret)
        l += 1
      if r&1:
        ret = func(ret,self.tree[r-1])
      l >>= 1
      r >>= 1
    return ret
  def update(self,i,x):
    i += self.n
    self.tree[i] = x
    while i > 1:
      i >>= 1
      self.tree[i] = func(self.tree[i<<1|0],self.tree[i<<1|1])
import sys
input = sys.stdin.readline
n,q = map(int,input().split())
a = [2**31-1]*n
sol = SegmentTree(a,commutative=False)
for _ in range(q):
  a,b,c = map(int,input().split())
  if a == 0:
    sol.update(b,c)
  else:
    print(sol.get(b,c+1))


Measured memory_bytes: 10448
#include <iostream>
#include <iomanip>
#include <string>
#include <string.h>
#include <math.h>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <utility>
#include <deque>
#include <queue>

#define rep(i, n) for(int i = 0; i < n; ++i)
#define REP(i, m, n) for(int i = m; i < n; ++i)
#define rrep(i,n) for(int i = n; i >= 0; --i)
#define RREP(i, m, n) for(int i = n; i >= m; --i)

typedef long long ll;
typedef unsigned long long ull;
typedef std::pair<int, int> pii;
typedef std::pair<long long, long long> pll;

using namespace std;

const long long MOD = 1000000007;

typedef class UnionFind {
private:
	int n;
	int* par;
	int* hight;

	int root(int a) {
		while (par[a] != a) a = par[a];
		return a;
	}
public:
	UnionFind(int num) {
		n = num;
		par = new int[n];
		hight = new int[n];
		for (int i = 0; i < n; ++i) {
			par[i] = i;
			hight[i] = 1;
		}
	}
	~UnionFind() {
		delete[] par;
	}

	void unite(int a, int b) {
		int ra = root(a);
		int rb = root(b);
		if (ra == rb) return;
		
		if (hight[ra] > hight[rb]) {
			par[rb] = ra;
		}
		else if (hight[ra] < hight[rb]) {
			par[ra] = rb;
		}
		else {
			par[ra] = rb;
			++hight[rb];
		}
	}
	bool same(int a, int b) {
		return root(a) == root(b);
	}

	int numofRoot() {
		int counter = 0;
		for (int i = 0; i < n; ++i) if (par[i] == i) ++counter;
		return counter;
	}
} Uf;

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

	int n, m;
	cin >> n >> m;
	Uf p(n);

	rep(i, m) {
		int x, y, z;
		cin >> x >> y >> z;
		
		p.unite(x - 1, y - 1);
	}

	cout << p.numofRoot() << "\n";

	return 0;
}


Measured memory_bytes: 1024
#include <iostream>

using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;
    if (b != 1){
    int ans = 1;
    int curr = a;
    while (curr < b){
        curr += a;
        ans++;
        curr--;
    }
    cout << ans << endl;
    } else cout << 0 << endl;
    return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
#define mod 1000000007
using namespace std;
int n,k,a[2000],dp[2000],tp;
int qpow(int a,int b){
	int ans=1,tmp=a;
	for(;b;b>>=1,tmp=1ll*tmp*tmp%mod)
		if(b&1)ans=1ll*ans*tmp%mod;
	return ans;
}
int main(){
	scanf("%d%d",&n,&k);
	for(int i=1;i*i<=n;i++)if(n%i==0){
		a[++tp]=i;
		if(i*i!=n)a[++tp]=n/i;
	}
	sort(a+1,a+tp+1);
	for(int i=1;i<=tp;++i){
		dp[i]=qpow(k,(a[i]+1)/2);
		for(int j=1;j<i;++j)if(a[i]%a[j]==0)
			dp[i]=(dp[i]-dp[j]+mod)%mod;
	}
	int ans=0;
	for(int i=1;i<=tp;++i)
		ans=(ans+1ll*(a[i]&1?a[i]:a[i]/2)*dp[i])%mod;
	printf("%d",ans);
}

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

int main() {
	int n, h, ans=0;
	cin >> n >> h;
	vector<int> a(n), b(n);
	rep(i,n) cin >> a[i] >> b[i];
	int m = 0;
	rep(i,n) m = max(m,a[i]);
	sort(b.begin(), b.end());
	int i = n - 1;
	while (h > 0) {
		if (b[i] > m && i >= 0) {
			h -= b[i];
			i--;
			ans++;
		}
		else {
			ans += (h + m - 1) / m;
			h = 0;
		}
	}
	cout << ans << endl;
	return 0;
}


Measured memory_bytes: 3952
#include<cstdio>
#include<iostream>
using namespace std;
int n,k,doe,ans,num;
int pre[5050],now[2020],son[5050];
void add(int x,int y)
{
	++doe;
	pre[doe]=now[x];
	now[x]=doe;
	son[doe]=y;
}
void dfs(int x,int deep,int fa)
{
	if (deep>k) return;
	++num;
	int p=now[x];
	while (p)
	{
		int y=son[p];
		if (y!=fa) dfs(y,deep+1,x);
		p=pre[p];
	}
}
int main()
{
	scanf("%d%d",&n,&k);
	int x,y;
	for (int i=1;i<n;++i)
	{
		scanf("%d%d",&x,&y);
		add(x,y);
		add(y,x);
	}
	if (k%2==0)
	{
		k/=2;
		for (int i=1;i<=n;++i)
			num=0,dfs(i,0,0),ans=max(ans,num);
	}
	else
	{
		k/=2;
		for (int i=1;i<=n;++i)
		{
			int p=now[i];
			while (p)
			{
				int j=son[p];
				num=0;
				dfs(i,0,j);
				dfs(j,0,i);
				ans=max(num,ans);
				p=pre[p];
			}

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

Measured memory_bytes: 384
#define NDEBUG
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <type_traits>


using namespace std;

// template {{{
#ifdef NDEBUG
# define dump(x)
# define debug if (0)
#else
# define dump(x) cerr << "dump: " << __LINE__ << "] " << (#x) << " = " << x << endl
# define debug
#endif
template <class T>
false_type is_container_impl(...);
template <class T, class = typename T::iterator>
true_type is_container_impl(T);
template <class T>
struct is_container : decltype(is_container_impl<T>(declval<T>())) {};
template <>
struct is_container <string> : std::false_type {};
template <class Container, class = enable_if_t<is_container<Container>{}>>
istream& operator>> (istream& is, Container& cont) {
  for (auto& v : cont) is >> v;
  return is;
}
template <class Container, class = enable_if_t<is_container<Container>{}>>
ostream& operator<< (ostream& os, Container const& cont) {
  bool first = true;
  for (auto const& v : cont) {
    if (!first) {
      os << ' ';
    }
    first = false;
    os << v << ' ';
  }
  if (is_container<typename Container::value_type>{})
    os << '\n';
  return os;
}
template <class T, class U>
ostream& operator<< (ostream& os, pair<T, U> p) {
  os << '(' << p.first << ", " << p.second << ')';
  return os;
}
// }}}

using ll = long long;
constexpr ll Mod = 1000000007;

ll modpow(ll x, ll k = Mod - 2) {
  if (k == 0) return 1;
  ll prev = modpow(x, k / 2),
     pp = (prev * prev) % Mod;
  if (k % 2 == 0)
    return pp;
  else
    return (pp * x) % Mod;
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  ll n, k;
  cin >> n >> k;
  if (k >= n) k = n - 1;
  vector<ll> factorials(n + 1);
  factorials[0] = 1;
  for (ll i = 1; i <= n; i++) {
    factorials[i] = factorials[i - 1] * i;
    factorials[i] %= Mod;
  }
  ll ans = 0;
  for (ll i = 0; i <= k; i++) {
    ll pats = 1;
    pats *= factorials[n];
    pats %= Mod;
    pats *= factorials[n - 1];
    pats %= Mod;
    dump(pats);
    pats *= modpow(factorials[i]);
    pats %= Mod;
    dump(pats);
    pats *= modpow(factorials[i]);
    pats %= Mod;
    dump(pats);
    pats *= modpow(factorials[n - i]);
    pats %= Mod;
    dump(pats);
    pats *= modpow(factorials[n - i - 1]);
    pats %= Mod;
    dump(i);
    dump(factorials[i]);
    dump(factorials[n - i]);
    dump(pats);
    ans += pats;
    ans %= Mod;
  }
  cout << ans << endl;
}



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

#define LL long long

int ans=0;
vector<int> G[100009];
bool mark[100009];

void dfs(int s){
	mark[s] = true;
	for(int i=0;i<(int)G[s].size();i++){
		int v = G[s][i];
		if(!mark[v]){
			dfs(v);
		}
	}
}

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

	int n,m;
	cin>>n>>m;

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

		G[a].push_back(b);
		G[b].push_back(a);
	}

	for(int i=1;i<=n;i++){
		if(!mark[i]){
			dfs(i);
			ans++;
		}
	}
	cout<<ans<<endl;

}

Measured memory_bytes: 10496
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1LL << 60;

int main() {
    int n;
    cin >> n;
    vector<int> a(n), b(n), c(n);
    c.at(n - 1) = -1;
    for (int i = 0; i < n; i++) {
        cin >> a.at(i);
    }
    for (int i = 0; i < n; i++) {
        cin >> b.at(i);
    }
    for (int i = 0; i < n - 1; i++) {
        cin >> c.at(i);
    }
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += b.at(a.at(i) - 1);
    }
    for (int i = 0; i < n - 1; i++) {
        if (a[i + 1] - a[i] == 1) {
            sum += c[a[i] - 1];
        }
    }
    cout << sum << endl;
    return 0;
}

Measured memory_bytes: 3668
import java.util.*;
import java.util.Map.*;

class Main{
	public static void main(String[] A){
		Scanner s=new Scanner(System.in);
		TreeMap<Integer,Integer> m=new TreeMap<>();
		while(true){
			int n=s.nextInt(),v=s.nextInt();
			if(n+v==0)
				return;
			m.clear();

			for(int i=0;i<n;++i)
				m.merge(s.nextInt(),1,Integer::sum);

			int r=-1;
			for(Entry<Integer,Integer> i:m.entrySet()){
				int k=i.getKey();
				Integer a=m.floorKey(v-k);
				if(a!=null&&a==k&&i.getValue()==1)
					a=m.floorKey(k-1);
				if(a!=null)
					r=Math.max(r,a+k);
			}
			System.out.println(r==-1?"NONE":r);
		}
	}
}



Measured memory_bytes: 48820
require 'prime'
require 'set'
require 'tsort'
include Math
ALP = ('a'..'z').to_a
INF = 0xffffffffffffffff
def max(a,b);              a > b ? a : b                              end
def min(a,b);              a < b ?  a : b                             end
def swap(a,b);             a, b = b, a                                end
def gif;                   gets.to_i                                  end
def gff;                   gets.to_f                                  end
def gsf;                   gets.chomp                                 end
def gi;                    gets.split.map(&:to_i)                     end
def gf;                    gets.split.map(&:to_f)                     end
def gs;                    gets.chomp.split.map(&:to_s)               end
def gc;                    gets.chomp.split('')                       end
def pr(num);               num.prime_division                         end
def pr?(num);              Prime.prime?(num)                          end
def digit(num);            num.to_s.length                            end
def array(s,ini=nil);      Array.new(s){ini}                          end
def darray(s1,s2,ini=nil); Array.new(s1){Array.new(s2){ini}}          end
def rep(num);              num.times{|i|yield(i)}                     end
def repl(st,en,n=1);       st.step(en,n){|i|yield(i)}                 end

n, a, b = gi
ct = 0
repl 1,n do |num|
tmp = (eval num.to_s.split('').join('+'))
ct += num if tmp >= a && tmp <= b
end
puts ct


Measured memory_bytes: 3324
import sys
#from io import StringIO
#import unittest

class UnionFind():
    # 作りたい要素数nで初期化
    # 使用するインスタンス変数の初期化
    def __init__(self, n):
        self.n = n
        # root[x]<0ならそのノードが根かつその値が木の要素数
        # rootノードでその木の要素数を記録する
        self.root = [-1]*(n+1)
        # 木をくっつける時にアンバランスにならないように調整する
        self.rnk = [0]*(n+1)

    # ノードxのrootノードを見つける
    def Find_Root(self, x):
        if(self.root[x] < 0):
            return x
        else:
            # ここで代入しておくことで、後の繰り返しを避ける
            self.root[x] = self.Find_Root(self.root[x])
            return self.root[x]
    # 木の併合、入力は併合したい各ノード
    def Unite(self, x, y):
        # 入力ノードのrootノードを見つける
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        # すでに同じ木に属していた場合
        if(x == y):
            return 
        # 違う木に属していた場合rnkを見てくっつける方を決める
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x

        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            # rnkが同じ（深さに差がない場合）は1増やす
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    # xとyが同じグループに属するか判断
    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)

    # ノードxが属する木のサイズを返す
    def Count(self, x):
        return -self.root[self.Find_Root(x)]

def resolve():
    int1 = lambda x: int(x) - 1
    readline=sys.stdin.readline

    n,m,k=map(int, readline().strip().split())

    uf = UnionFind(n)

    exc=[0]*n

    for i in range(m):
        a,b=map(int1, readline().strip().split())
        uf.Unite(a,b)
        exc[a]+=1
        exc[b]+=1
    
    for i in range(k):
        a,b=map(int1, readline().strip().split())
        if uf.isSameGroup(a,b):
            exc[a]+=1
            exc[b]+=1
    
    rescnt=[]

    for i in range(n):
        #ri=uf.Count(i)-1-exc[i]
        #rescnt.append(str(ri))
        if i==(n-1):
            print(uf.Count(i)-1-exc[i])
        else:
            print(uf.Count(i)-1-exc[i],end=" ")
    
        #print(" ".join(rescnt),end="")

resolve()

Measured memory_bytes: 7188
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <map>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <string.h>
#include <cstdio>
#include <tuple>
#include <numeric>
using namespace std; using ll = long long; using ld = long double;  using pll = pair<ll, ll>;
using vl = vector<ll>; using vll = vector<vl>; using vpll = vector<pll>;
using vs = vector<string>; using tll = tuple<ll, ll, ll>; using vtll = vector<tll>;
const ld PI = 3.1415926535897932;
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define co(i) cout << i << endl;
#define co2(i,j) cout << i << " " << j << endl;
#define co3(i) cout << i << " ";
#define po(i) cout << i.first << " " << i.second << endl;
void in() {}
void debug_out() { cerr << endl; }
template<typename Head, typename... Tail>
void debug_out(Head h, Tail... t) {
	cerr << " " << h;
	if (sizeof...(t) > 0) cerr << " :";
	debug_out(t...);
}
template <typename T>
ostream& operator<<(ostream& os, vector<T> vec) {
	for (size_t i = 0; i < vec.size(); i++)os << vec[i] << (i + 1 == vec.size() ? "" : " ");
	return os;
}
ll ctoi(char c) {
	switch (c) {
	case '0': return 0; case '1': return 1; case '2': return 2;
	case '3': return 3; case '4': return 4; case '5': return 5;
	case '6': return 6; case '7': return 7; case '8': return 8;
	case '9': return 9;  default: return 0;
	}
}
bool pairCompare(const pll firstElof, pll secondElof)
{
	return firstElof.first > secondElof.first;
}
//**Snippetリスト**//
//rep, vin, all, iteLoop, bitSearch, bitList, nod//
//gcdlcm, isPrime, eratos, primeFactorize, Npow, combination, divisor, modinv, doubling, digitDP//
//dfs, bfs, dijkstra, WarshallFloyd, BellmanFord, UnionFind, Kruskal, RMQ, LCA//
ll i, j, k, l; ll N, M, K, H, W, L, X, Y, Z, R, Q;
ll MOD = 1000000007, INF = 1LL << 60, ans = 0, z = 0, o = 1;
vl flag, D; vpll path;
//***********//
int main() { 
	cin >> N >> Q;
	string S;
	cin >> S;
	vector<char> T(Q), D(Q);
	for (k = 0; k < Q; k++) {
		cin >> T[k] >> D[k];
	}
	reverse(T.begin(), T.end());
	reverse(D.begin(), D.end());
	ll right = N;
	ll left = -1;
	ll L = 0, R = 0;
	for (k = 0; k < Q; k++) {
		if (right <= left) {
			cout << 0;
			exit(0);
		}
		else {
			//debug(T[k], S[left+1]);
			if (T[k] == S[left + 1] && D[k] == 'L') left++;
			else if (left >= 0) {
				if (T[k] == S[left] && D[k] == 'R') left--;
			}
			if (T[k] == S[right - 1] && D[k] == 'R') right--;
			else if (right <= N-1) {
				if (T[k] == S[right] && D[k] == 'L') right++;
			}
			//debug(left, right);
		}
	}
	
	cout << N - (left + 1) - (N - right);
}

Measured memory_bytes: 900