akhauriyash/Code-Regression huggingface dataset:
#include <bits/stdc++.h>
using namespace std;

#define len(x)  (int((x).size()))
#define append push_back
#define pp make_pair
#define ff(a, b)    for (int a = 0; a < int(b); ++a)
#define kk(n)    ff(k, n)
#define xx(n)    ff(x, n)
#define yy(n)    ff(y, n)
#define ii(n)    ff(i, n)
#define fff(a, b, c) for (int a = int(b); a < int(c); ++a)
#define kkk(a, b) fff(k, a, b)
#define xxx(a, b) fff(x, a, b)
#define yyy(a, b) fff(y, a, b)
#define iii(a, b) fff(i, a, b)
#define bb begin()
#define ee end()
#define uu first
#define vv second
#define all(x)  (x).bb, (x).ee
#define ite(v)   decltype((v).bb)
#define fe(i, v) for(ite(v) i = (v).bb; i != (v).ee; ++i)
#define err(...)    { fprintf(stderr, __VA_ARGS__); fflush(stderr); }
#define zz(array, byte)   memset(array, byte, sizeof(array));

using LL = long long;
using DD = long double;
using pii = pair<int, int>;



const LL  INFLL  = 0x7f7f7f7f7f7f7f7fLL;
const int INFint = 0x7f7f7f7f;  //Works with memset(..).
 
     




int main() {
    ios_base::sync_with_stdio(false);     cin.tie(NULL);
    //cout << '\n';
    cout.precision(16);
    
    string line;
    cin >> line;
    int c = 0;
    int rr = 0;
    ii (len(line)) {
        if (line[i] == 'S')
            ++c;
        else
            --c;
        rr = max(rr, -c);
    }

    cout << (2*rr) << '\n';
    

    return 0;
}



Measured memory_bytes: 720
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    a, b, k = mi()
    cnt = 0
    for i in range(min(a, b), 0, -1):
        if a % i == 0 and b % i == 0:
            cnt += 1
        if cnt == k:
            print(i)
            break

if __name__ == "__main__":
    main()


Measured memory_bytes: 5040
#include <iostream>
#include <climits>

#define ll long long

using namespace std;

ll int frog (ll int n, ll int k, ll int *arr) {
	ll int c[n];

	c[0] = 0;
	c[1] = abs( arr[0] - arr[1] );

	for (ll int i=2; i<n; i++) {
		ll int sol = LLONG_MAX;
		for (ll int j=1; j<=k; j++) {
			if (i-j < 0)
				break;

			ll int h = c[i-j] + abs( arr[i] - arr[i-j]);
			if (h < sol)
				sol = h;
		}
		c[i] = sol;
	}
	return c[n-1];

}

int main() {
	ll int n, k, *arr;
	cin >> n >> k;
	arr = new ll int[n];

	for (int i=0; i<n; i++)
		cin >> arr[i];

	cout << frog(n, k, arr) << endl;

	return 0;
}




Measured memory_bytes: 1792
import java.util.Scanner;

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

		int N = sc.nextInt();
		int res = 0;

		if (N % 2 == 0) {
			res = N;
		} else {
			res = N * 2;
		}

		System.out.println(res);
	}
}

Measured memory_bytes: 22868
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <algorithm>
#include <list>
using namespace std;
typedef long long ll;

int main() {
    string s;
    cin >> s;
    if(s.size() == 2) cout << s << endl;
    else{
        char t = s[0];
        s[0] = s[2];
        s[2] = t;
        cout << s << endl;
    }
}

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

bool ok(const vector<pair<int,int> > &v, int w) {
  int x = 0;
  for(int i = 0; i < v.size(); ++i) {
    if(x < v[i].first) return false;
    x = max(x, v[i].second);
  }
  return x == w;
}

int main() {
  for(int N, W, H;
      cin >> N >> W >> H && (N|W|H); ) {
    vector<pair<int,int> > xs, ys;
    for(int i = 0; i < N; ++i) {
      int x, y, w;
      cin >> x >> y >> w;
      xs.push_back(make_pair(max(0, x-w), min(W, x+w)));
      ys.push_back(make_pair(max(0, y-w), min(H, y+w)));
    }
    sort(xs.begin(), xs.end());
    sort(ys.begin(), ys.end());
    if(ok(xs, W) || ok(ys, H))
      cout << "Yes" << endl;
    else
      cout << "No" << endl;
  }
  return 0;
}

Measured memory_bytes: 2904
#include <stdio.h>
#include <stdlib.h>

 typedef struct  Point {
    float x;
    float y;
}fPoint;

float area(float x1, float y1, float x2, float y2, float x3, float y3)
{
   return abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0);
}


bool isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y)
{
   /* Calculate area of triangle ABC */
   float A = area (x1, y1, x2, y2, x3, y3);

   /* Calculate area of triangle PBC */
   float A1 = area (x, y, x2, y2, x3, y3);

   /* Calculate area of triangle PAC */
   float A2 = area (x1, y1, x, y, x3, y3);

   /* Calculate area of triangle PAB */
   float A3 = area (x1, y1, x2, y2, x, y);

   /* Check if sum of A1, A2 and A3 is same as A */
   return (A == A1 + A2 + A3);
}
float sign(fPoint p1, fPoint p2, fPoint p3)
{
  return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
}

bool PointInTriangle(fPoint pt, fPoint v1, fPoint v2, fPoint v3)
{
  bool b1, b2, b3;

  b1 = sign(pt, v1, v2) < 0.0f;
  b2 = sign(pt, v2, v3) < 0.0f;
  b3 = sign(pt, v3, v1) < 0.0f;

  return ((b1 == b2) && (b2 == b3));
}

int main()
{

   float x1,x2,x3,x4,x5,x6,x7,x8;
   while(scanf("%f%f%f%f%f%f%f%f",&x1,&x2,&x3,&x4,&x5,&x6,&x7,&x8)==8)
   {
       fPoint pt,v1,v2,v3;
       pt.x=x7;
       pt.y=x8;
       v1.x=x1;
       v1.y=x2;
       v2.x=x3;
       v2.y=x4;
       v3.x=x5;
       v3.y=x6;



       if (PointInTriangle( pt, v1, v2, v3))
        printf ("YES\n");
      else
         printf ("NO\n");

   }


   return 0;
}

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

int main(){

    size_t n, k;
    std::cin >> n >> k;

    std::vector<size_t> h(n);

    for(auto&& e : h){
        std::cin >> e;
    }

    std::sort(h.begin(), h.end());

    size_t min = std::numeric_limits<size_t>::max();
    for(size_t i = 0; i + k - 1 < n; i++){
        min = std::min(min, h.at(i + k - 1) - h.at(i));
    }
    
    std::cout << min << std::endl;

    return 0;
}


Measured memory_bytes: 1024
A, B = map(int, input().split())

x = A * 100 // 8
flag = False

for i in range(13):
  if (x+i) * 8 // 100 == A and (x+i) // 10 == B:
    print(x+i)
    flag = True
    break

if flag == False:
  print(-1)

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

# define REP(i,n) for (int i=0;i<(n);++i)
# define rep(i,a,b) for(int i=a;i<(b);++i)
# define p(s) std::cout << s ;
# define pl(s)  std::cout << s << endl;
# define printIf(j,s1,s2) cout << (j ? s1 : s2) << endl;
# define YES(j) cout << (j ? "YES" : "NO") << endl;
# define Yes(j) std::cout << (j ? "Yes" : "No") << endl;
# define yes(j) std::cout << (j ? "yes" : "no") << endl;
# define all(v) v.begin(),v.end()
# define showVector(v) REP(i,v.size()){p(v[i]);p(" ")} pl("")
template<class T> inline bool chmin(T &a, T b){ if(a > b) { a = b; return true;} return false;}
template<class T> inline bool chmax(T &a, T b){ if(a < b) { a = b; return true;} return false;}
typedef long long int ll;
typedef pair<ll,ll> P_ii;
typedef pair<double,double> P_dd;

template<class T>
vector<T> make_vec(size_t a){
    return vector<T>(a);
}

template<class T, class... Ts>
auto make_vec(size_t a, Ts... ts){
  return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...));
}

template<typename T,typename V>
typename enable_if<is_class<T>::value==0>::type
fill_v(T &t,const V &v){t=v;}

template<typename T,typename V>
typename enable_if<is_class<T>::value!=0>::type
fill_v(T &t,const V &v){
  for(auto &e:t) fill_v(e,v);
}


const int MOD = 1000000007;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;

void addM(long long &a, long long b) {
    a += b;
    if (a >= MOD) a -= MOD;
}

void mulM(long long &a, long long b) {
    a = ((a%MOD)*(b%MOD))%MOD ;
}

// a^b mod M
long myPow(long a,long b,int M) {
    long ret = 1;
    long tmp = a;
    while(b>0) {
        if((b&1)==1) ret = (ret * tmp) % M;
        tmp = (tmp * tmp) % M;
        b = b>>1;
    }
    return ret;
}

 // nCk mod M
int nCk(int n,int k,int M) {
    long ret = 1;
    int mi = min(k, n-k);
    for(int i=1;i<=mi;i++) {
        ret = (ret * myPow(i,M-2,M)) % M;
    }
    for(int i=n-mi+1;i<=n;i++) {
        ret = (ret * i) % M;
    }
    return (int)ret;
};

vector<pair<long long, long long> > prime_factorize(long long n) {
    vector<pair<long long, long long> > res;
    for (long long p = 2; p * p <= n; ++p) {
        if (n % p != 0) continue;
        int num = 0;
        while (n % p == 0) { ++num; n /= p; }
        res.push_back(make_pair(p, num));
    }
    if (n != 1) res.push_back(make_pair(n, 1));
    return res;
}


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

    string s_m_a = ""; 
    REP(i,s.size()) if(s[i]!='A') s_m_a += s[i];

    if(s_m_a != "KIHBR"){
        pl("NO")
    } else {
        REP(i,s.size()) if(s[i]=='A') {
            if(i==0 || s[i-1]=='H' || s[i-1]=='B' || s[i-1]=='R') continue;
            else {
                pl("NO")
                return 0;
            }
        }
        pl("YES")
    }

    return 0;
}

Measured memory_bytes: 256
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
#define MAX 114514
typedef long long int ll;
int main(){
   string s;
   cin>>s;
   int ans=0;
   for(int i=0;i<s.length();i++){
       if(s[i]=='2')ans++;
   }
   cout<<ans<<endl;
}

Measured memory_bytes: 256
#include <algorithm>
#include <iostream>
#include <string>
#include <stack>
#include <utility>
#include <vector>
#include <math.h>

#define rep(i, n) for (auto i = 0; i < (n); i++)
#define MOD 1e9 + 7
typedef long long ll;

using namespace std;

int main() {
  ll x, k, d;
  cin >> x >> k >> d;
  ll t = (ll)round((long double)abs(x)/d);
  if (x > 0) {
    if (k <= t) {
      cout << abs(x - k * d) << endl;
    } else {
      if ((k - t) % 2 == 0) {
        cout << abs(x - t * d) << endl;
      } else {
        ll c1 = abs(x - t * d + d);
        ll c2 = abs(x - t * d - d);
        cout << min(c1, c2) << endl;
      }
    }
  } else {
    if (k <= t) {
      cout << abs(x + k * d) << endl;
    } else {
      if ((k - t) % 2 == 0) {
        cout << abs(x + t * d) << endl;
      } else {
        ll c1 = abs(x + t * d + d);
        ll c2 = abs(x + t * d - d);
        cout << min(c1, c2) << endl;
      }
    }
  }

  return 0;
}



Measured memory_bytes: 3148
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll mod=1e9+7;
const int maxn=1e6+7;
ll fac[maxn];
ll inv[maxn];
ll C(int m,int n)
{
    if(m>n)
        return -1;
    return fac[n]*inv[m]%mod*inv[n-m]%mod;
}
ll quick_mod(ll a,ll m)
{
    ll tmp=a%mod;
    ll ans=1;
    while(m)
    {
        if(m&1)
            ans=ans*tmp%mod;
        tmp=tmp*tmp%mod;
        m>>=1;
    }
    return ans;
}
void init()
{
    fac[0]=1;
    for(int i=1; i<maxn; i++)
        fac[i]=(fac[i-1]*i)%mod;
    inv[maxn-1]=quick_mod(fac[maxn-1],mod-2);
    for(int i=maxn-2; i>=0; i--)
        inv[i]=(inv[i+1]*(i+1))%mod;
}

int main()
{
    init();
    int x,y;
    scanf("%d %d",&x,&y);
    if((x+y)%3!=0)
        printf("0\n");
    else
    {
        ll t=(x+y)/3;
        ll k1=x-t;
        ll k2=y-t;
        if(x*2>=y&&y*2>=x)
            printf("%lld\n",C(k1,k1+k2));
        else
            printf("0\n");
    }
    return 0;

}


Measured memory_bytes: 15872
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

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

		int n = sc.nextInt();	//N個の街
		long k = sc.nextLong();	//k回テレポート



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

		int[] ord = new int[n+1];
		for(int i = 0; i < n + 1; i++) {
			ord[i] = -1;
		}

		int now = 1;
		List<Integer> list = new ArrayList<>();
		while(ord[now] == -1) {
			ord[now] = list.size();
			list.add(now);
			now = array[now -1];

		}

		int c = list.size() - ord[now]; //周期
		int l = ord[now];

		if(k < l) {
			System.out.println(list.get((int)k));
		}else {
			k -= l;
			k %= c;
			System.out.println(list.get((int)k+l));
		}

	}
}


Measured memory_bytes: 61636
N = gets.to_i
ans = N % 2 == 1 ? "1" : "0"

def solve_aux(n)
    quo,rem = 0,0
    if n % 2 == 1
        quo = (n / -2) + 1
        rem = 1
    else
        quo = n / -2
        rem = n % -2
    end
    return [quo,rem]
end

def solve(n,ans)
    #puts [n,ans]
    return ans if n == 0
    quo,rem = solve_aux(n)
    if quo != 0
        solve(quo,rem.to_s + ans)
    else
        return rem.to_s + ans
    end
end

first,rem = solve_aux(N)
puts solve(first,ans)


Measured memory_bytes: 1788
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

struct pairs{
    long b;
    long c;
};

int main()
{

    int N, M;
    cin >> N >> M;
    vector<long> A(N);
    vector<pairs> P(M);
    long b, c;

    for (int i = 0; i < N; i++)
        cin >> A[i];
    for (int i = 0; i < M; i++) {
        cin >> b >> c;
        pairs p;
        p.b = b;
        p.c = c;
        P[i] = p;
    }

    sort(P.begin(), P.end(), [](const pairs& x, const pairs& y) { return x.c > y.c;});
        

    priority_queue<long, vector<long>, greater<long>> que;
    for (int i = 0; i < N; i++)
        que.push(A[i]);

    for (int i = 0; i < M; i++) {
        for (int j = 0; j < P[i].b; j++) {
            if (que.top() < P[i].c) {
                que.pop();
                que.push(P[i].c);
            } else {
                break;
            }
        }
    }

    long ans = 0;
    while (!que.empty()) {
        ans += que.top();
        que.pop();
    }

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


Measured memory_bytes: 3704
#include<iostream>
#include<cstdio>
#include<cstring>
#include <cstdlib>  
#include <math.h>
#include <cmath>
#include<cctype>
#include<string>
#include<set>
#include<iomanip>
#include <map>
#include<algorithm>
#include <functional>
#include<vector>
#include<climits>
#include<stack>
#include<queue>
#include<bitset>
#include <deque>
#include <climits>
#include <typeinfo>
#include <utility> 
using namespace std;
using ll = long long;
template<typename T>using min_priority_queue = priority_queue<T, vector<T>, greater<T>>;
const ll inf = 1LL << 60;
#define all(x) (x).begin(),(x).end()
#define puts(x) cout << x << endl;
#define rep(i,m,n) for(ll i = m;i < n;++i)
#define pb push_back
#define fore(i,a) for(auto &i:a)
#define rrep(i,m,n) for(ll i = m;i >= n;--i)
#define INF INT_MAX/2

const int MAX = 505050;
const int MOD = 1000000007;
ll fac[MAX], finv[MAX], inv[MAX];

void combinit() {
	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;
	}
}
ll comb(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;
}

ll choufuku(int n1, int n2, int n3, int y) {
	return comb(y-n1-n2-n3+2,2);
}


ll houjo(int n1,int n2,int n3,int y) {
	ll tmp1 = choufuku(0, 0, 0, y);
	ll tmp2 = choufuku(n1+1,0,0,y)+choufuku(0,n2+1,0,y)+choufuku(0,0,n3+1,y)-choufuku(n1+1,n2+1,0,y)-choufuku(0,n2+1,n3+1,y)-choufuku(n1+1,0,n3+1,y)+choufuku(n1+1,n2+1,n3+1,y);
	return ((tmp1 - tmp2)+10LL*MOD)%MOD;
}

int main() {
	combinit();
	int n;
	cin >> n;
	vector<int>a(n+1);
	map<int,int>mp;
	int db;
	rep(i, 0, n+1) {
		cin >> a[i];
		mp[a[i]]++;
		if (mp[a[i]] == 2)db = a[i];
	}
	vector<int>num(3);
	int cnt = 0;
	int f = 0;
	rep(i, 0, n + 1) {
		if (a[i] == db) {
			num[f] = cnt;
			cnt = 0;
			f++;
		}
		else {
			cnt++;
		}
	}
	num[f] = cnt;

	rep(i, 0, n + 1) {
		ll tot = comb(n + 1, i + 1);
		ll cho1 = comb(num[0] + num[2], i)-comb(num[0],i)-comb(num[2],i);
		ll cho2 = comb(num[0], i);
		ll cho3 = comb(num[2], i);
		puts((tot - cho1 - cho2 - cho3+ 10LL * MOD)%MOD)
	}
	
	
	return 0;
}


Measured memory_bytes: 18176
def main():
    import sys
    sys.setrecursionlimit(10 ** 7)

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

    digits = {x for x in range(10)}
    digits -= D
    # print(digits)
    digits = sorted(digits)

    def dfs(pay):
        if pay >= N:
            return pay

        np = pay * 10

        ret = 1 << 60
        if np == 0 and 0 in digits:
            for d in digits:
                if d == 0: continue
                ret = min(ret, dfs(np + d))
        else:
            for d in digits:
                ret = min(ret, dfs(np + d))
        return ret

    print(dfs(0))


if __name__ == '__main__':
    main()


Measured memory_bytes: 3064
#include <bits/stdc++.h>
using namespace std;
 
int main(){
double A, B, T;
  cin >> A >> B >> T;
 T+= 0.5;
  
double ans = 0;
 
int kaisuu =  T / A; 
  while(kaisuu){
  ans += B;
    A += A; 
    kaisuu--;
  }
  
cout << ans << endl; 
return 0;
  
}

Measured memory_bytes: 256
# -*- coding: utf-8 -*-

N = int(input())
S = []

for i in range(N):
    S.append(int(input()))

if sum(S)%10 != 0:
    print(sum(S))
    exit()

sumv = sum(S)
S.sort()

for s in S:
    if s % 10 != 0:
        sumv -= s
        print(sumv)
        exit()
print(0)

Measured memory_bytes: 3060
#define _USE_MATH_DEFINES
#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <complex>
#include <string>
#include <vector>
#include <array>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <limits>
#include <climits>
#include <cfloat>
#include <functional>
#include <iterator>
using namespace std;

int dfs(const vector<vector<int> >& edges, int curr, int prev, int limit)
{
    multiset<int> ms;
    for(int next : edges[curr]){
        if(next == prev)
            continue;
        int x = dfs(edges, next, curr, limit);
        if(x == -1)
            return -1;
        ms.insert(x);
    }

    vector<int> v;
    while(!ms.empty()){
        int x = *ms.rbegin();
        ms.erase(--ms.end());

        auto it = ms.upper_bound(limit - 1 - x);
        if(it == ms.begin()){
            v.push_back(x);
        }
        else{
            -- it;
            ms.erase(it);
        }
    }

    if(!v.empty() && limit < v[0] + 1)
        return -1;

    if(v.empty())
        return 1;
    else if(v.size() == 1)
        return v[0] + 1;
    else if(v.size() == 2 && prev != -1)
        return v[1] + 1;
    else
        return -1;
}

pair<int, int> solve(const vector<vector<int> >& edges)
{
    int n = edges.size();
    int ans = 1;
    for(int i=0; i<n; ++i)
        ans += (edges[i].size() - 1) / 2;

    int left = 1;
    int right = n;
    while(left < right){
        int mid = (left + right) / 2;
        if(dfs(edges, 0, -1, mid) != -1)
            right = mid;
        else
            left = mid + 1;
    }

    return make_pair(ans, left - 1);
}

int main()
{
    int n;
    cin >> n;
    vector<vector<int> > edges(n);
    for(int i=0; i<n-1; ++i){
        int a, b;
        cin >> a >> b;
        -- a;
        -- b;
        edges[a].push_back(b);
        edges[b].push_back(a);
    }

    pair<int, int> ans = solve(edges);
    cout << ans.first << ' ' << ans.second << endl;

    return 0;
}


Measured memory_bytes: 21632
#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 emplace_back
#define INF (1e9+1)
//#define INF (1LL<<59)


vector<string> v{"",".,!? ","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};

int main(){
    int n;
    cin>>n;
    while(n--){
        string s;
        cin>>s;
        char ch;
        int num=0;
        
        string ans = "";
        rep(i,s.size()){
            if(s[i]=='0'){
                if(num==0)continue;
                ans+=v[ch-'0'][(num-1)%((int)v[ch-'0'].size())];
                num = 0;
            }else{
                if(num==0)ch = s[i];
                num++;
            }
        }
        cout<<ans<<endl;
    }
}

Measured memory_bytes: 3160
#define _USE_MATH_DEFINES

#include <iostream>
#include <iomanip>
#include <stdio.h>

#include <sstream>
#include <algorithm>
#include <iterator>
#include <cmath>
#include <complex>

#include <string>
#include <cstring>
#include <vector>
#include <bitset>

#include <queue>
#include <set>
#include <map>
#include <stack>
#include <list>

#include <ctime>
////
//#include <random>//
/////////

typedef long long LL;
typedef long double LD;
typedef unsigned long long ULL;

////定数
const int INF = (int)1e9 + 10;
const LL MOD = (LL)1e9 + 7;
const LL LINF = (LL)4e18 + 20;
const LD PI = acos(-1.0);
const double EPS = 1e-9; 
/////////
using namespace::std;
//////////////

void solve() {
	string S;
	cin >> S;
	int N = S.size();
	int ans = 0;
	for (int i = 0; i < N; ++i) {
		if (S[i] == 'g') {
			if (i % 2 == 0) {
				
			}
			else {
				++ans;
			}
		}
		else {
			if (i % 2 == 0) {
				--ans;
			}
			else {
			}
		}
	}
	cout << ans << endl;
}

signed main(void) {
	std::cin.tie(0);
	std::ios::sync_with_stdio(false);
	std::cout << std::fixed;//小数を10進数表示
	cout << setprecision(16);//小数点以下の桁数を指定//coutとcerrで別	

	solve();
}


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

h.sort()

ans = 10000000000000000

for i in range(n-k+1):
  if ans > h[i+k-1]-h[i]:
    ans = h[i+k-1]-h[i]

print(ans)

Measured memory_bytes: 50264
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <complex>
#include <utility>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
#include <bitset>
#include <ctime>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <cassert>
#include <cstddef>
#include <iomanip>
#include <numeric>
#include <tuple>
#include <sstream>
#include <fstream>
#include <functional>

using namespace std;
#define REP(i, n) for (int (i) = 0; (i) < (n); (i)++)
#define FOR(i, a, b) for (int (i) = (a); (i) < (b); (i)++)
#define RREP(i, a) for(int (i) = (a) - 1; (i) >= 0; (i)--)
#define FORR(i, a, b) for(int (i) = (a) - 1; (i) >= (b); (i)--)
#define DEBUG(C) cerr << #C << " = " << C << endl;
using LL = long long;
using VI = vector<int>;
using VVI = vector<VI>;
using VL = vector<LL>;
using VVL = vector<VL>;
using VD = vector<double>;
using VVD = vector<VD>;
using PII = pair<int, int>;
using PDD = pair<double, double>;
using PLL = pair<LL, LL>;
using VPII = vector<PII>;
template<typename T> using VT = vector<T>;
#define ALL(a) begin((a)), end((a))
#define RALL(a) rbegin((a)), rend((a))
#define SORT(a) sort(ALL((a)))
#define RSORT(a) sort(RALL((a)))
#define REVERSE(a) reverse(ALL((a)))
#define MP make_pair
#define FORE(a, b) for (auto &&a : (b))
#define EB emplace_back
#define GREATER(T) T, VT<T> greater<T>
template<typename T> inline bool chmax(T &a, T b){if (a < b){a = b;return true;}return false;}
template<typename T> inline bool chmin(T &a, T b){if (a > b){a = b;return true;}return false;}

const int INF = 1e9;
const int MOD = INF + 7;
const LL LLINF = 1e18;

int calc(const string &S, int mid) {
    VI inv_r, inv_w;
    REP(i, S.size()) {
        if (S[i] == 'R' && mid <= i) {
            inv_r.EB(i);
        } else if (S[i] == 'W' && i < mid) {
            inv_w.EB(i);
        }
    }

    const int mi = min(inv_r.size(), inv_w.size());
    return inv_r.size() + inv_w.size() - mi;
}

void solve() {
    int N;
    cin >> N;
    string S;
    cin >> S;

    int low = 0, high = N + 1;
    while (high - low > 10) {
        const int mid1 = (high + low + low) / 3;
        const int mid2 = (high + high + low) / 3;

        if (calc(S, mid1) <= calc(S, mid2)) {
            high = mid2;
        } else {
            low = mid1;
        }
    }

    // REP(i, N + 1) DEBUG(calc(S, i))

    int ans = INF;
    FOR(i, low, high + 1) {
        chmin(ans, calc(S, i));
    }

    cout << ans << endl;
}

int main(void) {
#ifndef ONLINE_JUDGE
    const auto in_stream = freopen("../in.txt", "r", stdin);
    if (in_stream == nullptr) {
        cerr << "ERROR!" << endl;
        return 1;
    }
#endif

    solve();

#ifndef ONLINE_JUDGE
    fclose(in_stream);
#endif
}


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

int main(int argc, char *argv[])
{
    int N, Y;
    std::cin >> N >> Y;
    int x = -1;
    int y = -1;
    int z = -1;

    for (int i = 0; i <= N; i++) {
        for (int j = 0; i + j <= N; j++) {
            int total = i * 10000 + j * 5000 + (N - i - j) * 1000;
            if (total == Y) {
                x = i;
                y = j;
                z = N - i - j;
            }
        }
    }

    std::cout << x << " " << y << " " << z << std::endl;

    return 0;
}

Measured memory_bytes: 256
#pragma GCC optimize ("O2")
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wunused-result"
#pragma GCC diagnostic ignored "-Wunused-label"
#pragma GCC diagnostic ignored "-Wsign-compare"

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

#define rep(i, a, b) for (int i = (a); i < (b); ++i)
#define trav(a, A) for (auto & a : A)
#define all(a) (a).begin (), (a).end ()
#define f first
#define s second

typedef long long ll;

const ll MOD = 1e+9+7;
const ll INFLL = 0x3f3f3f3f3f3f3f3f;
const int INF = 0x3f3f3f3f;
const ll MAXN = 1e+6+7;

int main ()
{
	ios_base::sync_with_stdio (0);
	cin.tie (0);
	int tc = 1; //cin >> tc;
	while (tc--)
	{
		int i, j, n;
		vector <vector <int>> cart (3, vector <int> (3));
		trav (v, cart)
			trav (a, v)
				cin >> a;
		cin >> n;
		for (i = 0; i < n; ++i)
		{
			cin >> j;
			trav (v, cart)
				trav (a, v)
					if (a == j)
						a = -1;
		}
		bool ans = false;
		for (i = 0; i < cart.size (); ++i)
		{
			bool temp = true;
			for (j = 0; j < cart[i].size (); ++j)
			{
				if (cart[i][j] != -1)
					temp = false;
			}
			if (temp)
				ans = true;
		}
		for (j = 0; j < cart[0].size (); ++j)
		{
			bool temp = true;
			for (i = 0; i < cart.size (); ++i)
			{
				if (cart[i][j] != -1)
					temp = false;
			}
			if (temp)
				ans = true;
		}
		bool temp = true;
		for (i = 0; i < cart.size (); ++i)
		{
			if (cart[i][i] != -1)
				temp = false;
		}
		if (temp)
			ans = true;
		temp = true;
		for (i = 0; i < cart.size (); ++i)
			if (cart[i][cart.size () - i - 1] != -1)
				temp = false;
		if (temp)
			ans = true;
		if (ans) cout << "Yes\n";
		else cout << "No\n";
	}

	return 0;
}



Measured memory_bytes: 256
import java.util.*;

class Main {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        long n=sc.nextInt();
        long k=sc.nextInt();
        if(k%2==0){
            System.out.println((long)Math.pow(((n+k/2)/k),3)+(long)Math.pow(n/k,3));
        }else{
            System.out.println((long)Math.pow(n/k,3));
        }

    }
}

Measured memory_bytes: 23252
import math
A, B, H, M = [int(i) for i in input().split()]
short_hand = ((H * 60 + M) * 0.5) % 360
long_hand = M * 6
theta = abs(short_hand - long_hand)
C = (A**2 + B**2 - 2*A*B*math.cos(theta / 180 * math.pi)) ** 0.5
print(C)

Measured memory_bytes: 9512
#include "bits/stdc++.h"

#define REP(i,n) for(ll i=0;i<ll(n);++i)
#define RREP(i,n) for(ll i=ll(n)-1;i>=0;--i)
#define FOR(i,m,n) for(ll i=m;i<ll(n);++i)
#define RFOR(i,m,n) for(ll i=ll(n)-1;i>=ll(m);--i)
#define ALL(v) (v).begin(),(v).end()
#define UNIQUE(v) v.erase(unique(ALL(v)),v.end());
#define DUMP(v) REP(aa, (v).size()) { cout << v[aa]; if (aa != v.size() - 1)cout << " "; else cout << endl; }
#define INF 1000000001ll
#define MOD 1000000007ll
#define EPS 1e-9

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


using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
ll max(ll a, int b) { return max(a, ll(b)); }
ll max(int a, ll b) { return max(ll(a), b); }
ll min(ll a, int b) { return min(a, ll(b)); }
ll min(int a, ll b) { return min(ll(a), b); }


int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	ll x, y;
	cin >> x >> y;
	ll d = x - y;
	if (d < 0)d *= -1;
	if (d <= 1)cout << "Brown" << endl;
	else cout << "Alice" << endl;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 100000 + 10;
int a[32] = {1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51};
int main(){
    int n; cin>>n; cout<<a[n-1]<<endl;
}


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

using namespace std;

const int mx = 1e5+5;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
typedef pair<int,int>pii;
typedef pair<int,pii>piii;

#define  sf scanf
#define  pf printf

#define  input freopen("input.txt","r",stdin)
#define  output freopen("output.txt","w",stdout)

#define  inf 1e8
#define  ff first
#define  ss second
#define  MP make_pair
#define  pb push_back
#define  all(v) v.begin(), v.end()
#define  printcase(cases) printf("Case %d:", cases);
#define  Unique(a) a.erase(unique(a.begin(),a.end()),a.end())
#define  FAST  ios_base::sync_with_stdio(0);cout.tie(0)
#define  endl printf("\n")
#define  __lcm(a, b) ((a*b)/__gcd(a, b))

int  Set(int N,int pos){return N=N | (1<<pos);}
int  reset(int N,int pos){return N= N & ~(1<<pos);}
bool check(int N,int pos){return (bool)(N & (1<<pos));}
vector<pii>adj[mx];
int dis[mx];
int k;

int bfs(int src)
{
    priority_queue<pii, vector<pii>, greater<pii> >pq;
    pq.push(make_pair(0, src));
    for(int i = 0; i < mx; i++) dis[i] = inf;
    dis[src] = 0;
    while(!pq.empty())
    {
        pii top = pq.top();
        pq.pop();
        int u = top.ss;
        int curw = top.ff;
        for(int i = 0; i < adj[u].size(); i++)
        {
            int v = adj[u][i].ff;
            int w = adj[u][i].ss;
            if(w+curw<dis[v])
            {
                dis[v] = curw+w;
                pq.push(make_pair(dis[v], v));
            }
        }
    }
    //for(int i = 0; i < k; i++) cout << dis[i] << ' ';
    //cout << '\n';
    return dis[k];
}
int main()
{
    sf("%d", &k);

    for(int x = 0; x <= k; x++)
    {
        for(int p = 0; p <= 9; p++)
        {
            int u = x;
            int v = ((10*x)+p)%k;
            if(v == 0) v = k;
            if(v==k && u==0 && p==0) continue;
            adj[u].push_back(make_pair(v, p));
        }
    }
    int ans = bfs(0);
    pf("%d\n", ans);
    return 0;
}


Measured memory_bytes: 19188
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		try{
			while(true) {
				String str=scan.next();
				if(str.equals("-")){
					break;
				}
				int x=scan.nextInt();
				String str1;
				String str2;
				for(int i=0;i<x;i++) {
					int a=scan.nextInt();
					str1=str.substring(0,a);
					str2=str.substring(a);
					str=str2+str1;
				}
				System.out.println(str);
			}
			scan.close();
		}catch(InputMismatchException e){
			System.out.println("入力しなおしてください");
		}
		}
}


Measured memory_bytes: 26336
#include<bits/stdc++.h>
#define rep(i,n)for(int i=0;i<n;++i)
#include<string>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int, int>P;
//max=({});
//条件式が真ならwhileの中身を回し続ける
//printf("%d\n", ans);

//pairの入力
//vector<pair<ll, ll>>work(n);
//rep(i, n) {
//	ll a, b;
//	cin >> a >> b;
//	work[i] = make_pair(a, b);
//}

int g[15][15];
const int INF = 1001001001;
const int dx[4] = { -1,0,1,0 };
const int dy[4] = { 0,-1,0,1 };

//最大公約数
ll gcd(ll x, ll y) {
	return y ? gcd(y, x % y) : x;
}

//素因数分解
vector<pair<ll, int>>factorize(ll n) {
	vector<pair<ll, int>>res;
	for (ll i = 2;i * i <= n;++i) {
		if (n % i)continue;
		res.emplace_back(i, 0);
		while (n % i == 0) {
			n /= i;
			res.back().second++;
		}
	}
	if (n != 1)res.emplace_back(n, 1);
	return res;
}

int dp[1010][1010];
int bingo[3][3];
bool flag[3][3];

int n;

void dfs(string s, char mx) {
	if (s.length() == n) {
		printf("%s\n", s.c_str());
	}
	else {
		for (char c = 'a';c <= mx;c++) {
			dfs(s + c, ((c == mx) ? (char)(mx + 1) : mx));
		}
	}
}

int main() {
	cin >> n;
	dfs("", 'a');
	return 0;
}


Measured memory_bytes: 1536
A = list(map(int, input().split()))
five_cnt = 0
seven_cnt = 0

for a in A:
    if a == 5:
        five_cnt += 1
    elif a == 7:
        seven_cnt += 1

if five_cnt == 2 and seven_cnt == 1:
    print('YES')
else:
    print('NO')


Measured memory_bytes: 2940
#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<string>
#include<limits.h>
#include<utility>
#include<vector>
#include<tuple>
#include <map>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
#define rep(i,n) for(int i=0;i<n;i++)
#define ALL(A) A.begin(),A.end()
#define FOR(i,I,n) for(int i=I;i<=n;i++)
int main() {
	int n, m, q;
	cin >> n >> m >> q;
	vector<pair<P, P>> Q(q);
	rep(i, q) {
		cin >> Q[i].first.first >> Q[i].first.second >> Q[i].second.first >> Q[i].second.second;
	}
	vector<int> a(11, 1);
	sort(ALL(Q));
	ll ans = 0;
	FOR(i2, 1, m) {
		a[2] = i2;
		FOR(i3, i2, m) {
			a[3] = i3;
			FOR(i4, i3, m) {
				a[4] = i4;
				FOR(i5, i4, m) {
					a[5] = i5;
					FOR(i6, i5, m) {
						a[6] = i6;
						FOR(i7, i6, m) {
							a[7] = i7;
							FOR(i8, i7, m) {
								a[8] = i8;
								FOR(i9, i8, m) {
									a[9] = i9;
									FOR(i10, i9, m) {
										a[10] = i10;
										ll tmp = 0;
										for (pair<P, P> point : Q) {
											
											if (a[point.first.second] - a[point.first.first] == point.second.first) {
												tmp += point.second.second;
											}
										}
										if (ans < tmp) {
											ans = tmp;
										}

									}
								}
							}
						}
					}
				}
			}
		}
	}

	cout << ans << endl;
}


Measured memory_bytes: 3164
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define REP(i,n) for(ll i=0, i##_len=(n); i<i##_len; ++i)
#define REPR(i,n) for(ll i = n;i >= 0;--i)
#define FOR(i,m,n) for(ll i = m, i##_len=(n);i <i##_len; ++i)
#define all(x) (x).begin(),(x).end()
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
const int INF = 1e9;
const ll LLINF = 1e16;
 
ll modinv(ll a, ll m) {
    ll b = m, u = 1, v = 0;
    while (b) {
        ll t = a / b;
        a -= t * b; swap(a, b);
        u -= t * v; swap(u, v);
    }
    u %= m;
    if (u < 0) u += m;
    return u;
}

int main(void)
{
    int n;
    cin >> n;
    vector<int> h(n);
    REP(i, n) cin >> h[i];
    vector<int> cost(n, 0);
    cost[1] = abs(h[0] - h[1]);
    FOR(i, 2, n)
    {
        cost[i] = min(cost[i - 1] + abs(h[i - 1] - h[i]), cost[i - 2] + abs(h[i - 2] - h[i]));
    }

    cout << cost[n - 1] << endl;

    return 0;
}

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

int main() {
  int n;
  cin >> n;
  vector<int> l(n);
  for (int i = 0; i < n; i++) {
    cin >> l[i];
  }

  sort(l.begin(), l.end(), greater<int>());
  int sum = 0;
  for (int i = 1; i < n; i++) {
    sum += l[i];
  }
  if (l[0] < sum) {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }
}

Measured memory_bytes: 256
import sys
sys.setrecursionlimit(10 ** 6)

N = int(input())

G = []
for i in range(N):
    G.append([])

color = [None] * N

for i in range(N-1):
    u, v, w = list(map(int, input().split()))
    G[u-1].append([v-1, w])
    G[v-1].append([u-1, w])

# for i in range(N):
#     print(G[i])

def dfs(v, c):
    color[v] = c

    # vと隣接する点
    for p, d in G[v]:
        # 訪問済み
        if color[p] is not None:
            continue
        if d % 2 == 0:
            dfs(p, c)
        else:
            dfs(p, c ^ 1)  # 排他的論理和で0, 1をひっくり返す

# 0の頂点を0で塗る
dfs(0, 0)

# print(color)
for col in color:
    print(col)

Measured memory_bytes: 85808
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <iomanip>
//#include <unordered_map>
//#include <unordered_set>
using namespace std;
#define fi first
#define se second
#define ll long long
#define pb push_back
#define vi vector<int>
#define pii pair<int,int>
#define mem(a,b) memset(a,b,sizeof(a))
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int INF = 0x3f3f3f3f;

inline int read () {
	register int s = 0, w = 1;
	register char ch = getchar ();
	while (! isdigit (ch)) {if (ch == '-') w = -1; ch = getchar ();}
	while (isdigit (ch)) {s = (s << 3) + (s << 1) + (ch ^ 48); ch = getchar ();}
	return s * w;
}


int main() {
	IOS;
	//freopen("D:\\in.txt","r",stdin);
	//freopen("D:\\out2.txt","w",stdout);
	int n,k;
	cin>>n>>k;
	if(n*500>=k)cout<<"Yes"<<endl;
	else cout<<"No"<<endl;
	


	return 0;
}


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

int main(){
	long long N;
	cin >> N;
	vector<long long> A(N);
	for(auto &a:A)cin >> a;
	
	long long sum=accumulate(A.begin(),A.end(),0LL);
	if(sum%((N*N+N)/2LL)!=0LL){
		cout << "NO" << endl;
		return 0;
	}
	long long C=sum/((N*N+N)/2LL);
	
	if(*min_element(A.begin(),A.end())<C){
		cout << "NO" << endl;
		return 0;		
	}
	
	long long c=0LL;
	for(auto i=0;i<N;i++){
		long long L=A[i],R;
		if(i==N-1)R=A[0];
		else R=A[i+1];
			
		if((C-(R-L))%N!=0LL){
			cout << "NO" << endl;
			return 0;
		}
		c+=(C-(R-L))/N;
	}
	//cout << C << " " << c << endl;
	
	if(c==C)cout << "YES" << endl;
	else cout << "NO" << endl;
	return 0;
}

Measured memory_bytes: 1024
#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  set<int> a;
  int m;
  for(int i = 0;i < n;i++) {
    cin >> m;
    if(a.count(m)) {
      a.erase(m);
    }else {
      a.insert(m);
    }
  }
  cout << a.size() << endl;
}

Measured memory_bytes: 4864
#include<bits/stdc++.h>
using namespace std;
#define ll long long
typedef vector <ll> vi;
int main()
{
  ll n,m;
  cin>>n>>m;
  ll low=0;
  ll high=n;
  for(ll i=0;i<m;i++)
  {
    ll x,y;
    cin>>x>>y;
    low=max(low,x);
    high=min(high,y);
  }
  if(low<=high)
  {
    cout<<high-low+1<<endl;
  }
  else
  {
    cout<<0<<endl;
  }
}
  






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

using namespace std;
using LL = long long;
using P = pair<int,int>;

int main(){
	int H1, M1, H2, M2, K;
	cin >> H1 >> M1 >> H2 >> M2 >> K;
	int d=(H2-H1)*60+(M2-M1);
	cout << d-K << endl;

	return 0;
}

Measured memory_bytes: 3624
# 接続最大クラスタのサイズが答え？

N, M = [int(x) for x in input().split(' ')]

# from collections import defaultdict
# d = defaultdict(set)

# for i in range(M):
#     a, b = [int(x) for x in input().split(' ')]
#     d[a].add(b)
#     d[b].add(a)

class UF:
    def __init__(self):
        self.r = [-1] * N

    def root(self, i):
        r = self.r
        if r[i] < 0:
            return i
        else:
            r[i] = self.root(r[i])
            return r[i]

    def union(self, i, j):
        i -= 1
        j -= 1
        ri = self.root(i)
        rj = self.root(j)
        if ri == rj:
            return
        else:
            if not self.r[ri] < self.r[rj]:
                ri, rj = rj, ri
            self.r[ri] += self.r[rj]
            self.r[rj] = ri
            return

    def max_size(self):
        return -min(self.r)

uf = UF()
for i in range(M):
    uf.union(*[int(x) for x in input().split(' ')])
print(uf.max_size())
        
        



Measured memory_bytes: 13468
s = input()

if s == "SUN" :
    print(7-0)
elif s == "MON":
    print(7-1)
elif s == "TUE":
    print(7-2)
elif s == "WED":
    print(7-3)
elif s == "THU":
    print(7-4)
elif s == "FRI":
    print(7-5)
elif s == "SAT":
    print(7-6)

Measured memory_bytes: 3060
#include<bits/stdc++.h>
using namespace std;
int main(){
  int a[5];
  int k;
  for(int i=0;i<3;i++)cin>>a[i];
  cin>>k;
  sort(a,a+3);
  cout<<a[0]+a[1]+(a[2]<<k)<<endl;
  return(0);
}


Measured memory_bytes: 256
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def I(): return int(sys.stdin.readline())


def LS(): return [list(x) for x in sys.stdin.readline().split()]


def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res


def IR(n):
    return [I() for i in range(n)]


def LIR(n):
    return [LI() for i in range(n)]


def SR(n):
    return [S() for i in range(n)]


def LSR(n):
    return [LS() for i in range(n)]


sys.setrecursionlimit(1000000)
mod = 1000000007


def main():
    # write codes here
    A = LIR(3)
    N = I()
    B = IR(N)

    bingo_card = [[0, 0, 0] for i in range(3)]

    for b in B:
        for i in range(3):
            for j in range(3):
                if A[i][j] == b:
                    bingo_card[i][j] = 1

    flag = 0

    for i in range(3):
        if sum(bingo_card[i]) == 3:
            flag = 1
            break

        if bingo_card[0][i] + bingo_card[1][i] + bingo_card[2][i] == 3:
            flag = 1
            break

    if sum([bingo_card[i][i] for i in range(3)]) == 3:
        flag = 1

    if sum([bingo_card[i][2 - i] for i in range(3)]) == 3:
        flag = 1

    if flag == 1:
        print("Yes")
    else:
        print("No")

    return 0


# Main
if __name__ == "__main__":
    main()


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

#define int long long int
#define fi first
#define so second
#define ps push_back
#define ld long double

signed main()
{
    int n,i,j;
    cin>>n;
    ld a[n];
    for(i=0;i<n;i++) cin>>a[i];
    ld dp[n+1][n+1];
    for(i=0;i<=n;i++) {for(j=0;j<=n;j++) dp[i][j]=0;}
    dp[0][0]=1;
    for(i=1;i<=n;i++) dp[0][i]=0;
    ld t[n],h[n];
    t[0]=1-a[0];
    h[0]=a[0];
    for(i=1;i<n;i++) {t[i]=t[i-1]*(1-a[i]);h[i]=h[i-1]*a[i];}
    for(i=1;i<=n;i++)
    {
        dp[i][0] = t[i-1];
        for(j=1;j<=n;j++)
        {
            if(j==i) dp[i][j]=h[i-1];
            else if(j>i) dp[i][j]=0;
            else dp[i][j] = ((1-a[i-1])*dp[i-1][j]) + (dp[i-1][j-1]*a[i-1]);
        }
    }
    ld sum=0;
    for(i=0;i<=n;i++) if(i>n-i) sum+=dp[n][i];
    cout<<setprecision(10)<<sum;
}


Measured memory_bytes: 141056
//int a = stoi(c); 文字列をintへ
//小文字から大文字
//transform(a.begin(), a.end(), a.begin(), ::toupper);
//数値計算 個数以外はdouble
//map 全探索
//auto begin = p.begin(), end = p.end();
//for (auto it = begin; it != end; it++) {}
//mapのキー：it->first mapのバリュー：it->second
//大文字判定 isupper(文字) 小文字判定 islower(文字)
//do{}while(next_permutation(ALL(配列)))
//小文字に対応する文字コード：S[i] - 'a'
//文字コード→小文字：(char)(数字+'a')
//グラフの距離:隣接行列で扱う
//bool型　初期値はTrue
//島渡りの問題：中間ノードに着目
//数が大きい時の比較はstring型で行う
//全て0になったか調べたい->0になるたびにcntする
//例外処理は最初にする
//x = p^m + q^n...の約数の個数:(n+1)*(m+1)....
//N!のどの素因数で何回割れるか
//⇔1~Nまでの数がそれぞれどの素因数で何回割り切れるかの和
//パズルの問題->一般化して全探索
//stack<ll> s;
//s.push(要素);s.top();s.pop();
//queue<ll> q;
//q.push(要素);q.front();q.pop();
//同じ作業繰り返す系の問題：収束先を見つける
//過半数：N/2.0で判定
//優先度付きキュー
//priority_queue<
//ll,
//vector<ll>
//> q;
#include <bits/stdc++.h>
#define rep(i,N) for(int i = 0; i < N;i++)
#define ALL(a) (a).begin(),(a).end()
#define ll long long int
using namespace std;

//円周率
const double PI = 3.14159265358979323846;
//割るやつ
const ll MOD = (pow(10, 9) + 7);

// K進数でのNの桁数
ll dig(ll N, ll K) {
	ll dig = 0;
	while (N) {
		dig++;
		N /= K;
	}
	return dig;
}
// a,bの最大公約数
ll gcd(ll a, ll b) {
	if (b == 0) return a;
	return gcd(b, a%b);
}

//a,bの最小公倍数
ll lcm(ll a, ll b) {
	ll g = gcd(a, b);
	return a / g * b;
}

//階乗計算
ll f(ll n) {
	if (n == 0 || n == 1) return 1;
	else return (n * f(n - 1));
}

//Nのd桁目の数
ll dignum(ll N, ll d) {
	ll x = pow(10, d);
	N %= x;
	ll y = pow(10, d - 1);
	N /= y;
	return N;
}

//Nをdで何回割れるか
ll divcnt(ll N, ll d) {
	ll ans = 0;
	while (1) {
		if (N%d == 0) {
			ans++;
			N /= d;
		}
		else break;
	}

	return ans;
}

//素数判定
bool prime(ll num) {
	if (num < 2) return false;
	else if (num == 2) return true;
	else if (num % 2 == 0) return false;
	double sqrtNum = sqrt(num);
	for (int i = 3; i <= sqrtNum; i += 2) {
		if (num % i == 0) return false;
	}
	return true;
}

//フィボナッチ数列
vector<ll> memo(pow(10, 6) + 1);
ll fibo(ll n) {
	if (n == 1) return 1;
	else if (n == 2) return 1;
	else if (memo[n] != 0) return memo[n];
	else return memo[n] = fibo(n - 1) + f(n - 2);
}

int main() {
	double A, B, H, M; cin >> A >> B >> H >> M;

	double th1 = 2 * PI * (M / 60.0);
	double th2 = 2 * PI * (H / 12.0) + (PI /6.0) * M/60.0;
	double th;

	th = min(abs(th1 - th2), 2 * PI - abs(th1 - th2));

	double ans = sqrt(A * A + B * B - 2 * A * B * cos(th));
	cout <<setprecision(20) << ans << endl;
}

Measured memory_bytes: 11032
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define pb push_back
#define pp pop_back
#define mp make_pair
#define ff first
#define ss second
#define maxn 1000000007
#define PI 3.14159265358979323846
#define MAX 1000007 
using namespace std; 

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); 
    //cout<<fixed<<setprecision(20);
    ll n;
    cin>>n;
    ll a[n];
    for (int i = 0; i < n; ++i)
    {
        cin>>a[i];
    }
    ll c=0;
    for (int i = 1; i < n-1; ++i)
    {
        if((a[i]>a[i-1] && a[i]<a[i+1]) || (a[i]<a[i-1] && a[i]>a[i+1]))
        {
            c++;
        }
    }
    cout<<c<<endl;
    return 0;
}

Measured memory_bytes: 256