akhauriyash/Code-Regression huggingface dataset:
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i=(a),i##formax=(b);i<i##formax;i++)
#define FORR(i,a,b) for(int i=(a),i##formax=(b);i>=i##formax;i--)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define pcnt __builtin_popcount
#define sz(x) (int)(x).size()
#define maxs(x,y) x=max(x,y)
#define mins(x,y) x=min(x,y)
#define show(x) cout<<#x<<" = "<<x<<endl;
#define all(a) (a.begin()),(a.end())
#define each(it,c) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();it++)
#define perm(c) sort(all(c));for(bool c##p=1;c##p;c##p=next_permutation(all(c)))
#define bitComb(a,n,k) for(int a##x,a##y,a=(1<<k)-1;a<(1<<n);a##x=a&-a,a##y=a+a##x,a=(((a&~a##y)/a##x)>>1)|a##y)
#define bit(n) (1LL<<(n))
#define randInt(l,r) (uniform_int_distribution<ll>(l,r)(rnd))
#define randDouble(l,r) (uniform_real_distribution<double>(l,r)(rnd))
#define dout(d) printf("%.12f\n",d)

typedef long long ll;
typedef __int128_t lll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
template<class T>using V=vector<T>;
template<class T>using VV=V<V<T>>;
template<class T,class Y>ostream& operator<<(ostream&o,const pair<T,Y>&p){return o<<"("<<p.fi<<","<<p.se<<")";}
template<class T>ostream& operator<<(ostream&o,V<T>&v){for(T&t:v)o<<t<<",";return o<<endl;}
template<typename A,size_t N,typename T>void Fill(A (&array)[N],const T&v){fill((T*)array,(T*)(array+N),v);}
template<typename T>void uniq(V<T>&v){sort(all(v));v.erase(unique(all(v)), v.end());}
lll gcd(lll a,lll b,lll &x,lll &y){if(!b){x=1;y=0;return a;}lll d=gcd(b,a%b,y,x);y-=a/b*x;return d;}
ll modInv(ll a,ll m){lll x,y;gcd(a,m,x,y);return (x%m+m)%m;}
ll modPow(lll a,lll n,ll m){if(!a)return a;lll p=1;for(;n>0;n>>=1,a=a*a%m)if(n&1)p=p*a%m;return(ll)p;}
bool isPrime(ll n){if(n<2||n%2==0)return n==2;lll t=n-1,d=t/(t&-t);for(lll a:{2,325,9375,28178,450775,9780504,1795265022})if(a%n){for(t=d,a=modPow(a,t,n);t!=n-1&&a!=1&&a!=n-1;a=a*a%n,t=t*2%n);if(a!=n-1&&t%2==0)return 0;}return 1;}
//V<ll>fac,rfac;void setFac(int n,int mod){fac=rfac=V<ll>(++n);fac[0]=1;FOR(i,1,n)fac[i]=fac[i-1]*i%mod;rfac[n-1]=modInv(fac[n-1],mod);FORR(i,n-1,1)rfac[i-1]=rfac[i]*i%mod;}
const int IINF = 1e9+6;
const ll LINF = 1e18;
const int MOD = 1e9+7;
const double PI = acos(-1);
const double EPS = 1e-10;
static random_device rd;
static mt19937 rnd(rd());

const int N = 1e5;
int n;
multiset<int> s;
V<int> v;
main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  cin >> n;
  FOR(i, 0, bit(n)){
    int a;
    cin >> a;
    s.insert(IINF-a);
  }
  {
    auto itr = s.upper_bound(0);
    v.pb(*itr);
    s.erase(itr);
  }
  FOR(i, 0, n) FOR(j, 0, bit(i)){
    auto itr = s.upper_bound(v[j]);
    if(itr == s.end()){
      cout << "No" << endl;
      return 0;
    }
    v.pb(*itr);
    s.erase(itr);
  }
  cout << "Yes" << endl;
}

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

using namespace std;

int main(void)
{
    int K,X;

    cin >> K;
    cin >> X;

    for(int i=0;i<2*K-1;i++){
        cout<< X-K+1+i;
        if(i != 2*K-1){
            cout << " ";
        }
    }
    cout << "" << endl;

    return 0;
}

Measured memory_bytes: 256
#/*
    AUTHOR:shivam51
    IIESTS
*/
  #include<bits/stdc++.h>
  using namespace std;
  //
  #define add accumulate
  #define ll long long int
  #define ff first
  #define ss second
  #define pb push_back
  #define mp make_pair
  #define vll vector<ll>
  #define lb lower_bound
  #define ub upper_bound
  #define pll pair<ll,ll>
  #define vpll vector<pll>
  #define all(v) v.begin(), v.end()
  #define rep(i,k,n) for(int i=k;i<n;i++)
  #define hs ios_base::sync_with_stdio(false);cin.tie(NULL);
  const ll mod=1e9+7;
  const ll MAX=1e5+18;
  //
  //
  	ll dp[MAX];
  	void solve(){
  		ll n,k,t;
  		cin>>n>>k;
  		int temp[n+10];
  		rep(i,0,n+10)
  			temp[i]=1;
  		rep(i,0,k){
  			cin>>t;
  			temp[t]=0;
  			if(t!=1)
  				if(temp[t]==0&&temp[t-1]==0){
  					cout<<'0';return ;
  				}
  		}
  		dp[0]=1;dp[1]=temp[1];
  		rep(i,2,n+1){
  			if(temp[i-1]==0)
	  			dp[i]=dp[i-2];
	  		else if(temp[i-2]==0)
	  			dp[i]=dp[i-1];
	  		else
	  			dp[i]=dp[i-1]+dp[i-2];
  			dp[i]%=mod;
  		}
  		cout<<dp[n];
  	}
	int main(){ 
		hs;
		ll t;
		// cin>>t;
		t=1;
		while(t--)
			solve();
    return 0; 
} 

Measured memory_bytes: 1408
#h=int(input())
n,m=map(int,input().split())
xl=list(map(int,input().split()))
#l=[list(map(int,input().split())) for i in range(n)]

if n>=m:
    ans=0
else:
    xl.sort()
    bet=[]
    for i in range(1,m):
        bet.append(xl[i]-xl[i-1])
    bet.sort(reverse=True)
    ans=xl[m-1]-xl[0]-(sum(bet[0:n-1]))
print(ans)



Measured memory_bytes: 13968
import numpy as np
def acinput():
    return list(map(int, input().split(" ")))

N=int(input())

S=[]
a=[]
for i in range(N):
    tmp=acinput()
    S.append(tmp)


S=sorted(S,key=lambda x:x[1])
a=[]
b=[]
for ss in S:
    a.append(ss[0])
    b.append(ss[1])
acs=np.cumsum(a)

res="Yes"
for i in range(N):
    if acs[i]>b[i]:
        res="No"
        break

print(res)


Measured memory_bytes: 68532
#include"bits/stdc++.h"
#include<boost/multi_array.hpp>
#include<boost/optional.hpp>
#include<boost/range/irange.hpp>
#include<boost/range/algorithm.hpp>
#include<boost/range/adaptors.hpp>
#include<boost/operators.hpp>
#include<boost/dynamic_bitset.hpp>

namespace adaptor = boost::adaptors;
using index_t = std::size_t;
	
void Main()
{
	int N;
	std::int64_t K;
	std::cin >> N >> K;
	std::vector<std::int64_t> member(N);
	std::vector<std::int64_t> food(N);
	for (auto& m : member)
	{
		std::cin >> m;
	}
	for (auto& f : food)
	{
		std::cin >> f;
	}
	boost::sort(member);
	boost::sort(food, std::greater<>());
	std::int64_t min = -1;
	std::int64_t max = food.front() * member.back() + 1;
	while (max - min > 1)
	{
		auto mid = (min + max) / 2;
		std::int64_t count = 0;
		for (auto i : boost::irange(0, N))
		{
			count += std::max(std::int64_t(), member[i] - mid / food[i]);
		}
		if (count <= K)
		{
			max = mid;
		}
		else
		{
			min = mid;
		}
	}
	std::cout << max << std::endl;
}

int main()
{
	std::cin.tie(nullptr);
	std::ios_base::sync_with_stdio(false);
	std::cout << std::fixed << std::setprecision(15);
	Main();
}

Measured memory_bytes: 3456
use std::io;

fn gets() -> String {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).ok();
    buf
}

fn main() {
    let line = gets();
    let n = line.trim().parse::<i32>().unwrap();
    let x = n * 800;
    let y = n / 15 * 200;
    println!("{}", x - y);
}


Measured memory_bytes: 4352
// インクルード(GCC only)
#include <bits/stdc++.h>

// 長い型名
using namespace std;
typedef long long LL;

// 省略記法
#define INF 1e9
#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define rrep(i,n) for(int i##_len=(n), i=(i##_len-1); i>=0; ++i)
#define FOR(i,m,n) for(int i=(m), i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
#define sizei(x) ((int)(x).size())
#define fill(x,y) memset(x,y,sizeof(x))
#define printvector(x) rep(i,sizei(x)){cout << x[i] << endl;}
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; }

// mod付き四則演算(mod関数のオーバーヘッドが重いかも)
// TODO: 二項係数、離散対数、平方剰余の実装
#define MOD 1000000007
inline LL mod(LL const &a) { return (a % MOD + MOD) % MOD; }
inline LL madd(LL const &a, LL const &b) { return mod(mod(a) + mod(b)); }
inline LL msub(LL const &a, LL const &b) { return mod(mod(a) - mod(b)); }
inline LL mmul(LL const &a, LL const &b) { return mod(mod(a) * mod(b)); }
inline LL mpow(LL a, LL b) {
  LL r = 1;
  for (; b > 0; b >>= 1) {
    if (b & 1) (r *= a) %= MOD;
    (a *= a) %= MOD;
  }
  return r;
}
inline LL minv(LL const &a) { return mpow(a, MOD-2); }
inline LL mdiv(LL const &a, LL const &b) { return mod(mod(a) * minv(b)); }


// デバッグ用
#ifdef LOCAL
    #define eprint(...) fprintf(stderr, __VA_ARGS__)
    #define eprintvector(x) printvector(x)
#else
    #define eprint(...) 42
    #define eprintvector(x) 42
#endif

LL T = 0, A = 1, G = 2, C = 3;

bool NG(LL a, LL b, LL c)
{
  return (a == A && b == G && c == C);
}

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

  LL dp[N+1][4][4][4];
  fill(dp, 0);
  dp[0][0][0][0] = 1;
  rep(i, N) rep(a, 4) rep(b, 4) rep(c, 4) rep(d, 4) {
            if (NG(b, c, d) || NG(c, b, d) || NG(b, d, c)) continue;
            if (NG(a, c, d) || NG(a, b, d)) continue;

            dp[i+1][b][c][d] = madd(dp[i+1][b][c][d], dp[i][a][b][c]);
  }

  LL ans = 0;
  rep(a, 4) rep(b, 4) rep(c, 4) ans = madd(ans, dp[N][a][b][c]);
  cout << ans << endl;

  return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#define rep3(i, s, n, a) for (int i = (s); i < (int)(n); i += a)
#define rep2(i, s, n) rep3(i, s, n, 1)
#define rep(i, n) rep2(i, 0, n)

using namespace std;
using ll = long long;
using ull = unsigned long long;
using P = pair<int, int>;

void update(int i, int x);
int query(int x, int y, int k, int l, int r);

int n;
vector<int> GCD;

int main(){
    cin >> n;
    vector<int> a, num(1e6+1, 1), pri, P(1e6+1, 1);

    int cnt=0;
    
    rep(i, n){
        int x;
        cin >> x;
        if(x!=1){
          cnt++;
        }
        a.push_back(x);
    }
    num[0] = 0;
    num[1] = 0;

    rep2(i, 2, 1e6+1){
        if(num[i]){
            pri.push_back(i);
            rep3(j, i*2, 1e6+1, i){
                num[j] = 0;
            }
        }
    }

    bool flag = true;

    if(cnt<79000){
      rep(i, n) {
        int check = a[i];
        rep2(j, 2, sqrt(check)+1){
          if (check % j == 0) {
            if (P[j]) {
              P[j] = 0;
            } else {
              flag = false;
              break;
            }
            while (check % j == 0) {
              check /= j;
            }
          }
        }
        if(check!=1){
            if(P[check]){
                P[check] = 0;
            }else{
                flag = false;
            }
        }
        if (!flag) {
          break;
        }
      }
    }else{
        flag = false;
    }

    


    if(flag){
      cout << "pairwise coprime" << endl;
    }else{
      rep(i, 30) {
        if ((n - 1) < 1 << i) {
          n = 1 << i;
          break;
        }
      }

      rep(i, 2 * n - 1) { GCD.push_back(0); }

        int alen = a.size();
      rep(i, alen){
          update(i, a[i]);
      }

        if(query(0, n, 0, 0, n)==1){
          cout << "setwise coprime" << endl;
        }else{
            cout << "not coprime" << endl;
        }

    }
    return 0;
}

void update(int i, int x) {
  i += n - 1;
  GCD[i] = x;
  while (i > 0) {
    i = (i - 1) / 2;
    GCD[i] = gcd(GCD[i * 2 + 1], GCD[i * 2 + 2]);
  }
}

int query(int x, int y, int k, int l, int r) {
  if (r <= x || y <= l) return 0;
  if (x <= l && r <= y)
    return GCD[k];
  else {
    int vl = query(x, y, k * 2 + 1, l, (l + r) / 2);
    int vr = query(x, y, k * 2 + 2, (l + r) / 2, r);
    return gcd(vl, vr);
  }
}

Measured memory_bytes: 27496
import java.util.*;

public class Main {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] data = new int[n];

    for(int i = 0;i < n;i++) {
      data[i] = sc.nextInt();
    }

    Arrays.sort(data);

    int x = 0;

    for(int i = 0;i < n-2;i++) {
      for(int k = i + 1;k < n-1;k++) {
        int high = n;
        int low = 0;
        while(high - low > 1) {
          int middle = (high + low) / 2;
          if(data[middle] < data[i] + data[k]) {
            low = middle;
          } else {
            high = middle;
          }
        }
        x += high - k - 1;
      }
    }

    System.out.println(x);

  }

}


Measured memory_bytes: 26944
import sys
from math import factorial
from collections import Counter
from fractions import Fraction
import heapq, bisect, fractions
import math
import itertools
sys.setrecursionlimit(10 ** 5 + 10)
INF = 10**15 +5
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
MOD = 10**9 + 7

a, v = MAP()
b, w = MAP()
t = INT()
if abs(b-a)+t*w - t*v <= 0:
    print('YES')
else:
    print('NO')

Measured memory_bytes: 72588
#include<cstdio>
#include<vector>
#include<cstdlib>


using namespace std;
using vi=vector<int>;

int main(void)
{
	int n;

	while(scanf("%d", &n)==1)
	{
		vi a(n);

		int s=0;
		int ans=-1, ans_d=n*1000;

		for(int i=0;i<n;i++)
		{
			scanf("%d", &a[i]);
			s+=a[i];
		}
		for(int i=0;i<n;i++)
		{
			int d=abs(s-a[i]*n);
			if(d<ans_d)
			{
				ans_d=d;
				ans=i;
			}
		}
		printf("%d\n", ans);
	}

	return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#pragma GCC optimize("unroll-loops,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
using namespace __gnu_pbds;
using namespace std;
/*
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
*/
#define ull unsigned long long int
#define ll long long int
#define MAX 1000000007
//1e9+7
#define pll pair<ll,ll>
#define pii pair<int,int>
#define IO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define FO ifstream fin("a.in");ofstream fout("a.out");
#define TEST int testcase;cin>>testcase;while(testcase--)
#define all(x) (x).begin(),(x).end()
#define mset0(x) memset((x), 0, sizeof((x)));
#define mset1(x) memset((x), -1, sizeof((x)));
#define endl "\n"
#define plll pair<ll,pll>
typedef tree<ll,null_type,less<ll>,rb_tree_tag, tree_order_statistics_node_update> indexed_set;
FO


void solve(){
    string s,t;
    cin>>s>>t;
    int cnt=0;
    int n=s.size();
    for(int i=0;i<n;i++) if(s[i]!=t[i]) cnt++;
    cout<<cnt;
    return;
}
int main(){
    //IO FO

    //TEST
    solve();

    return(0);
}



Measured memory_bytes: 3904
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>

using namespace std;

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

    vector <int> A;
    map <int, long long> m;
    for (int i = 0; i < N; i++){
        long long a, b;
        cin >> a >> b;

        if (m[a] == 0){
            A.push_back(a);
        }
        m[a] += b;
    }
    
    sort(A.begin(), A.end());

    int ans;
    for (int i = 0; i < A.size(); i++){
        K -= m[A[i]];
        if (K <= 0){
            ans = A[i];
            break;
        }
    }
    
    cout << ans << endl;

    return 0;
}

Measured memory_bytes: 4476
module UnionFind = struct

  type t = { mutable parent : int; mutable rank : int }

  let make n = Array.init n (fun i -> { parent = i; rank = 0 })

  let find s x =
    let rec doit x =
      let p = s.(x).parent in
      if x = p then x
      else begin
        s.(x).parent <- doit p;
        s.(x).parent
      end in
    doit x

  let unite s x y =
    let px = find s x in
    let py = find s y in
    if s.(px).rank > s.(py).rank then s.(py).parent <- px
    else begin
      s.(px).parent <- py;
      if s.(px).rank = s.(py).rank then s.(py).rank <- s.(py).rank + 1
    end

  let same_p s x y = find s x = find s y

end

module U = UnionFind

let split_on_char sep s =
  let open String in
  let r = ref [] in
  let j = ref (length s) in
  for i = length s - 1 downto 0 do
    if get s i = sep then begin
      r := sub s (i + 1) (!j - i - 1) :: !r;
      j := i
    end
  done;
  sub s 0 !j :: !r

let readln () = read_line () |> split_on_char ' ' |> List.map int_of_string

let solve n q =
  let s = U.make n in
  for i = 0 to q - 1 do
    match readln () with
    | n :: x :: y :: _ ->
      if n = 0 then U.unite s x y
      else print_endline (if U.same_p s x y then "1" else "0")
    | _ -> assert false
  done

let () =
  match readln () with
  | [n; q] -> solve n q
  | _ -> assert false

Measured memory_bytes: 4656
import java.util.Scanner

object Main extends App{

  val sc = new Scanner(System.in)

  val n = sc.nextInt
  val hs = Seq.fill(n)(sc.nextInt)

  val res = hs.tail.foldLeft((0, 0, hs.head)){ case ((max, cons, pre), h) =>
    val newCons = if (pre >= h) cons + 1 else 0
    (Math.max(max, newCons), newCons, h)
  }._1

  println(res)
}

Measured memory_bytes: 66996
#include <bits/stdc++.h>
using namespace std;
int main(void){
    int num=0;
    string n;
    cin>>n;
    vector<int>a(n.size());
    for(int i=0;i<n.size();i++){
        a[i]=(n[i]-'0');
    }
    for(int i=0;i<n.size();i++){
        num+=a[i];
    }
    if(num%9==0){
        cout<<"Yes"<<endl;
    }
    else{
        cout<<"No"<<endl;
    }
}

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

int main()
{
    ios_base::sync_with_stdio(false); cin.tie(0);
    int n, k; cin >> n >> k;
    cout << ((n%2==0?n/2:n/2+1)>=k?"YES":"NO") << '\n';

}



Measured memory_bytes: 256
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return list(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])

def main():
    s = input()
    if s == 'AAA' or s == 'BBB':
        print('No')
    else:
        print('Yes')
    
if __name__ == "__main__":
    main()

Measured memory_bytes: 39148
b = input()

if b == "A" :
	answer = "T"

if b == "C" :
	answer = "G"

if b == "G" :
	answer = "C"

if b == "T" :
	answer = "A"

print(answer)


#等しいというときは　==
#b == A だと　A は　箱だと思われてしまうので　b == "A" と書くこと！！！！

Measured memory_bytes: 2940
// inputに入力データ全体が入る
function Main(input) {
	var line = input.split("\n");
	var N = Number(line[0]);
	var tmp = line[1].split(" ");
	var days = Number(tmp[0]);
	var rest = Number(tmp[1]);
	var A = [];
	for(var i = 2; i < N+2; i++){
		A[i-2] = Number(line[i]);
	}

	var ans = rest;

	for(var j = 0; j < A.length; j++){
		ans += 1 + Math.floor((days-1)/A[j]);
	}

	console.log(ans);

}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Measured memory_bytes: 11468
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.next());
        int x = Integer.parseInt(sc.next());
        int[] m = new int[n];
        int min = 1001;
        for(int i=0; i<n; i++) {
            m[i] = Integer.parseInt(sc.next());
            x -= m[i];
            if(min > m[i]) min = m[i];
        }
        System.out.println(n + x/min);
    }
}

Measured memory_bytes: 21972
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <set>
#include <queue>
#include <stack>
#include <tuple>
#include <cmath>
#include <iomanip>
#include <map>
#include <cstring> //memset(dp,0,sizeof(dp))
#include <functional>
#include <cctype>
#include <locale>
#define ll long long
#define rep(i,n) for(int i=0;i<(n);i++)
#define rrep(i,n) for(int i=n-1;i>=0;i--)
#define fi first
#define se second
#define pb push_back
#define ALL(a) (a).begin(),(a).end()
using namespace std;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
typedef pair<int,int> P;
typedef pair<long long,long long> Pll;
#define fout(num) cout << fixed << setprecision(20) << (num) << endl
//s[i]=tolower(s[i]); islower(s[i]); cout << tolower(s[i])はバグ
//vector<vector<ll>> dp(n,vector<ll>(n))
//exist x map o set

signed main(){
    ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n; cin >> n;
    vector<ll> a(n);
    rep(i,n)  cin >> a[i];
    sort(ALL(a));
    ll m1=0,m2=0;
    for(int i=n-1;i>0;i--){
        if(a[i]==a[i-1]){
            chmax(m2,a[i]);
            i--;
        }
        if(m1<m2) swap(m1,m2);
    }
    cout << m1*m2 << endl;
}


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

#define pb push_back
#define ff first
#define ss second

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

const int MAXN = 100 * 1000 + 17;

int n, m, mark[MAXN], unmark[MAXN], ans;

int main() {
	ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> n >> m;
	for (int i = 2; i <= n; i++)
		unmark[i]++;
	mark[1]++;
	while (m--) {
		int x, y;
		cin >> x >> y;
		if (mark[x]) {
			mark[x]--;
			if (unmark[y])
				mark[y] += unmark[y], unmark[y] = 0;
			mark[y]++;
		}
		else {
			unmark[x]--;
			if (mark[y])
				mark[y]++;
			else
				unmark[y]++;
		}
	}
	for (int i = 1; i <= n; i++)
		if (mark[i] > 0) ans++;
	cout << ans << endl;
	return 0;
}


Measured memory_bytes: 1024
#include<stdio.h>

static const int N = 1000;

void trace(int A[], int n){
  int i;
  for ( i = 1; i <= n; i++ ){
    if ( i > 1 ) printf(" ");
    printf("%d", A[i]);
  }
  printf("\n");
}

int main(){
  int n, i, j;
  int A[N+1];
  scanf("%d", &n);

  for ( i = 1; i <= n; i++ ) scanf("%d", &A[i]);
  
  trace(A, n);
  int key;
  
   for(i=2;i<n+1;i++){
    key=A[i];
    j=i-1;
    while(j>=0 && A[j]>key){
      A[j+1]=A[j];
      j--;
      A[j+1] = key;
    }
    trace(A,n);
   }
   

  return 0;
}

Measured memory_bytes: 608
n, k = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)

aa = a.group_by(&:itself).map{ |key, value| value.count }
aa.sort!.reverse!

aa.shift(k)
if aa.empty?
  p 0
else
  p aa.inject(:+)
end


Measured memory_bytes: 47216
H,W = list(map(int,input().split()))

e_list = [[] for i in range(10)]
for i in range(10):
    c = list(map(int,input().split()))
    for j in range(10):
        if i!=j:
            e_list[i].append([j,c[j]])

A = [list(map(int,input().split())) for i in range(H)]

#dijkstra
#you need to prepare e_list = [[orient,dist]]

import heapq

d_list = []
N=10
for i in range(10):
    vi = i
    min_d_list = [10**27 for i in range(N)]
    min_d_list[vi] = 0
    prev_list = [-1 for i in range(N)]
    q = []
    for i in range(N):
        heapq.heappush(q,[min_d_list[i],i])

    while len(q)>0:
        d,v = heapq.heappop(q)
        for e in e_list[v]:
            v1,d1=e
            if min_d_list[v1]>d+d1:
                min_d_list[v1]=d+d1
                prev_list[v1]=v
                heapq.heappush(q,[d+d1,v1])
    d_list.append(min_d_list)
score=0
for i in range(H):
    for j in range(W):
        if A[i][j]!=-1:
            score+=d_list[A[i][j]][1]

print(score)

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

template<typename H> void read(H& head) { cin >> head; }
template<typename H, typename ...T> void read(H& head, T& ...tail) { cin >> head; read(tail...); }
template<typename H> void write(H head) { cout << head << '\n'; }
template<typename H, typename ...T> void write(H head, T ...tail) { cout << head << " "; write(tail...); }
template<typename ...T> void die(T ...tok) { write(tok...); exit(0); }
#endif
#ifndef _TEMPLATE_OPT
#define _TEMPLATE_OPT
#pragma GCC optimize("Ofast")
#pragma GCC target("avx2")
#endif
using namespace std;

int a[500005];

struct Query {
  int l, r, id, ans;
};

// freqcnt
int freq[500005];
int distinct = 0;
void freqadd(int x) { 
//write("FA", x, freq[x], "->", freq[x]+1);
  if (!freq[x]) distinct++; freq[x]++; }
void freqrem(int x) { 
  
//write("FR", x, freq[x], "->", freq[x]-1);
  freq[x]--; if (!freq[x]) distinct--; }
Query query[500005];

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

  int n, q; read(n, q);
  rep(i, 1, n + 1) read(a[i]);
  rep(i, 0, q) read(query[i].l, query[i].r), query[i].id = i;
  
  const int BS = 1500;
  sort(query, query + q, [](const Query& a, const Query& b) {
    if (a.l / BS != b.l / BS) return a.l / BS < b.l / BS;
    else return (a.l / BS % 2 ? a.r < b.r : a.r > b.r);
    });

  // inclusive [cl, cr]
  int cl = 1, cr = 0;
  rep(i, 0, q) {
    int nl = query[i].l, nr = query[i].r;
    while (cl > nl) freqadd(a[--cl]);
    while (cr < nr) freqadd(a[++cr]);
    while (cl < nl) freqrem(a[cl++]);
    while (cr > nr) freqrem(a[cr--]);
    query[i].ans = distinct;
  }

  sort(query, query + q, [](const Query& a, const Query& b) { return a.id < b.id; });
  rep(i, 0, q) write(query[i].ans);
}



Measured memory_bytes: 15428
#include "bits/stdc++.h"
using namespace std;
#define long int64_t

struct Solver {
	Solver() {
		ios::sync_with_stdio( false );
		cout << fixed << setprecision( 10 );
	}

	void solve() {
		long N, K;
		cin >> N >> K;
		cout << min( N%K, K - N%K ) << endl;
	}
};

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


Measured memory_bytes: 256
#include <bits/stdc++.h>
#define rep(i, ns, ne) for (int i = ns; i < ne; ++i)
using namespace std;
using ULL = unsigned long long;

int main() {
  ULL N, a, b, ans = 0;
  cin >> N >> a >> b;
  vector<ULL> v(N);
  rep(i, 0, N) { cin >> v.at(i); }
  rep(i, 0, N - 1) { ans += min(a * (v[i + 1] - v[i]), b); }
  cout << ans << endl;
  getchar();
}

Measured memory_bytes: 4032
from collections import defaultdict

N = int(input())
A = []
B = []

d = defaultdict(int)

for i in range(N):
	a, b = map(int, input().split())
	A.append(a)
	B.append(b)
	d[a] = b

ans = max(A)

ans += d[max(A)]

print(ans)

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

int main()
{
    string s;
    cin >> s;

    if (s == "SUN")
    {
        cout << 7 << endl;
    }
    else if (s == "MON")
    {
        cout << 6 << endl;
    }
    else if (s == "TUE")
    {
        cout << 5 << endl;
    }
    else if (s == "WED")
    {
        cout << 4 << endl;
    }
    else if (s == "THU")
    {
        cout << 3 << endl;
    }
    else if (s == "FRI")
    {
        cout << 2 << endl;
    }
    else if (s == "SAT")
    {
        cout << 1 << endl;
    }
}

Measured memory_bytes: 256
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using static MyIO;


public class A
{
	public static void Main() => (new Solver()).Solve();
}


public class Solver
{
	public void Solve()
	{
		int N = GetInt();
		int A = GetInt();
		int B = GetInt();
		int[] t = GetInts(N);

		Console.WriteLine(t.Count(x => (x < A) || (x >= B)));
	}
}


public static class MyIO
{
	private static string[] args = null;
	private static int num = -1;
	private static int used = -1;

	private static string getArg()
	{
		if(used == num)
		{
			args = Console.ReadLine().Split(' ');
			num = args.Length;
			used = 0;
		}
		return args[used++];
	}

	public static int GetInt() => int.Parse(getArg());
	public static long GetLong() => long.Parse(getArg());
	public static double GetDouble() => double.Parse(getArg());
	public static string GetString() => getArg();
	public static char GetChar() => getArg()[0];
	public static int[] GetInts(int N) => Enumerable.Range(0, N).Select(_ => GetInt()).ToArray();
	public static long[] GetLongs(int N) => Enumerable.Range(0, N).Select(_ => GetLong()).ToArray();
	public static double[] GetDoubles(int N) => Enumerable.Range(0, N).Select(_ => GetDouble()).ToArray();
	public static string[] GetStrings(int N) => Enumerable.Range(0, N).Select(_ => GetString()).ToArray();
}


Measured memory_bytes: 13396
k, n = map(int, input().split())
array = list(map(int,input().split()))
max_length = 0
sum_length = 0
for i in range(n - 1):
  length = array[i + 1] - array[i]
  sum_length += length
  if length > max_length:
    max_length = length
last_length = k - array[n - 1] + array[0]
sum_length += last_length
max_length = max(max_length, last_length)
print(sum_length - max_length)

Measured memory_bytes: 26444
while True:
    n = int(input())
    if n == 0:
        break
    a = [int(x) for x in input().split()]
    cnt = 0
    while True:
        b = {}
        for i in a:
            if i in b:
                b[i] += 1
            else:
                b[i] = 1
        c = 0
        for k, v in b.items():
            if k == v:
                c += 1
        if len(b) == c:
            break
        else:
            for i in range(n):
                a[i] = b[a[i]]
            cnt += 1
    print(cnt)
    print(*a)

Measured memory_bytes: 7692
import sys
s = str(input())

n = len(s)

odd = ["R", "U", "D"]
even = ["L", "U", "D"]

for i in range(n):
    if not ((i % 2 == 0 and s[i] in odd) or (i % 2 == 1 and s[i] in even)):
        print("No")
        sys.exit()

print("Yes")


Measured memory_bytes: 38256
#include<bits/stdc++.h>
using namespace std;
int N,L;
map<string,int> S;
vector<string> ans;

int main(){
  cin>>N>>L;
  for(int i=0;i<N;i++){
    string str;
    cin>>str;
    string tmp=str;
    reverse(tmp.begin(),tmp.end());
    if( S[tmp]>0 ){
      S[tmp]--;
      ans.push_back( min(tmp,str) );
    }else{
      S[str]++;
    }
  }

  string X="";
  map<string,int> :: iterator it;
  for(it=S.begin();it!=S.end();it++){
    if(it->second==0)continue;
    string str=it->first;
    string tmp=str;
    reverse(str.begin(),str.end());
    if(str==tmp && ( X=="" || X>str) ){
      X=str;
    }
  }
  sort(ans.begin(),ans.end());
  for(int i=0;i<ans.size();i++)cout<<ans[i];
  cout<<X;
  reverse(ans.begin(),ans.end());
  for(int i=0;i<ans.size();i++){
    reverse(ans[i].begin(),ans[i].end());
    cout<<ans[i];
  }
  cout<<endl;
  return 0;
}

Measured memory_bytes: 3444
n,k = map(int,input().split())
p_l = list(map(int,input().split()))

possibility=list(map(lambda x:(1+x)/2,p_l))


max_p=sum(possibility[0:k:1])
tmp=max_p
for i in range(1,len(possibility)-k+1):
    tmp+=possibility[i+k-1]-possibility[i-1]
    if tmp>max_p:
        max_p=tmp
        
print(max_p)

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


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

  int h,w;
  cin >> h >> w;

  int a,b;
  cin >> a >> b;

  rep(i,h){
    rep(j,w){
      bool left,up;
      if(j<a) left = true;
      else left = false;

      if(i<b) up = true;
      else up = false;
      cout << (left^up);
    }
    cout << endl;
  }
  
  return 0;
    

}


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

int main(void)
{
    int N, K;
    cin >> N;
    cin >> K;

    if(N % 2 ==0)
    {
        if(K <= (int)(N / 2))
            cout << "YES" << endl;
        else
            cout << "NO" << endl;
    }
    else
    {
        if(K <= (int)(N / 2) + 1)
            cout << "YES" << endl;
        else
            cout << "NO" << endl;
    }
    
    return 0;
}

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

bool pallan(string &S)
{
    string temp = S;
    
    reverse(temp.begin(),temp.end());
    if(temp==S) return true;
    return false;
    
    
}

void solve()
{   
    
    double a=0;
	cin>>a;
	double ans=a*a*a/27;
	printf("%.10lf",ans);
   	return ;
    
}

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

Measured memory_bytes: 256
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <climits>

#define rep(i, m, n) for(int i=int(m);i<int(n);i++)
#define all(c) begin(c),end(c)

template<typename T1, typename T2>
inline void chmin(T1 &a, T2 b) { if (a > b) a = b; }

template<typename T1, typename T2>
inline void chmax(T1 &a, T2 b) { if (a < b) a = b; }

//改造
typedef long long int ll;
using namespace std;
#define INF (1 << 30) - 1
#define INFl (ll)5e15
#define DEBUG 0 //デバッグする時1にしてね
#define dump(x)  cerr << #x << " = " << (x) << endl
#define MOD 1000000007


//ここから編集する


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


    int N, M, X, Y;
    cin >> N >> M >> X >> Y;

    vector<int> x, y;
    rep(i, 0, N) {
        int tmp;
        cin >> tmp;
        x.push_back(tmp);
    }
    x.push_back(X);
    sort(all(x));
    rep(i, 0, M) {
        int tmp;
        cin >> tmp;
        y.push_back(tmp);
    }
    y.push_back(Y);
    sort(all(y));

    if (x.back() < y.front()) {
//    if (y.front() - x.back() > 0) {
        cout << "No War" << endl;
    } else {
        cout << "War" << endl;
    }


    return 0;
}


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

int main(){
  int n; cin>>n;
  vector<pair<int,int>> ba(n);
  for(int i=0; i<n; ++i){
    int a,b; cin>>a>>b;
    ba[i]=make_pair(b,a);
  }

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

  long long time=0LL; bool flg=true;
  for(int i=0; i<n; ++i){
    time+=ba[i].second;
    if(time>ba[i].first){flg=false; break;}
  }
  

  if(flg)cout<<"Yes"<<endl;
  else cout<<"No"<<endl;
  
}


Measured memory_bytes: 1792
#include <bits/stdc++.h>
#define rep(i,cc,n) for(int i=cc;i<=n;++i)
#define drep(i,cc,n) for(int i=cc;i>=n;--i)
#define sz(s) (int)(s.size())
#define mod 1000000007

using namespace std;
class CompareFirst
{
public:
  bool operator()(pair<int,int> n1,pair<int,int> n2) {
    return n1.first>n2.first; //>:desc <:asc
  }
};


int main(){

  string s;
  int i,j,k,l,n,m;
  vector<string> vs;
  vector<int> vi;
  pair<int,int> pr;
  //unordered_map<string,int> mp;
  //priority_queue<int> pq; // default ‘å‚«‚¢‡
  //priority_queue<pair<int,int>,vector<pair<int,int>>,CompareFirst> pq;

  cin >> n;

  cout << n*n*n << endl;
//  printf("%.10f\n",ans);

  return 0;

}


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

#define REP(i,s,n) for(int i=s;i<n;++i)
#define rep(i,n) REP(i,0,n)
#define fst first
#define snd second
#define pb push_back
#define ALL(x) x.begin(),x.end()
#define EPS (1e-9)
#define equals(a,b) (fabs((a)-(b))<EPS)

using namespace std;

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

const string YES = "";
const string NO  = "";

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

#define MAX 1010
int X,N,p[MAX];

void solve() {

}

int main() {
  cin >> X >> N;
  rep(i,N) cin >> p[i];
  set<int> S;
  rep(i,N) S.insert(p[i]);
  int ans = INT_MAX, v = INT_MAX;
  REP(i,-1000,1000) {
    if( S.count(i) ) continue;
    if( ans > (int)abs(X-i) ) {
      ans = min(ans,(int)abs(X-i));
      v = i;
    }
  }
  cout << v << endl;
  return 0;
}


Measured memory_bytes: 3648
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cmath>
#include <queue>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
const int INF = 1<<29;

int main() {
  int n;
  long long m;
  while(cin>>n>>m,n||m) {
    int d[n], p[n];
    vector<pair<int,int> > v;
    REP(i,n) {
      cin >> d[i] >> p[i];
      v.push_back(make_pair(p[i], i));
    }
    sort(ALL(v), greater<pair<int,int> >());
    long long res = 0;
    REP(i,n){
      int c = d[v[i].second];
      if (m>=c)
        m-=c;
      else {
        res += v[i].first*(c-m);
        m = 0;
      }
    }
    cout << res << endl;
  }
}

Measured memory_bytes: 1192
import sys
sys.setrecursionlimit(4100000)

import math

import logging

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)

import numpy as np


def resolve():
    # S = [x for x in sys.stdin.readline().split()][0]  # 文字列 一つ
    N = [int(x) for x in sys.stdin.readline().split()][0]  # int 一つ
    # N, D = [int(x) for x in sys.stdin.readline().split()]  # 複数int
    a_list = [int(x) for x in sys.stdin.readline().split()]  # 複数int

    # grid = [list(sys.stdin.readline().split()[0]) for _ in range(N)]  # 文字列grid
    # v_list = [int(sys.stdin.readline().split()[0]) for _ in range(N)]
    # grid = [[int(x) for x in sys.stdin.readline().split()]
    #         for _ in range(N)]  # int grid

    logger.debug('{}'.format([]))

    MAX = 10**6
    count_list = np.array([0 for _ in range(MAX + 1)])
    for a in a_list:
        count_list[a] += 1

    for i in range(1, MAX + 1):
        if count_list[i]:
            count_list[i * 2::i] = 0
            if count_list[i] >= 2:
                count_list[i] = 0

    print(count_list.sum())


if __name__ == "__main__":
    resolve()

# AtCoder Unit Test で自動生成できる, 最後のunittest.main は消す
# python -m unittest template/template.py で実行できる
# pypy3 -m unittest template/template.py で実行できる

import sys
from io import StringIO
import unittest


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """5
24 11 8 3 16"""
        output = """3"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """4
5 5 5 5"""
        output = """0"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """10
33 18 45 28 8 19 89 86 2 4"""
        output = """5"""
        self.assertIO(input, output)

    def test_入力例_4(self):
        input = """2
1000000 1000000"""
        output = """0"""
        self.assertIO(input, output)


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

#define rep(l, r) for (int i = (l); i < (r); i++)

typedef long long ll;
 
using namespace std;

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

    cout << ((a * 3 + p) / 2) << endl;

    return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int (i) = 0; (i) < (n); ++(i))
#define rrep(i,n) for(int (i) = (n) - 1; (i) >= 0; --(i)) //Reversi rep
#define nfor(i,a,b) for(int (i) = (a); (i) < (b); ++(i)) //Natural for
#define rfor(i,a,b) for(int (i) = (b); (i) >= (a); --(i)) //Reversi for

int main()
{
    int X;
    cin >> X;
    if (X < 1200) {
        cout << "ABC" << endl;
    }else{
        cout << "ARC" << endl;
    }
    return 0;
}

Measured memory_bytes: 256
S = input()
K = int(input())

if S==S[0]*len(S):
    print(len(S)*K//2)
    exit()
    
rle = []
cnt = 1

for i in range(len(S)-1):
    if S[i]!=S[i+1]:
        rle.append((S[i], cnt))
        cnt = 1
    else:
        cnt += 1

rle.append((S[-1], cnt))
#print(rle)

if rle[0][0]==rle[-1][0]:
    ans = rle[0][1]//2+rle[-1][1]//2
    
    for i in range(1, len(rle)-1):
        ans += rle[i][1]//2*K
    
    ans += (rle[0][1]+rle[-1][1])//2*(K-1)
else:
    ans = 0
    
    for i in range(len(rle)):
        ans += rle[i][1]//2*K
    
print(ans)

Measured memory_bytes: 62060
#include <stdio.h>

int linerSearch(int);

int s[10000],t[500];
int counter=0,n,q;

int main(){
  int i,j;

  
  scanf("%d",&n);
  for(i=0;i<n;i++){
    scanf("%d",&s[i]);
  }
  scanf("%d",&q);
  for(i=0;i<q;i++){
    scanf("%d",&t[i]);
    if(linerSearch(t[i])==1)counter++;
  }
  printf("%d\n",counter);  
  
  return 0;
}
int linerSearch(int key){
  int i=0;
  while(s[i]!=key){
    i++;
    if(i==n)return 0;
  }
  return 1;
}

Measured memory_bytes: 640
#include <bits/stdc++.h>
#define int long long
#define double long double
#define yy cout<<"YES\n"
#define nn cout<<"NO\n"
#define rt return
#define ct continue
#define br break
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define mmod 1000000007
#define pmod 998244353
using namespace std;
int gcd(int a,int b){
    while (b) b^=a^=b^=a%=b;
    return a;
}
int lcm(int a,int b){
    return a*b/gcd(a,b);
}
int bigmod(int b,int p,int m){
    int ans=1;
    b%=m;
    if (!b) return 0;
    while (p){
        if (p&1) ans=(ans*b)%m;
        p>>=1;
        b=(b*b)%m;
    }
    return ans;
}
void recur(){
	
	
	
}
int ss[200005];
int ans[200005];
vector <pair <int,int> > v[200005];
void solve(){
	int n,k;
	cin>>n>>k;
	for (int i=1; i<=k; i++){
		int x,y;
		cin>>x>>y;
		for (int j=1; j<=n; j++){
			if (j+x>n) break;
			v[j].push_back({x,min(y,n-j)}); 
		}
	}
	ans[n]=1;
	ss[n]=1;
	for (int i=n-1; i>0; i--){
		for (auto&j:v[i]){
			ans[i]+=ss[i+j.first]-ss[i+j.second+1];
			ans[i]%=pmod;
		}
		ss[i]=ss[i+1]+ans[i];
	}
	cout<<ans[1];
	
	
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t=1;
    //cin>>t;
    while (t--) solve();
}

Measured memory_bytes: 34344
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<bitset>
#include<cctype>
#include<climits>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<deque>
#include<list>
#include<map>
#include<set>
#include<stack>
#include<string>
#include<sstream>
#include<queue>
#include<vector>
using namespace std;

typedef unsigned long long ull;

//return 1??????a?????§???????????°
ull len(ull a) {
	//cout << "len " << a << endl;
	//ret = Fizz Buzz??????????????°
	ull ret = (a / 3 + a / 5) * 4;

	// [ 10^n -1 , 10^(n+1) -1 ) n=1,2,...,18
	// [0,9),[9,99),... ??¨???????????????????????°????¨????
	int l = 0; //?????°
	for (ull pow = 1; a >= pow; pow *= 10) {
		l++;
		ull L = pow - 1;
		ull R = min(a, pow * 10 - 2);
		//cout << " pow " << pow << " L " << L << " R " << R << endl;

		//ret += Fizz Buzz?????????????????????????????°
		ret += ((R - R / 3 - R / 5 + R / 15) - (L - L / 3 - L / 5 + L / 15))*l;
	}
	//cout << " return " << ret << endl;
	return ret;
}

int main() {
	ull s; cin >> s;

	//????????¢?´¢
	//???????????¶ L+1 == R == t????§????????????°
	ull L = 0,
		R = 100000000000000000;
	while (L + 1 < R) {
		//cout << "L " << L << " R " << R << endl;
		ull M = (L + R) / 2;
		if (len(M) >= s)R = M;
		else L = M;
	}

	//L: R-1
	//R: t????§????????????°
	//cout << "L " << L << " R " << R << endl;

	string t = "";
	for (int i = 1; i < 20; i++) {
		if ((L + i) % 15 == 0)t += "FizzBuzz";
		else if ((L + i) % 3 == 0)t += "Fizz";
		else if ((L + i) % 5 == 0)t += "Buzz";
		else t += to_string(L + i);
	}
	//????????°-(t????§????????????°-1)?????§???????????°-1
	//s=4; 4-len(2)-1 == (Fizz???F)
	int beg = s - len(L) - 1;
	cout << t.substr(beg, 20) << endl;

	return 0;
}

Measured memory_bytes: 3284
#include<bits/stdc++.h>
 
using namespace std;
 
typedef long long int ll;
#define pb push_back
#define mp make_pair


ll fac[100002]; 
ll power(ll x, ll y, ll p) 
{ 
    ll res = 1;      // Initialize result 
    x = x % p; 
    while (y > 0) 
    { 
        if (y & 1) 
            res = (res*x) % p; 
  
        y = y>>1; // y = y/2 
        x = (x*x) % p; 
    } 
    return res; 
} 
  
ll modInverse(ll n, ll p) 
{ 
    return power(n, p-2, p); 
} 
  
ll nCrModPFermat(ll n, ll r, ll p) 
{ 
   if (r==0) 
      return 1; 
    return (fac[n]* modInverse(fac[r], p) % p * 
            modInverse(fac[n-r], p) % p) % p; 
}
int  main()
{

	ll i,m=1e9+7,a[100002];
    fac[0] = 1; 
    for (ll i=1 ; i<=100001; i++) 
        fac[i] = fac[i-1]*i%m; 
	ll n,k;
	scanf("%lld%lld",&n,&k);	
	for(i=0;i<n;i++)
		scanf("%lld",&a[i]);
	sort(a,a+n);
	ll minsum=0;
	ll maxsum=0;
	for(i=0;i<=n-k;i++){
		minsum+= nCrModPFermat(n-i-1,k-1,m)*a[i];
		minsum%=m;
	}
	for(i=k-1;i<n;i++){
		maxsum+= nCrModPFermat(i,k-1,m)*a[i];
		maxsum%=m;
	}
	ll ans=maxsum-minsum;
	if(ans<0)
		ans+=m;
	ans%=m;
	printf("%lld\n",ans );
	return 0;
}


Measured memory_bytes: 1792
// =====================================================================
// macros
// =====================================================================

/// stdin macro from https://techracho.bpsinc.jp/jhonda/2019_08_05/78537
macro_rules! stdin {
    () => {{
        use std::io::Read;
        let mut s = String::new();
        std::io::stdin().read_to_string(&mut s).unwrap();
        s
    }};
}

/// input macro from https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

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

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

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

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

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

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

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

/// test macro from https://techracho.bpsinc.jp/jhonda/2019_08_05/78537
macro_rules! test {
    ($($input:expr => $output:expr),* $(,)*) => {
        #[test]
        fn answer_test() {
            $(
                assert_eq!(answer($input), $output);
            )*
        }
    };
}
// =====================================================================
// test cases
// =====================================================================

test!{
    /// write inputs for test cases here.
    /// e.g.) 
    /// ```
    /// "1 2 3"=>"4",
    /// r"4 5 6
    ///   7 8 9"=>"10",
    /// ```
    r"oder atc"=>"atcoder",
}

// =====================================================================
// functions
// =====================================================================

/// answer fn for the problem
fn answer(input: &str)->String{
    input!{
        source = input,
        s: String,
        t: String,
    }
    let result = t + &s;
    return result;
}

/// the entry point
fn main() {
    println!("{}",answer(&stdin!()));
}


Measured memory_bytes: 4352
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef vector<int> V;
const long long MOD=1000000007LL;
const long long INFL=1LL << 60;
const int INF=1<<29;

const int MAX = 210000;

long long fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit() {
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}

// 二項係数計算
long long COM(int n, int k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}


int main(){
    COMinit();
    int N,M,K;
    cin >>N>>M>>K;
    ll ans=0; 
    for(ll i=1;i<N;i++){
        ans+=i*M%MOD*M%MOD*(N-i)%MOD;
        ans%=MOD;
    }
    for(ll j=1;j<M;j++){
        ans+=j*N%MOD*N%MOD*(M-j)%MOD;
        ans%=MOD;
    }
    ans=ans*COM(N*M-2,K-2)%MOD;
    cout<<ans<<endl;



    
    return 0;
}

Measured memory_bytes: 5120
import sys
input=sys.stdin.readline
import math

N,K=(int(x) for x in input().rstrip('\n').split())
R,S,P=(int(x) for x in input().rstrip('\n').split())
T = list(input().rstrip('\n'))
s_d = {'r':P,'s':R,'p':S}
score = 0
for i in range(K):
  now=i
  now_h=''
  while now<N:
    next= T[now]
    if next!=now_h:
      score += s_d[next]
      now_h=next
    else:
      now_h=''
    now += K
print(score)

Measured memory_bytes: 9880