akhauriyash/Code-Regression huggingface dataset:
a,b,k=map(int,input().split())
l=[]
for i in range(a,min(a+k,b+1)):
    l.append(i)
for i in range(max(a,b-k+1),b+1):
    l.append(i)


l=list(set(l))
l.sort()
for i in l:
    print(i)
    

Measured memory_bytes: 39408
N,M = map(int, input().split())
ab = [tuple(map(int, input().split())) for _ in range(M)]
ab.sort()
ans = 1
l, r = ab[0][0], ab[0][1]

for a,b in ab[1:]:
    if a < r:
        l = max(l,a)
        r = min(r,b)
    else:
        ans += 1
        l = a
        r = b 

print(ans)

Measured memory_bytes: 17400
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <string>
#include <iomanip>
using namespace std;
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define FOR(i,m,n) for(int (i)=(m);(i)<(n);(i)++)
typedef long long ll;
const int dx[4]={1,0,-1,0};
const int dy[4]={0,1,0,-1};

int main(){
    int x,y,z,k;
    cin >> x >> y >> z >> k;
    vector<ll> a(x),b(y),c(z);
    rep(i,x)cin >> a[i];
    rep(i,y)cin >> b[i];
    rep(i,z)cin >> c[i];

    sort(c.begin(),c.end());
    reverse(c.begin(),c.end());
    
    vector<ll> ab;
    ab.reserve(x*y);

    rep(i,x)rep(j,y)ab.push_back(a[i]+b[j]);
    
    sort(ab.begin(),ab.end());
    reverse(ab.begin(),ab.end());
    int lim = min(k,(int)ab.size());

    vector<ll> res;
    rep(i,lim){
        rep(j,z){
            res.push_back(ab[i]+c[j]);
        }
    }

    sort(res.begin(),res.end());
    reverse(res.begin(),res.end());

    rep(i,k)cout << res[i] << endl;

    return 0;
}

Measured memory_bytes: 42984
n = int(input())
a = list(map(int,input().split()))
ans=1
tmp = a[0]
l=0
for i in range(1,n):
    x = a[i]
    while tmp^x != tmp+x:
        tmp-=a[l]
        l+=1
    ans+=i-l+1
    tmp+=x
print(ans)

Measured memory_bytes: 23560
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
#include <bitset>
using namespace std;
#define INF 110000000000
#define MOD 1000000007
typedef long long ll;
typedef pair<ll,int> P;

int dp[11000];

int main(){
  int g=0,p=0,ans=0;
  string s;
  cin>>s;

  for(int i=0;i<(int)s.size();i++){
    if(g>p){
      if(s[i]=='g') ans++;
      p++;
    }else{
      g++;
      if(s[i]=='p') ans--;
    }
  }

  cout<<ans<<endl;
}


Measured memory_bytes: 512
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define df 0
#define max(x,y) ((x)>(y)?x:y)
#define D_abs(x) max(x,-x)
#define ceil(a,b) (((a)+(b)-1)/(b))

int ans[2][200010]={};
int len=0;
void closer(int* x,int* y,int d);
void decline(int* a,int d);

int main(){
  int k,x,y,s;
  scanf("%d%d%d",&k,&x,&y);
  int d=D_abs(x)+D_abs(y);
  if(df) printf("%d %d\n",d,k);
  if(d==k)s=1;
  if((k&1)==0){   ///step:even
    if(d&1) s=-1;
    else s=max(ceil(d,k),2);
  }else{          ///step:odd
    if(d<k)s=2;
    else s=ceil(d,k);
    if(df)printf("%d / %d = %d\n",d,k,ceil(d,k));
    s+=(d^s)&1;
  }
  printf("%d\n",s);
  if(s>0){
    ans[0][len]=x;
    ans[1][len++]=y;
  }
  while(s>2){
    closer(&x,&y,k);
    s--;
  }
  if(s==2){
    int f1=x>0?1:-1,f2=y>0?1:-1;
    x*=f1;y*=f2;
    if(x+y>k){
      int p=(2*k-x-y)/2;
      if(x>y){
	if(df)printf("x+y>d, x>y %d,%d\n",x,y);
	x=k-y;
	x-=p;
	y+=p;
      }
      else{
	if(df)printf("x+y>d, x<y %d,%d\n",x,y);
	y=k-x;
	y-=p;
	x+=p;
      }
    }
    else{
      int p=(x+y)/2;
      if(x>y){
	if(df)printf("x+y<d, x>y %d,%d\n",x,y);
	y=k-x;
	x-=p;
	y+=p;
      }
      else{
	if(df)printf("x+y<d, x<y %d,%d\n",x,y);
	x=k-y;
	y-=p;
	x+=p;
      }
    }
    x*=f1;y*=f2;
    ans[0][len]=x;
    ans[1][len++]=y;
    
  }
  int i;
  for(i=len-1;i>=0;i--){
    printf("%d %d\n",ans[0][i],ans[1][i]);
  }


  return 0;
}
void closer(int* x,int* y,int d){
  if(abs(*x)>abs(*y)) {
    decline(x,d);
    ans[0][len]=*x;
    ans[1][len++]=*y;
  }
  else {
    decline(y,d);
    ans[0][len]=*x;
    ans[1][len++]=*y;
  }
  
}

void decline(int* a,int d){
  int f=(0<(*a))?1:-1;
  *a=*a-f*d;
}


/// confirm df==0 ///


Measured memory_bytes: 3968
#define _USE_MATH_DEFINES

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <bitset>
using namespace std;

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef tuple<ll, ll, ll> tl3;



const int BIG_NUM = 1e9;
const ll INF = 1000000000000000000;
const ll MOD = 1e9 + 7;
//const ll MOD = 998244353;



int main() {
	int r;
	cin >> r;
	cout << 3 * r * r << endl;
}


Measured memory_bytes: 3636
#include<bits/stdc++.h>
#define LL long long
#define pb push_back
#define SZ(x) ((int)x.size()-1)
#define ms(a,b) memset(a,b,sizeof a)
#define F(i,a,b) for (int i=(a);i<=(b);++i)
#define DF(i,a,b) for (int i=(a);i>=(b);--i)
#pragma GCC optimize(2)
using namespace std;
inline int read(){
	char ch=getchar(); int w=1,c=0;
	for(;!isdigit(ch);ch=getchar()) if (ch=='-') w=-1;
	for(;isdigit(ch);ch=getchar()) c=(c<<1)+(c<<3)+(ch^48);
	return w*c;
}
const int M=(1<<18)+10;
int t[25],tot,tv[M],tw[M],v[M],w[M];
int mx[(1<<9)+10][100050],ini[M],mxl[M]; 
#define lowbit(x) (x&-x)
bool cmp(int x,int y){
	return tw[x]<tw[y]; 
}
void dfs(int x,int fa,int lim){
	if (x>=512) return ; mxl[x]=lim;
	DF(i,lim,0)mx[x][i]=mx[fa][i]; 
	DF(i,lim,w[x])mx[x][i]=max(mx[x][i],mx[x][i-w[x]]+v[x]);
	dfs((x<<1),x,min(100000,lim+w[x<<1]));
	dfs((x<<1|1),x,min(100000,lim+w[x<<1|1]));
	F(i,1,lim) mx[x][i]=max(mx[x][i],mx[x][i-1]);
} 
int main(){
//	freopen("1.in","r",stdin);
//	freopen("1.out","w",stdout);
	int n=read();
	F(i,1,n) v[i]=read(),w[i]=read();
	dfs(1,0,w[1]);
	int Q=read();
	while (Q--){
		int x=read(),l=read(); tot=0;
		int op=0,ans=0;
		for (;x>=512;x>>=1) t[++tot]=x,ini[(1<<op)]=x,op+=(x>=512);
//		cout<<op<<"   gg\n";
		F(i,0,(1<<op)-1){
			int pos=lowbit(i); 
			tv[i]=tv[i-pos]+v[ini[pos]];
			tw[i]=tw[i-pos]+w[ini[pos]];
			if (tw[i]<=l){
				ans=max(ans,tv[i]+mx[x][min(l-tw[i],mxl[x])]);
			}
		} 
		assert(!tv[0] && !tw[0]);
		cout<<ans<<"\n";
	}
	return 0;
}




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

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)   FOR(i,0,n)
#define ALL(a)     (a).begin(),(a).end()
#define RALL(a)     (a).rbegin(),(a).rend()
#define PRINT(a)   cout << (a) << endl

#define pb push_back
#define eb emplace_back
#define Fi first
#define Se second

#define debug(x) cerr << x << " " << "(L:" << __LINE__ << ")" << '\n';

using ll = long long int;
using P = pair<int,int>;
using vi = vector<int>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
using pii = pair<int, int>;

template <typename T> using PQ = priority_queue<T>;
template <typename T> using minPQ = priority_queue<T, vector<T>, greater<T>>;

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; }

const int INF = 1001001001;
const ll LINF = 1001001001001001001ll;
const int MOD = 1e9 + 7;

ll dp[3001][3001][4];

int main(){
  int r,c,k;
  cin >> r >> c >> k;
  
  map<P, int> mp;

  REP(i,k){
    int rr,cc,v;
    cin >> rr >> cc >> v;
    mp[make_pair(rr,cc)]=v;
  }

  FOR(i,1,r+1)FOR(j,1,c+1){
    if(mp.end() != mp.find(make_pair(i,j))){
      ll v = mp[make_pair(i,j)];
      FOR(k,1,4){
        dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k-1]+v);        
      }
      REP(l,4){
        dp[i][j][1] = max(dp[i][j][1], dp[i-1][j][l]+v);        
      }
      REP(k,4){
        dp[i][j][k] = max(dp[i][j][k], max(dp[i-1][j][k], dp[i][j-1][k]));        
      }
    }else{
      REP(k,4){
        dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k]);        
        dp[i][j][0] = max(dp[i][j][0], dp[i-1][j][k]);        
      }
    }
  }

  ll ans = 0;
  REP(i,4)chmax(ans, dp[r][c][i]);

  // REP(i,r+1)REP(j,c+1)REP(k,4){
  //   cout << dp[i][j][k] << endl;
  // }

  cout << ans << endl;

}



Measured memory_bytes: 297424
//#pragma comment(linker, "/stack:200000000")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
#include<bits/extc++.h>
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define pb push_back
using namespace std;
//using namespace __gnu_pbds;
using ll = long long;
using vi = vector<ll>;
using vvi = vector<vector<ll>>;
const ll mod = 1e9 + 7;
//using oset = tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	ll n;
	string s;
	cin >> s;
	n = s.size()+1;
	ll m = 0;
	vi x(n+1);
	for(int i = 0; i < s.size(); i++) {
		if(s[i]=='<') {
			x[i+1] = max(x[i+1], x[i]+1);
		}
	}
	ll sm = 0;
	for(int i = s.size(); i--;) {
		if(s[i]=='>') {
			x[i] = max(x[i+1]+1, x[i]);
		}
	}
	for(int i =0; i < n; i++)
	sm += x[i];
	cout << sm << '\n';
}


Measured memory_bytes: 4764
#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define endl '\n'
int M = 1e9 + 7;
int32_t main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int n, k;
  cin >> n >> k;
  int a[n + 1];
  for (int i = 1; i <= n; ++i)
  {
    cin >> a[i];
  }
  vector<int> v;
  int top = 1;
  bool vis[n + 1] = {0};
  while (vis[a[top]] == 0)
  {
    vis[a[top]] = 1;
    v.push_back(a[top]);
    int next = a[top];
    top = next;
  }
  vector<int> cycle;
  for (int i = 0; i < v.size(); ++i)
  {
    if (k)
    {
      if (v[i] != a[top])
        k--;
      else
      {
        int j = i;
        while (j < v.size())
        {
          cycle.push_back(v[j]);
          j++;
        }
        break;
      }
    }
    else
    {
      cout << v[i - 1];
      exit(0);
    }
  }
  int x = (k % cycle.size() - 1 + cycle.size()) % cycle.size();
  cout << cycle[x];


}

Measured memory_bytes: 9312
#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <cfloat>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <memory>
#include <string>

#include <algorithm>
#include <complex>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <bitset>

using namespace std;

#ifdef _MSC_VER
#define __typeof__ decltype
#define strtok_r strtok_s
#endif

#define ITER(c)             __typeof__((c).begin())
#define FOREACH(it, c)      for (ITER(c) it=(c).begin(); it != (c).end(); ++it)
#define RITER(c)            __typeof__((c).rbegin())
#define RFOREACH(it, c)     for (RITER(c) it=(c).rbegin(); it != (c).rend(); ++it)
#define REP(i, n)           REPEAT(i, 0, n)
#define RREP(i, n)          RREPEAT(i, 0, n)
#define REPEAT(i, k, n)     for(int i = (k); i < ((k)+(n)); ++i)
#define RREPEAT(i, k, n)    for(int i = (k)+(n)-1; i >= (k); --i)
#define FROMTO(i,f,t)       for(int i = f; i < t; i++)
#define ALL(c)              (c).begin(), (c).end()
#define LLPOW(p1,p2)        ((ll)pow((double)(p1), (int)p2))
#define ESIZEOF(A)          (sizeof(A)/sizeof((A)[0]))
#define CIN_NO_SYNC         do { cin.tie(0); ios_base::sync_with_stdio(false); } while(0)
#define GETSTR(p)           fgets((p), sizeof(p), stdin)
#define CHOMP(p)            do{ char *_q = (p) + strlen(p)-1; if(*_q == '\n' || *_q == '\r') *_q = 0; } while(0)
#define FILL(m,v)           memset(m, v, sizeof(m))
#define mp                  make_pair
#define pb                  push_back
template<class _T> _T MAX(_T p1,_T p2){return (p1>p2)?p1:p2;} 
template<class _T> _T MIN(_T p1,_T p2){return (p1<p2)?p1:p2;} 
template <class _Tv> inline string join(const _Tv &v,string sep=" "){
    ostringstream s;FOREACH(it,v){if(it!=v.begin())s<<sep;s<<*it;};return s.str();
}

typedef long long ll;
typedef unsigned long long ull;
typedef double D;
typedef complex<D> P;
typedef vector<int> VI;
typedef vector<VI> VVI;
#define X real()
#define Y imag()
#define EPS (1e-9)
#define DEQ(p1,p2) (abs((p1)-(p2)) < EPS)

#ifdef _DEBUG
template<class _Tv> inline void _prfe(const char *_n,const _Tv _c,bool _p=false){
    ITER(_c) _it=_c.begin();
    if(_p){cout<<_n<<" = ["<<endl;for(;_it!=_c.end();++_it)cout<<"    "<<*_it<<endl;cout<<"]"<<endl; }
    else{cout<<_n<<" = [ "<<*_it++;for(;_it!=_c.end();++_it)cout<<", "<<*_it;cout<<" ]"<<endl; }
}
ostream &operator<<(ostream &os, const pair<int,int> &p){return(os<<"("<<p.first<<","<<p.second<<")");}
#define pf printf
#define pr(n) do{cout<<#n" = "<<(n)<<endl;}while(0)
#define prfe(n) _prfe(#n, n)
#define prfep(n) _prfe(#n, n, true)
#define dbgchk(n) do{if(n)throw;}while(0)
#else
#define pf(...) /* */
#define pr(...) /* */
#define prfe(...) /* */
#define prfep(...) /* */
#define dbgchk(...) /* */
#endif

int main(){
    int n;
    while(cin >> n && n){
        int t = 32, k[30];
        REP(i,n) cin >> k[i];
        for(int i = 0; t > 0;i++){
            cout << (t -= (t-1)%5) << endl;
            cout << (t -= MIN(k[i%n],t)) << endl;
        }
    }
    return 0;
}

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

int	main() {
	ll N, K, X, Y;
	cin >>N >>K >>X >>Y;
	if (N<=K)
		cout <<N*X <<endl;
	else
		cout <<K*X+Y*(N-K) <<endl;
	return 0;
}



Measured memory_bytes: 256
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <queue>
#include <math.h>
using namespace std;


int main()
{
	int A, B, C, D;

	cin >> A >> B >> C >> D;

	while(1){
		C -= B;
		if(C <= 0){
			cout << "Yes";
			break;
		}

		A -= D;
		if(A <= 0){
			cout << "No";
			break;
		}

	}

	 
	return 0;
	
}

Measured memory_bytes: 3624
def bubbleSort(A,N):
    flag = 1
    count = 0
    while flag:
        flag = 0
        for j in range(N-1,0,-1):
            Aj = int(A[j][1])
            Aj_1 = int(A[j-1][1])
            if Aj < Aj_1:
                A[j],A[j-1] = A[j-1],A[j]
                flag = 1
                count += 1
    return A[:]

def selectionSort(A,N):
    count=0
    for i in range(N):
        minj = i
        for j in range(i,N):
            Aj = int(A[j][1])
            Aminj = int(A[minj][1])
            if Aj < Aminj:
                minj = j
        A[i],A[minj] = A[minj],A[i]
        if i != minj:
            count +=1
    return A[:]

N = int(input())
#table = input().split()
#for c in range(input().split()):
#    l.append(int(c[1],c[0]))
table = [x for x in input().split(' ')]
t = table[:]
u = table[:]
#B = A.copy

A=bubbleSort(t,N)
print('{0}'.format(' '.join(map(str,A))))
print('Stable')
B=selectionSort(u,N)
print('{0}'.format(' '.join(map(str,B))))
if A == B:
    print('Stable')
else:
    print('Not stable')



Measured memory_bytes: 5616
from collections import deque


def bellman_ford(start: int, graph: list) -> list:
    """bellman-ford法: 始点startから各頂点への最短距離を求める(負辺OK)
    計算量: O(|E||V|)
    """
    INF = float("inf")
    n = len(graph)
    dist = [-INF] * n
    dist[start] = 0
    if n == 1:
        return False, [0]
    for _ in range(n - 1):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if not (visited[nxt_v] and visited2[nxt_v]):
                    continue
                if dist[nxt_v] < dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            break
    else:
        return True, dist
    return False, dist

def bellman_ford2(start: int, graph: list) -> list:
    """bellman-ford法: 始点startから各頂点への最短距離を求める(負辺OK)
    計算量: O(|E||V|)
    """
    INF = float("inf")
    n = len(graph)
    dist = [-INF] * n
    dist[start] = 0
    if n == 1:
        return False, [0]
    for _ in range(n + 100):
        update = False
        for v, edge in enumerate(graph):
            for nxt_v, cost in edge:
                if not (visited[nxt_v] and visited2[nxt_v]):
                    continue
                if dist[nxt_v] < dist[v] + cost:
                    dist[nxt_v] = dist[v] + cost
                    update = True
        if not update:
            break
    else:
        return True, dist
    return False, dist

n, m, p = map(int, input().split())
info = [list(map(int, input().split())) for i in range(m)]

graph = [[] for i in range(n)]
rev_graph = [[] for i in range(n)]
for a, b, cost in info:
    a -= 1
    b -= 1
    cost -= p
    graph[a].append((b, cost))
    rev_graph[b].append((a, cost))

visited = [False] * n
def dfs():
    q = deque([0])
    visited[0] = True
    while q:
        v = q.pop()
        for nxt_v, _ in graph[v]:
            if visited[nxt_v]:
                continue
            visited[nxt_v] = True
            q.append(nxt_v)
dfs()

visited2 = [False] * n
def dfs2():
    q = deque([n - 1])
    visited2[n - 1] = True
    while q:
        v = q.pop()
        for nxt_v, _ in rev_graph[v]:
            if visited2[nxt_v]:
                continue
            visited2[nxt_v] = True
            q.append(nxt_v)
dfs2()

#print(visited)
#print(visited2)

boolian, dist = bellman_ford(0, graph)
boolian, dist2 = bellman_ford2(0, graph)
if not boolian:
    print(max(dist[-1], 0))
else:
    for i in range(n):
        if dist[i] < dist2[i]:
            print(-1)
            exit()
    print(dist2[-1])
        

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

typedef long long ll;
#define REP(i,n) for(int i=0,_n=(int)(n);i<_n;++i)
#define ALL(v) (v).begin(),(v).end()
#define CLR(t,v) memset(t,(v),sizeof(t))
template<class T1,class T2>ostream& operator<<(ostream& os,const pair<T1,T2>&a){return os<<"("<<a.first<<","<<a.second<< ")";}
template<class T>void pv(T a,T b){for(T i=a;i!=b;++i)cout<<(*i)<<" ";cout<<endl;}
template<class T>void chmin(T&a,const T&b){if(a>b)a=b;}
template<class T>void chmax(T&a,const T&b){if(a<b)a=b;}



ll range(ll L) {
  switch (L & 3) {
  case 0: return L;
  case 1: return 1;
  case 2: return L + 1;
  case 3: return 0;
  }
  return 0;
}

int main2() {
  ll A, B; cin >> A >> B;
  ll ans = range(B) ^ range(A-1);
  cout << ans << endl;
  return 0;
}

int main() {
  for (;!cin.eof();cin>>ws)
    main2();
  return 0;
}


Measured memory_bytes: 256
#include <iostream>
using namespace std;
#define MAXSIZE 10

int main(){
    int n, p[MAXSIZE], sum = 0, M = 0;
    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> p[i];
        M = (p[i] > M)? p[i] : M;
        sum += p[i];
    }
    sum -= M / 2;
    cout << sum;
    cout << endl;
    return 0;
}

Measured memory_bytes: 256
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const A = parseInt(arg[0].split(" ")[0]);
    let B = parseInt(arg[0].split(" ")[1]);
    let C = parseInt(arg[0].split(" ")[2]);
    
    let answer = C;
    
    for(let i=B; i<A; i++) {
        if(C === 0) {
            console.log(C);
            return;
        }
        
        C--;
    }
    
    console.log(C)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


Measured memory_bytes: 7372
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int,int>;
int main() {
    int k; cin >> k;
    map<int, int> mp;
    int mod = 7;
    int base = 70;
    for (int i=1;;i++) {
        mod %= k;
        if (mod == 0) {
            cout << i << endl;
            break;
        }
        if (mp[mod] == 1) {
            cout << -1 << endl;
            break;
        }
        mp[mod] = 1;
        mod += base;
        base *= 10;
        base %= k;
    }
}


Measured memory_bytes: 50356
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <queue>
#include <set>
#include <numeric>
#include <cmath>

using namespace std;

typedef long long int ll;

#define all(x) x.begin(),x.end()

const ll mod = 1e9+7;
const ll INF = 1e9;
const ll MAXN = 1e9;

int main()
{
	int n,m;
	cin >> n >> m;

	cout << pow(2,m)*(1900*m+100*(n-m)) << endl;


	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i = 0; i < (int)(n); ++i)
#define DEBUG(x) cerr << #x << " = " << x << endl
const int INF = (int)1e9;
int main() {
  int N, M; cin >> N >> M;
  vector<vector<int>> G(N);
  REP(i,M) {
    int a, b; cin >> a >> b;
    a--; b--;
    G[a].push_back(b);
    G[b].push_back(a);
  }
  int Q; cin >> Q;
  vector<int> V(Q), D(Q), C(Q);
  REP(i,Q) {
    cin >> V[i] >> D[i] >> C[i];
    V[i]--;
  }
  static pair<int, int> d[11][100000];
  REP(i,11) REP(j,N) {
    d[i][j] = make_pair(0, 0);
  }
  REP(i,Q) {
    d[D[i]][V[i]] = make_pair(i + 1, C[i]);
  }
  for(int i = 10; i > 0; i--) {
    REP(j,N) {
      d[i-1][j] = max(d[i-1][j], d[i][j]);
      REP(k,G[j].size()) {
        d[i-1][G[j][k]] = max(d[i-1][G[j][k]], d[i][j]);
      }
    }
  }
  REP(i,N) {
    cout << d[0][i].second << endl;
  }
}


Measured memory_bytes: 16248
use std::str::FromStr;
use std::collections::HashMap;

fn get_one<T : FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    return s.trim().parse().ok().unwrap();
}

fn get_vec<T : FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    return s.trim().split_whitespace().map(|e| e.parse().ok().unwrap()).collect();
}

fn get_vec_by_lines<T : FromStr>(n : usize) -> Vec<T> {
    let mut v : Vec<T> = Vec::new();
    for _i in 0..n {
        let x : T = get_one();
        v.push(x);
    }
    return v;
}

fn main() {
    let n : usize = get_one();
    let mut v : Vec<i32> = get_vec_by_lines(n);
    v.sort();
    let mut ans = v.iter().sum();
    for i in 0..n {
        if ans % 10 != 0 {
            break;
        }
        if v[i] % 10 != 0 {
            ans -= v[i];
            break;
        }
    }
    println!("{}", if ans % 10 == 0 {0} else {ans} );
}


Measured memory_bytes: 4352
#include<bits/stdc++.h>
using namespace std;
int main()
{
	std::ios::sync_with_stdio(false);
	int a[4];
	for(int i=1;i<=3;i++) cin>>a[i];
	sort(a+1,a+4);
	if(a[1]==5&&a[2]==5&&a[3]==7) cout<<"YES"<<endl;
	else cout<<"NO"<<endl; 
	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define leading zero str.erase(0, min(str.find_first_not_of('0'), str.size()-1));
using namespace __gnu_pbds;
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
string text="abcdefghijklmnopqrstuvwxyz";
const int maxn=1e6+7;
//        .--------------.
//        | Try First One|
//        '--------------'
//                |     .--------------.
//                |     |              |
//                V     V              |
//              .--------------.       |
//              |      AC.     |<---.  |
//              '--------------'    |  |
//              (True)|  |(False)   |  |
//           .--------'  |          |  |
//           |           V          |  |
//           |  .--------------.    |  |
//           |  |   Try Again  |----'  |
//           |  '--------------'       |
//           |                         |
//           |  .--------------.       |
//           '->| Try Next One |-------'
//              '--------------'
bool ugly[100005];
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n;
    string s;
    cin>>n>>s;
    int ans=0;
    for(int i=0;i+1<n;i++){
        if(s[i]==s[i+1])s[i]='#';
    }
    for(auto x: s){
        if(isalpha(x))ans++;
    }
    cout<<ans<<endl;
}


Measured memory_bytes: 3760
char a[100][20],b[100][20];
n,m,s,i,j,t;
main(){
	scanf("%d\n",&n);
	for(i=0;i<n;i++)gets(a[i]);
	scanf("%d\n",&m);
	for(i=0;i<m;i++)gets(b[i]);
	for(i=0;i<n;i++)
	{
		t=0;
		for(j=0;j<n;j++)t+=!strcmp(a[i],a[j]);
		for(j=0;j<m;j++)t-=!strcmp(a[i],b[j]);
		s=s<t?t:s;
	}
	printf("%d",s);
}


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

int main() {
  using namespace std;
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
  int N;
  cin >> N;
  vector<deque<int>> graph(N);
  for (int i = 0; i < N - 1; ++i) {
    int a, b;
    cin >> a >> b, --a, --b;
    graph[a].push_back(b);
    graph[b].push_back(a);
  }
  int len = 0;
  vector<pair<int, int>> memo(N);
  auto dfs = [](auto&& f) {
    return [=](auto&&... args) {
      return f(f, std::forward<decltype(args)>(args)...);
    };
  }([&](auto&& self, int cur, int prv, int depth) -> int {
    int size = 0;
    if (cur == N - 1) len = depth;
    for (int nxt : graph[cur]) {
      if (nxt == prv) continue;
      size += self(self, nxt, cur, depth + 1);
    }
    memo[cur] = make_pair(prv, size + 1);
    return memo[cur].second;
  });
  dfs(0, -1, 0);
  int t = N - 1;
  for (int i = 0; i < (len - 1) / 2; ++i) t = memo[t].first;
  bool ans = memo[0].second - memo[t].second > memo[t].second;
  cout << (ans ? "Fennec" : "Snuke") << endl;
}


Measured memory_bytes: 73984
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cmath>
#include <string>
#include <queue>
#include <stack>
#include <sstream>
#include <cstdlib>
using namespace std;
int main(){
	string str,sub;
	int m,h[101];
	while(cin>>str){
		if(str=="-") break;
		cin>>m;
		for(int i=0;i<m;i++){
			cin>>h[i];
			sub=str.substr(0,h[i]);
			str=str+sub;
			str.erase(str.begin(),str.begin()+h[i]);
		}
		cout<<str<<endl;
	}
	return 0;
}


Measured memory_bytes: 3156
#define _GLIBCXX_DEBUG
#include "bits/stdc++.h"
using namespace std;
using Graph = vector<vector<int>>;
 
typedef long long ll;
typedef long double ld;
 
 
#define int long long
#define rep(i, n) for(long long i = 0; i < (n); i++)
#define sqrt(d) pow((long double) (d), 0.50)
 
const ll INF = 2e9;
const ll large_P = 1e9 + 7;
 
 
 
 
 
signed main() {
	int R; cin >> R;
	ld r = (ld)R;
 
	ld pi = 3.14159265358979;
	cout << 2.0 * r * pi << endl;
}

Measured memory_bytes: 3812
#include <bits/stdc++.h>
#include <math.h>
#define _GLIBCXX_DEBUG
#define _LIBCPP_DEBUG 0

using namespace std;
#define ll long long
#define rep(i,n) for (int i = 0; i < n; i++)
#define MOD (1000000007)
#define vi vector<int>
#define vvi vector<vi>
#define pii pair<int, int>
#define pb push_back
#define mp make_pair
#define all(a) (a).begin(),(a).end()

template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }

int gcd(int a, int b) {
    if (b == 0) return a;
    else return gcd(b, a % b);
}

const ll INF = 1LL << 60;

int main(){
  int n,k; cin >> n >> k;
  vector<char> d(k); rep(i, k) cin >> d[i];

  bool ok = false;
  int i;
  for (i = n; ok == false; i++) {
    string s = to_string(i);
    ok = true;
    rep(j, s.size()){
      for(auto c : d) if(s[j] == c) ok = false;
    }
  }
  std::cout << i-1 << '\n';
}


Measured memory_bytes: 256
import java.util.Scanner;

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

        String str = sc.nextLine();

        if (str.charAt(2) == str.charAt(3) && str.charAt(4) == str.charAt(5)) {
            System.out.println("Yes");
        }

        else {
            System.out.println("No");
        }
    }
}


Measured memory_bytes: 24148
#include<bits/stdc++.h>
#define ll long long int
#define vll vector<pair<ll, ll> >
#define vl vector<ll>
#define vi vector<int>
#define vii vector<pair<int, int> >
const ll mod = 1e9 + 7;
const ll inf = LLONG_MAX;
using namespace std;

ll power_mod(ll x, ll y, ll p)
{
	ll ans = 1;
	x = x%p;
	if(x==0)
	return p;

	while(y>0)
	{
		if(y&1)
		{
			ans = (ans*x)%p;
		}
		y = y>>1;
		x = (x*x)%p;
	}
	return ans;
} 

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	int t;
	ll n,i,j,k;
	cin>>n;
	if(n%2==1)
	{
	    cout<<0;
	}
	else
	{
	    ll sum = 0;
	    ll temp = 10;
	    while(true)
	    {
	        if(temp>n)
	        break;
	        
	        sum+=(n/temp);
	        temp*=5;
	    }
	    cout<<sum;
	}
	return 0;
}


Measured memory_bytes: 3596
#include <bits/stdc++.h>
const int INF = 1e9;
const int MOD = 1e9+7;
using LL = long long;
const LL LINF = 1e18;
using namespace std;
#define COUT(v) cout<<(v)<<endl
#define CIN(n)  int(n);cin >> (n)
#define LCIN(n) LL(n);cin >> (n)
#define SCIN(n) string(n);cin >> (n)
#define YES(n) cout<<((n)? "YES" : "NO")<<endl
#define Yes(n) cout<<((n)? "Yes" : "No")<<endl
#define POSSIBLE(n) cout << ((n) ? "POSSIBLE" : "IMPOSSIBLE"  ) << endl
#define Possible(n) cout << ((n) ? "Possible" : "Impossible"  ) <<endl

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) for(int i=0;i<(n);++i)
#define REPR(i,n) for(int i=n;i>=0;i--)

#define FOREACH(x,a) for(auto& (x) : (a) )

#define ALL(obj) (obj).begin(),(obj).end()

#define P pair<LL,LL>
#define I vector<int>
#define S set<int>
#define pb(v) push_back(v)
#define V vector
#define rt return
#define rmsame(a) sort(ALL(a)),a.erase(unique(ALL(a)), a.end())

typedef string::const_iterator State;
class PalseError {};
class Edge{
public:
    LL from,to,value;
    Edge(LL a,LL b,LL c){
        from = a;
        to = b;
        value = c;
    }
    Edge(LL a,LL b){
        from = a;
        to = b;
    }
};

int main(){
    CIN(A);CIN(B);
    COUT((A+B)%24);
    return 0;
}


Measured memory_bytes: 256
if __name__ == "__main__":
    N, A = map(int, input().split())
    x = [i-A for i in map(int, input().split())]
    X = max(x + [A])
    dp = [[0] * (2*N*X + 1) for _ in range(N+1)]
    for row in range(N+1):
        for column in range(2*N*X):
            if row == 0 and column == N*X:
                dp[row][column] = 1
            elif row >=1 and (column - x[row-1] < 0 or column - x[row-1] > 2*N*X):
                    dp[row][column] = dp[row-1][column]
            elif row >=1 and 0 <= column - x[row-1] <= 2*N*X:
                dp[row][column] = dp[row-1][column] + dp[row-1][column-x[row-1]]
            else:
                dp[row][column] = 0
    print(dp[N][N*X]-1)


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

long long gcd(long long a, long long b){
	long long temp;
	if(a<b){
		temp=b;
		b=a;
		a=temp;
	}
	if(b==0)return a;
	while(a%b!=0){
		temp=a%b;
		a=b;
		b=temp;
	}
	return b;	
}

using namespace std;

int main(){
	int n;
	cin >> n;
	vector<long long> vec(n,0), Lvec(n+2,0),Rvec(n+2,0),ans(n+1,0);
	for(int i=0;i<n;i++)cin >> vec[i];
	
	for(int i=1;i<n;i++){
		Lvec[i]=gcd(Lvec[i-1],vec[i-1]);
		Rvec[n-i-1]=gcd(Rvec[n-i],vec[n-i]);
	}
	for(int i=0;i<n;i++)ans[i]=gcd(Lvec[i],Rvec[i]);
	sort(ans.rbegin(),ans.rend());

	cout << ans[0];
	}

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

#define ll long long
#define Fi first
#define Se second
#define Pb push_back
#define vi vector<int>
#define vvi vector<vector<int>>
#define vvp vector<vector<pair<int,int>>>

const int INF = 1e9;
const int MOD = 1e9+7;

#define all(v) v.begin(),v.end()
#define output_s(a) printf("%s\n",(a).c_str())

#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define Rep(i,n,m) for(int i=(int)(n);i<(int)(m);i++)
#define RepS(i,n,m) for(int i=(int)(n);i<=(int)(m);i++)
#define RRepS(i,n,m) for(int i=(int)(n);i>=(int)(m);i++)
#define RepA(x) for(auto &item:(x))

void CINT(){}
template <class Head,class... Tail>
void CINT(Head&& head,Tail&&... tail){
    cin>>head;
    CINT(move(tail)...);
}    
#define CIN(...) int __VA_ARGS__;CINT(__VA_ARGS__)
#define LCIN(...) ll __VA_ARGS__;CINT(__VA_ARGS__)
#define SCIN(...) string __VA_ARGS__;CINT(__VA_ARGS__)

template<typename TypeInt> //最大公約数
TypeInt GCD(TypeInt a,TypeInt b){
    if(a%b==0) return b;
    else return GCD(b,a%b);
}
template<typename TypeInt> //最小公倍数
TypeInt LCM(TypeInt a,TypeInt b){
    return a*b/GCD(a,b);
}

//library----------------------------------------------


signed main(){
    CIN(N);SCIN(s);
    const char z = 'A';
    if(N==0){
        output_s(s);
    }else{
        rep(i,s.size()){
            if(s[i]!='Z'){
                if(s[i]+N>90) printf("%c",z+(s[i]+N-90)-1);
                else printf("%c",s[i]+N);
            }
            else {
                printf("%c",z+(N-1));
            }
        }
        printf("\n");
    }
    
    return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#define pb push_back
#define REP(i, n) for (signed long long i = 0; i < (n); i++)
#define MOD 1000000007
#define bitcnt(a) (ll) __builtin_popcount((a))
using namespace std;
typedef long long ll;

int main() {
  ll a, b, c, k;
  cin >> a >> b >> c >> k;
  cout << a + b + c + pow(2, k) * max({a, b, c}) - max({a, b, c}) << endl;
}


Measured memory_bytes: 512
#include<bits/stdc++.h>
#pragma GCC optimize(2)
#define ll long long
#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,n,a) for(int i=n;i>=a;i--)
#define endl '\n'
#define eps 0.000000001
#define pb push_back
#define mem(a,b) memset(a,b,sizeof(a))
#define IO ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
const int INF=0x3f3f3f3f;
const ll inf=0x3f3f3f3f3f3f3f3f;
const int mod=1e9+7;
const int maxn=1e5+5;
int d[maxn];
int main(){
	string s,t;cin>>s>>t;
	int lens=s.length(),len=t.length();
	s=" "+s;t=" "+t;
	for(int i=1;i<=lens-len+1;i++){
		for(int j=1;j<=len;j++){
			if(s[j+i-1]!=t[j]) d[i]++;	
		}
	}
	int minn=INF;
	for(int i=1;i<=lens-len+1;i++){
		minn=min(minn,d[i]);
	}
	cout<<minn<<endl;
}


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

using namespace std;

int main(){
  long long  n,m;
  cin >> n >> m;
  vector<pair<long,long>> c(n);
  for(int i=0;i<n;i++){
    cin >> c[i].first >> c[i].second;
  }
  sort(c.begin(),c.end());
  long number=m;
  long cost=0;
  for(int i=0;i<n;i++){
    if(number-c[i].second>=0){
      number-=c[i].second;
      cost+=c[i].first*c[i].second;
    }
    else{
      cost+=c[i].first*number;
      break;
    }
  }
  cout << setprecision(20);
  cout << cost << endl;
}


Measured memory_bytes: 1792
#include<bits/stdc++.h>
using namespace std;
int main(){
  double N,D,a,b;
  cin>>N>>D;
  int count =0;
  for(int i=0;i<N;i++){
    cin >> a >> b;
    if(sqrt(a*a+b*b)<=D)count++;
  }
  cout <<count<<endl;
}

Measured memory_bytes: 3808
#include <stdio.h>

int main() {
	int a, b, c, d, e, k;
	scanf("%d %d %d %d %d %d", &a, &b, &c, &d, &e, &k);
	if (e - a > k)
		printf(":(\n");
	else
		printf("Yay!\n");
	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }

int n;
const long long INF = 1e9;
vector<long long> nowdp(100100, -1);

bool isOK(int index, int key) {
    if(nowdp.at(index) < key) return true;
    else return false;
}

int binary_search(int key) {
    int ng = -1;
    int ok = n+1;

    while(abs(ok-ng) > 1) {
        int mid = (ok+ng) / 2;
        if(isOK(mid, key)) ok = mid;
        else ng = mid;
    }
    return ok;
}


int main() {
    cin >> n;
    vector<int> a(n, 0);
    for(int i = 0; i < n; ++i) cin >> a.at(i);

    int now = 0;
    for(int i = 0; i < n; ++i) {
        int check = a.at(i);
        int chno = binary_search(check);
        if(nowdp.at(chno) == -1) now++;
        nowdp.at(chno) = check;
    }
    cout << now << endl;
}

Measured memory_bytes: 1408
import java.util.*;
public class Main {
	final int INF = 1 << 24;
	final int MAXDIS = 100000;
	
	private void doit(){
		Scanner sc = new Scanner(System.in);
		while(true){
			int n = sc.nextInt();
			int m = sc.nextInt();
			int c = sc.nextInt();
			int s = sc.nextInt();
			int g = sc.nextInt();
			if((n|m|c|s|g) == 0) break;
			s--;
			g--;
			int [][] mlist = new int[m][4];
			int [][][] dispass = new int [c][n][n];
			for(int i=0; i < c;i++){
				for(int j = 0; j < n; j++){
					Arrays.fill(dispass[i][j], INF);
					dispass[i][j][j] = 0;
				}
			}
			for(int i=0; i < m;i++){
				int from = sc.nextInt() -1;
				int to = sc.nextInt() - 1;
				int dis = sc.nextInt();
				int nowc = sc.nextInt() -1;
				mlist[i][0] = from;
				mlist[i][1] = to;
				mlist[i][2] = dis;
				mlist[i][3] = nowc;
				if(dispass[nowc][from][to] > dis){
					dispass[nowc][from][to] = dis;
					dispass[nowc][to][from] = dis;
				}
			}
			for(int cind = 0; cind < c; cind++){
				for(int j = 0; j < n; j++){
					for(int i = 0; i < n ; i++){
						for(int k = 0; k < n; k++){
							dispass[cind][i][k] = Math.min(dispass[cind][i][k], 
									dispass[cind][i][j] + dispass[cind][j][k]);
						}
					}
				}
			}
			
			int [] plist = new int[c];
			for(int i=0; i < c; i++){
				plist[i] = sc.nextInt();
			}
			ArrayList<ArrayList<Integer>> qlist = new ArrayList<ArrayList<Integer>>();
			ArrayList<ArrayList<Integer>> rlist = new ArrayList<ArrayList<Integer>>();
			for(int i=0; i < c; i++){
				qlist.add(new ArrayList<Integer>());
				qlist.get(i).add(0);
				rlist.add(new ArrayList<Integer>());
				for(int j = 0; j < plist[i] - 1; j++){
					qlist.get(i).add(sc.nextInt());
				}
				qlist.get(i).add(MAXDIS);
				for(int j = 0; j < plist[i]; j++){
					rlist.get(i).add(sc.nextInt());
				}
			}
			//create fare
			int [][] farelist = new int[c][MAXDIS + 1];
			for(int cInd=0; cInd < c;cInd++){
				ArrayList<Integer> nowq = qlist.get(cInd);
				for(int i = 1; i < nowq.size();i++){
					for(int j = nowq.get(i-1) + 1 ; j <= nowq.get(i); j++){
						farelist[cInd][j] = farelist[cInd][j-1] + rlist.get(cInd).get(i-1);
					}
				}
			}
			
			//create pass
			int [][] pass = new int[n][n];
			
			for(int i = 0; i < n; i++){
				for(int j = 0; j < n; j++){
					int value = INF;
					for(int cind = 0; cind < c; cind++){
						int dis = dispass[cind][i][j];
						if(dis >= INF) continue;
						value = Math.min(value, farelist[cind][dis]);
					}
					pass[i][j] = value;
				}
			}

			for(int j = 0; j < n; j++){
				for(int i = 0; i < n; i++){
					for(int k = 0; k < n; k++){
						pass[i][k] = Math.min(pass[i][k], pass[i][j] + pass[j][k]);
					}
				}
			}
			int ans = pass[s][g] >= INF ? -1 : pass[s][g];
			System.out.println(ans);
		}
	}

	public static void main(String[] args) {
		Main obj = new Main();
		obj.doit();
	}
}

Measured memory_bytes: 27000
#include <iostream>
using namespace std;
using ll = long long;
int main() {
    ll n,m;
    cin >> n >> m;
    ll ans = 1;
    ll mod=1000000007;
    for (int i = 0; i < n; i++) {
        ans *= (m - i);
        ans %= mod;
    }
    ll p = 1;
    ll q = 0;
    for (int i = 0; i < n; i++) {
        int qq = q;
        q = (p+qq) * (n - i - 1);
        p *= (m - n);
        p += qq * (m - n + 1);
        p %= mod;
        q %= mod;
    }
    cout << ans*p%mod<< endl;
}

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


int main(int argc, char *argv[]) {
  // C-style stdio functions should not be used.
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout << setprecision(20);

  int N; cin >> N;
  vector<int> L(N), R(N);
  for (int i = 0; i < N; i++) cin >> L.at(i) >> R.at(i);
  vector<int> ord(N);
  iota(ord.begin(), ord.end(), 0);
  sort(ord.begin(), ord.end(),
       [&](int x, int y) {
	 if (L.at(x) == L.at(y)) { return R.at(x) > R.at(y); }
	 return L.at(x) < L.at(y);
       });
  vector<int> vec(N);
  int iv = 0;
  vec.at(iv++) = 0;
  for (int i = 1; i < N; i++) {
    while (iv > 0 && R.at(ord.at(vec.at(iv-1))) >= R.at(ord.at(i))) {
      iv--;
    }
    vec.at(iv++) = i;
  }
  if (iv == 1) {
    int i0 = vec.at(0);
    int minLen = R.at(ord.at(i0)) - L.at(ord.at(i0)) + 1;
    int xmax = 0;
    for (int i = 0; i < N; i++) {
      if (i == i0) continue;
      xmax = max(xmax, R.at(ord.at(i)) - L.at(ord.at(i)) + 1);
    }
    cout << minLen + xmax << endl;
    return 0;
  }

  int xmax = 0;
  int xmaxArg = 0;
  for (int i = 0; i < N; i++) {
    int thisLen = R.at(i) - L.at(i) + 1;
    if (thisLen > xmax) {
      xmax = thisLen;
      xmaxArg = i;
    }
  }
  int rr0 = (int)(1e9) + 10;
  int ll0 = 0;
  for (int i = 0; i < N; i++) {
    if (i == xmaxArg) continue;
    rr0 = min(rr0, R.at(i));
    ll0 = max(ll0, L.at(i));
  }
  int zLen = max(0, rr0 - ll0 + 1);

  int ymax = 0;
  int rrr = R.at(ord.at(vec.at(0)));
  int lll = L.at(ord.at(vec.at(iv-1)));
  for (int i = 0; i < iv-1; i++) {
    int len1 = rrr - L.at(ord.at(vec.at(i))) + 1;
    int len2 = R.at(ord.at(vec.at(i+1))) - lll + 1;
    int thisLen = max(0, len1) + max(0, len2);
    ymax = max(ymax, thisLen);
  }
  cout << max(ymax, xmax + zLen) << endl;

  return 0;
}



Measured memory_bytes: 1920
#include<stdio.h>

int main()
{
	int h, w, i, j;

	scanf("%d %d", &h, &w);
	while (h && w)
	{
		for (i = 0; i < w; i++)
			printf("#");
		printf("\n");

		for (i = 0; i < h - 2; i++)
		{
			printf("#");
			for (j = 0; j < w - 2; j++)
			{
				printf(".");
			}
			printf("#\n");
		}
		for (i = 0; i < w; i++)
			printf("#");
		printf("\n\n");
		scanf("%d %d", &h, &w);
	}
	return 0;
}


Measured memory_bytes: 2120
#include <bits/stdc++.h>
using namespace std;
#define PI 3.141592653589793
#define MOD 1000000007
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(v) v.begin(), v.end()

typedef long long ll;
typedef long double ld;

int main() {
    ll A, B;
    cin >> A >> B;
    vector<ll> num_A;
    vector<ll> num_B;
    vector<ll> num;
    num_A.push_back(1);
    num_B.push_back(1);
    for(int i = 2; i <= sqrt(A); i++){
        if(A % i == 0){
            while(A % i == 0){
                A = A / i;
            }
            num_A.push_back(i);
        }
    }
    num_A.push_back(A);
    sort(num_A.begin(),num_A.end());
    num_A.erase(unique(num_A.begin(), num_A.end()), num_A.end());

    for(int i = 2; i <= sqrt(B); i++){
        if(B % i == 0){
            while(B % i == 0){
                B = B / i;
            }
            num_B.push_back(i);
        }
    }
    num_B.push_back(B);
    sort(num_B.begin(),num_B.end());
    num_B.erase(unique(num_B.begin(), num_B.end()), num_B.end());

    for(int i = 0; i < num_A.size(); i++){
        for(int j = 0; j < num_B.size(); j++){
            if(num_A[i] == num_B[j]){
                num.push_back(num_A[i]);
            }
        }
    }

    cout << num.size() << endl; 
}

Measured memory_bytes: 3680
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            int hmax = 250, hmin = 250, wmax = 250, wmin = 250;
            int n = sc.nextInt();
            if (n == 0) {
                break;
            }
            int[][] map = new int[1000][2];
            map[0] = new int[]{250, 250};
            int[] dir = new int[]{1, 0, -1, 0, 1};
            for (int i = 1; i < n; i++) {
                int k = sc.nextInt();
                int d = sc.nextInt();
                int dx = map[k][0];
                int dy = map[k][1];
                map[i] = new int[]{dx + dir[d], dy + dir[d + 1]};
                hmax = Math.max(map[i][1], hmax);
                hmin = Math.min(map[i][1], hmin);
                wmax = Math.max(map[i][0], wmax);
                wmin = Math.min(map[i][0], wmin);
            }
            // arrayDump(map);
            System.out.println((wmax - wmin + 1) + " " + (hmax - hmin + 1));
        }
    }

    public static void arrayDump(int[][] a) {
        for (int i = 0, l = a.length; i < l; i++) {
            for (int j = 0, l2 = a[0].length; j < l2; j++) {
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
    }
}

Measured memory_bytes: 42728
class UnionFindTree:
    __slots__ = ('__tree', '__current')

    def __init__(self, n):
        self.__tree = [-1] * n
        self.__current = iter(self.__tree)

    def find(self, x):
        t = self.__tree
        if t[x] < 0:
            return x
        root = self.find(t[x])
        t[x] = root
        return root

    def union(self, x, y):
        t = self.__tree
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False
        if t[x] > t[y]:
            x, y = y, x
        t[x] += t[y]
        t[y] = x
        return True

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def size(self, x):
        return -self.__tree[self.find(x)]

    def __next__(self):
        try:
            return next(self.__current)
        except StopIteration:
            self.__current = iter(self.__tree)
            raise StopIteration()

    def __iter__(self):
        return self


def spline(func_=int, iter_=None):
    if iter_ is None:
        iter_ = input().split()
    return map(func_, iter_)


def main():
    n, m = spline()
    tree = UnionFindTree(n)
    for i in range(1, m + 1):
        x, y, _ = spline(func_=lambda x: int(x) - 1)
        tree.union(x, y)
    ans = 0
    for i in tree:
        if i < 0:
            ans += 1
    print(ans)


if __name__ == "__main__":
    main()


Measured memory_bytes: 5356
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false); cin.tie(0)
#define int long long
#define SZ(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF (int)1e18

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
  return neg * x;
}
inline void print(int x) {
  if (x < 0) { putchar('-'); x = -x; }
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}

int n;
string str;
signed main() {
  IO;
  cin >> n;
  cin >> str;
  int sum = 0;
  for(int i = 0 ; i < n ; i++){
    if(str[i] == 'R') sum++;
  }
  int cnt = 0;
  for(int i = 0 ; i < n ; i++){
    if(i < sum && str[i] != 'R') cnt++;
    if(i >= sum && str[i] == 'R') cnt++;
  }
  cout << cnt / 2 << '\n';
  return 0;
}

Measured memory_bytes: 3760
def main():
    n,m,x,y = map(int, input().split())
    X = list(map(int, input().split()))
    Y = list(map(int, input().split()))

    for z in range(x+1,y+1):
        if sorted(X)[-1] < z:
            if z <= sorted(Y)[0]:
                print('No War')
                return
    print('War')


if __name__ == '__main__':
    main()


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

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    
    long long n, k;
    cin >> n >> k;
    
    n %= k;
    cout << min(n, k - n);
    
    
    //if (n % k == 0){
        //cout << 0;
    //} else {
        //cout << k - n % k;
    //}
    
    cout << "\n";
    
    return 0;
}

// scanf("%d %d", &a, &b)
// printf("%d %d", 123, 456);

// getline(cin, s)
// while (cin >> x) {...} - read unknown data

// vector. vector[i],
// set. insert(), contains == set.find(x) != set.end(), size_t size() or count(x) 
// map. contains == count(x) ?


Measured memory_bytes: 256
def resolve():
    N = int(input())
    X = list(map(int, input().split()))
    ans = []
    for i in range(min(X), max(X)+1):
        count = 0
        for j in range(N):
            count += (X[j]-i)**2
        ans.append(count)
    print(min(ans))
resolve()

Measured memory_bytes: 3060
'use strict';
process.stdin.on('data', function(chunk) {
    var inputs = chunk.toString().trim().split(' ');
    var a = Number(inputs[0]);
    var b = Number(inputs[1]);
    var c = Number(inputs[2]);
    
    var sortTable  = [a,b,c].sort(function(a,b) {
    	return a - b;
    });
		console.log(sortTable.join(' '));
});
process.stdin.resume();
process.stdin.setEncoding('utf8');

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

const int N = (int)1e5 + 10;
const double eps = 1e-8;

template <typename T> inline T gcd(T a, T b) { a = abs(a), b = abs(b); while ( b ) { a %= b; swap(a, b); } return a; }
ll dp[N + 7][2];
bool vis[N + 7][2];
ll arr[N + 7];
int n;

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cin >> n;
	for ( int i = 0; i < n; ++i ) cin >> arr[i];
	dp[0][0] = arr[0], dp[0][1] = -arr[0];
	for ( int i = 1; i < n; ++i ) {
		dp[i][0] = max(dp[i - 1][0] + arr[i], dp[i - 1][1] - arr[i]);
		dp[i][1] = max(dp[i - 1][0] - arr[i], dp[i - 1][1] + arr[i]);
	}
	cout << dp[n - 1][0] << endl;
    return 0;
}


Measured memory_bytes: 2560