akhauriyash/Code-Regression huggingface dataset:
## 01BFS
## 2値の場合、priority queueみたいなのを工夫して計算量を落とせる
# 0の場合 : 先頭に値を追加 appendleft
# 1の場合 : 後方に値を追加 append
# 常に先頭から取り出す pop
# ※queueを２つ用いても良い

from collections import deque

H, W = map(int, input().split())
ch, cw = map(int, input().split())
dh_, dw_ = map(int, input().split())

fs = []
for i in range(H):
    r = list(input())
    fs.append(r)

walks = [(-1,0),(1,0),(0,1),(0,-1)]
magics = []
for i in range(-2,3):
    for j in range(-2,3):
        if i==j==0:continue
        if (i,j) not in walks:
            magics.append((i,j))

INF = 1 << 50
dps = [[INF]*W for i in range(H)]
dps[ch-1][cw-1] = 0
q = deque([])
q.appendleft(((ch-1)*INF+(cw-1),0))
while len(q)>0:
    n,cnt = q.popleft()
    h,w = divmod(n, INF)
    if cnt > dps[h][w]:continue
    dps[h][w] = cnt
    # 歩いた
    for dh, dw in walks:
        hn = h + dh
        wn = w + dw
        if 0<=hn<H and 0<=wn<W:
            if dps[hn][wn] != INF:continue
            if fs[hn][wn] == ".":
                q.appendleft((hn*INF+wn, cnt))
    # 魔法
    for dh, dw in magics:
        hn = h + dh
        wn = w + dw
        if 0<=hn<H and 0<=wn<W:
            if dps[hn][wn] != INF:continue
            if fs[hn][wn] == ".":
                q.append((hn*INF+wn, cnt+1))

ans = dps[dh_-1][dw_-1]
print(ans if ans != INF else -1)


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


#define fi first
#define se second
#define all(x) (x).begin() , (x).end()
#define rall(x) (x).rbegin() , (x).rend()
#define pb push_back
#define len(x) (int)(x).size()
#define mkp make_pair

using namespace std;

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


const int maxn = 3e5 + 10 , inf = 1e9;
int fen[maxn];
int get(int pos){
    int ans = 0;
    for(;pos > 0 ;pos -= (pos & -pos))
        ans += fen[pos];
    return ans;
}
void add(int x , int val){
    for(;x < maxn; x += (-x & x)){
        fen[x]+= val;
    }
}
void modify(int l , int r){
    add(l ,   +1);
    add(r+1 , -1);
}
vector < int > line[maxn];
signed main(){
    ios_base::sync_with_stdio(0) , cin.tie(0) , cout.tie(0);
    int n , m;cin >> n >> m;
    vector < pii > lines(n);
    for(auto &i : lines)cin >> i.fi >> i.se;
    for(int i = 0 ; i < len(lines); ++i){
        line[lines[i].se-lines[i].fi+1].pb(lines[i].fi);
    }
    int muchlonger = n;
    for(int i = 1; i <= m; ++i){
        int pos = 0;

        int ans = muchlonger;
        while(pos <= m){
            ans += get(pos);
            pos += i;
        }
        for(auto l : line[i]){
            int r = l + i - 1;
            modify(l , r);
            muchlonger--;
        }
        cout << ans << '\n';
    }

    return 0;
}


Measured memory_bytes: 16312
import sys
import random

def rd():
        return sys.stdin.readline().rstrip()

def rdi():
        return [ int(x) for x in rd().split() ]

N, = rdi()
A = rdi()
B = rdi()
C = rdi()

a = sorted(A)
b = sorted(B)
c = sorted(C)

s = []
j = 0
for i in range(N):
        while j < N and a[j] < b[i]:
                j += 1
        if i == 0:
                s.append(j)
        else:
                s.append(s[i-1] + j)

t = 0
j = 0
for i in range(N):
        while j < N  and b[j] < c[i]:
                j += 1
        #print s[i], j, s[i]*j
        if j > 0:
                t += s[j-1]

print t

Measured memory_bytes: 22948
#include <cstdio>
using namespace std;
typedef long long LL;
const int N=100010;
int n;
LL m;
LL pos[N];
int val[N];
LL fwd[N],bwd[N];
inline LL max(LL x,LL y){
	return x>y?x:y;
}
void readData(){
	scanf("%d%lld",&n,&m);
	for(int i=1;i<=n;i++)
		scanf("%lld%d",&pos[i],&val[i]);
}
void init(){
	LL sum;
	sum=0;
	fwd[0]=0;
	for(int i=1;i<=n;i++){
		sum+=val[i];
		fwd[i]=max(fwd[i-1],sum-pos[i]);
	}
	sum=0;
	bwd[n+1]=0;
	for(int i=n;i>=1;i--){
		sum+=val[i];
		bwd[i]=max(bwd[i+1],sum-(m-pos[i]));
	}
}
void solve(){
	LL ans=max(fwd[n],bwd[1]);
	LL sum;
	sum=0;
	for(int i=1;i<=n;i++){
		sum+=val[i];
		ans=max(ans,sum-2*pos[i]+bwd[i+1]);
	}
	sum=0;
	for(int i=n;i>=1;i--){
		sum+=val[i];
		ans=max(ans,sum-2*(m-pos[i])+fwd[i-1]);
	}
	printf("%lld\n",ans);
}
int main(){
	readData();
	init();
	solve();
	return 0;
}


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

int main()
{
	int a[4];
	for(int i=0;i<4;i++) scanf("%i",&a[i]);
	sort(a,a+4);
	if(a[0]==1 && a[1]==4 && a[2]==7 && a[3]==9) printf("YES\n");
	else printf("NO\n");
	return 0;
}


Measured memory_bytes: 256
L = list(map(int, input()))
N = len(L)

tab2 = [None] * (N + 2)
tab2[0] = tmp = 1
for i in range(N + 1):
    tmp = (tmp * 2) % (10 ** 9 + 7)
    tab2[i + 1] = tmp

tab3 = [None] * (N + 1)
tab3[0] = tmp = 1
for i in range(N):
    tmp = (tmp * 3) % (10 ** 9 + 7)
    tab3[i + 1] = tmp

ans = tab3[-1]
cnt = 0
for i, Li in enumerate(L):
    if Li == 1:
        cnt += 1
    else:
        ans = (ans - tab3[N - 1 - i] * tab2[cnt + 1]) % (10 ** 9 + 7)
        
print(ans)

Measured memory_bytes: 11784
#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <cstdio>
#include <cmath>

using namespace std;

int main(){
    int n;
  cin>>n;
  long long int a[n+1];
  for(int i=0;i<=n;i++){
	if(i==0){
      a[i]=2;
    }else if(i==1){
      a[i]=1;
    }else{
      a[i]=a[i-1]+a[i-2];
    }
  }
  cout<<a[n];
    return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
P dp[101][50001];
 
void Max(P &a,P b){a=max(a,b);}
 
int main(){
  int n,p[101];
  while(cin>>n,n){
    for(int i=0;i<n;i++)cin>>p[i];
     
    memset(dp,-1,sizeof(dp));
    dp[0][0]=P(0,0);
   
    for(int i=0;i<n;i++)
      for(int j=0;j<n*500;j++){
    if(dp[i][j]==P(-1,-1))continue;
    int coin=dp[i][j].first, ncost=dp[i][j].second-p[i];
    Max(dp[i+1][j],dp[i][j]);
    if(p[i]%1000<500&&p[i]%1000)Max(dp[i+1][j+(500-p[i]%500)],P(coin+1,ncost));
    if(p[i]%1000==0&&j>=500) Max(dp[i+1][j-500],P(coin+1,ncost));
     
    if(p[i]%1000>=500) {
      if(j>=p[i]%500)Max(dp[i+1][j-p[i]%500],P(coin+1,ncost));
      else Max(dp[i+1][j+(500-p[i]%500)],P(coin,ncost));
    }
      }
     
    P ans=P(0,0);
    for(int i=0;i<50000;i++)Max(ans,dp[n][i]);
    cout <<ans.first<<" "<<-ans.second<<endl;
     
  } 
  return 0;
}

Measured memory_bytes: 42536
#include <bits/stdc++.h>
		using namespace std;
		typedef long long ll;
		#define PRINT(x,y) cout<<"Case #"<<(int)x<<": "<<(int)(y)<<endl;
		ll exp(ll x, ll y) {
			if(y==0) return 1;
			if(y==1) return x;
			if(y%2==0) return exp(x,y/2)*exp(x,y/2);
			else return x*exp(x,y/2)*exp(x,y/2);
		}
		ll gcd(ll a , ll b) {
			if(b==0) return a;
			return gcd(b , a%b);
		}
		ll lcm(ll a , ll b) {
			return (a*b)/gcd(a,b);
		}
		#define vec(n) vector<int> v((int)(n),0);
		#define vecl(n) vector<ll> v((ll)(n),0);
		#define sq(a) ((int)(a))*((int)(a));
		#define io ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
		int l;
		ll fact(ll x) {
			if(x==1) return 1;
			else return x*fact(x-1);
		}
		bool isPrime(int x) {
			int ans  = 0;
			for(int i=2;i<=sqrt(x);++i) {
				if(x%i==0) {
					ans = 1; i=x;
				}  
			}
			if(ans==0) return true;
			else return false;
		}
		ll isPerfect(ll x) {
			double y = sqrt(x);
			return (floor(y)==ceil(y));
		} 

		int z = 0;
		void ask(int x, int y) {
			cout<<"? "<<x<<" "<<y<<endl;
			}

		void solve() {
			int n; cin>>n;
		cout<<!n;

		}			



		int main() {
			io
			
			 solve();
		}
		    
		

Measured memory_bytes: 3720
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb emplace_back
#define mp make_pair
#define f(i,a,n) for(int i=a ; i<n ; i++)
#define F first
#define E endl
#define S second
#define fast ios:: sync_with_stdio(false),cin.tie(0);
    
int main()
{
	ll n,a,b;
	cin>>n>>a>>b;
	ll x=min(a,b);
	ll y=max(a,b);
	ll j=x-1;
	ll k=n-y;
	ll z=abs(a-b);
	if(z%2==0)
	cout<<z/2;
	else
	{
		if(j<k)
		{
		   ll ans1=x-1+((y-x+1)/2);
		   ll ans=min(y-1,ans1);
		   cout<<ans;
		}
		else
		{
		    ll ans1=n-y+((y-x+1)/2);
		    ll ans=min(n-x,ans1);
		    cout<<ans;
		}
	}
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
 
int main() {
  string S,T;
  int count = 0;
  cin >> S >> T ;
  for(int i = 0 ; i < 3 ; i++){
    if(S.at(i) == T.at(i)) count++;
  }
  cout << count;
  return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>
#include <set>

using namespace std;

#define x first
#define y second
#define mp make_pair
#define pb push_back

typedef long long ll;

const ll MOD = 1e9+7;

char a[30005];

int l[15];
int r[15];

set <int> sol;

int main() {
	int n;
	scanf("%d", &n);
	for (int i=0 ; i<n ; i++) {
		scanf(" %c", a+i);
		a[i] -= '0';
		r[a[i]]++;
	}
	for (int i=0 ; i<n ; i++) {
		r[a[i]]--;
		for (int j=0 ; j<10 ; j++) {
			for (int k=0 ; k<10 ; k++) {
				if (l[j] and r[k]) {
					//cout <<"nigga\n";
					sol.insert(j*100 + a[i]*10 + k);
				}
			}
		}
		l[a[i]]++;
	}
	printf("%d", sol.size());
	return 0;
}

Measured memory_bytes: 256
import sys
C=range(1001)
m=0
d=[[0 for i in C] for j in range(2)]
for s in sys.stdin.readlines():
    if s=="\n":m+=1
    else:
        a,b=map(int,s.split(','))
        d[m][a]+=1
for i in C:
    a=d[0][i]
    b=d[1][i]
    if a!=0 and b!=0:print i,a+b

Measured memory_bytes: 4248
#include <bits/stdc++.h>
#include <unordered_map>
#include <unordered_set>
using namespace std;
#define endl '\n'
#define PI acos(-1)
typedef long long ll;
//	Table is the complete reverse of dp
//	Always think of the pattern (LCM, GCD)
//	Be careful of unsigned
//	double epsilon = FLT_EPSILON;
//	Think of a solution that gets TLE and optimize it
const int MOD = 1e9 + 7;
int n, **dp[2], d;
string k;
int main()
{
    cin.tie(nullptr); cout.tie(nullptr); ios_base::sync_with_stdio(false);
    cin >> k >> d;
    n = k.size();
    dp[0] = new int *[d];
    dp[1] = new int *[d];
    for(int i = 0; i < d; i++)
    {
    	dp[0][i] = new int[n + 1];
    	dp[1][i] = new int[n + 1];
    	dp[0][i][n] = dp[1][i][n] = 0;
    }
    dp[1][0][n] = 1;
    for(int i = n - 1; i >= 0; i--)
    	for(int rem = d - 1; rem >= 0; rem--)
    	{
    		dp[0][rem][i] = dp[1][rem][i] = 0;
    		for(int j = 9; j >= 0; j--)
			{
    			dp[1][rem][i] += dp[1][(rem + j) % d][i + 1];
    			if(dp[1][rem][i] >= MOD)
    				dp[1][rem][i] -= MOD;
			}
    		for(int j = k[i] - '0'; j >= 0; j--)
			{
				dp[0][rem][i] += dp[j != k[i] - '0'][(rem + j) % d][i + 1];
				if(dp[0][rem][i] >= MOD)
					dp[0][rem][i] -= MOD;
			}
    	}
    int ans = 0;
    for(int i = 0; i < n; i++)
    	ans += k[i] - '0';
    ans = ans % d == 0;
    cout << ((ans + dp[0][0][0] - 1) % MOD + MOD) % MOD;
}


Measured memory_bytes: 8064
#include <iostream> // cout, endl, cin
#include <string> // string, to_string, stoi
#include <vector> // vector
#include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound
#include <utility> // pair, make_pair
#include <tuple> // tuple, make_tuple
#include <cstdint> // int64_t, int*_t
#include <cstdio> // printf
#include <map> // map
#include <queue> // queue, priority_queue
#include <set> // set
#include <stack> // stack
#include <deque> // deque
#include <unordered_map> // unordered_map
#include <iomanip>
#include <unordered_set> // unordered_set
#include <bitset> // bitset
#include <cctype> // isupper, islower, isdigit, toupper, tolower
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
using Graph = vector<vector<int>>;
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; }
const int INF = 1000000000;
const int MOD = 1000000007;

typedef pair<int, int> P;
int myAbs(int num) {
    if (num > 0)
        return num;
    else
        return -num;
}

long long gcd(long long a, long long b) {
    if (b == 0) return a;
    else return gcd(b, a % b);
}
long long lcm(long long a, long long b) {
    return a * b / gcd(a, b);
}

/*vector<bool> seen;
void dfs(const Graph& G, int v, int count) {
    seen[v] = true;
    count = 0;
    for (auto next_v : G[v]) {
        if (seen[next_v]) continue;
        if (count > 2) continue;
        count++;
        cout << count << ":" << next_v << endl;
        dfs(G, next_v, count);
    }
}*/

typedef pair<int, int> P;

using Maze = vector<vector<char>>;
using D = vector<vector<int>>;

int maze_solve(char Maze[51][51],int N, int M, int sx, int sy, int gx, int gy) {
    queue<P> que;
    que.push(P(sx, sy));
    //配列はNとMの最大値+1くらいをとっておく
    int D[51][51];
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            D[i][j] = INF;
        }
    }
    int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };
    D[sx][sy] = 0;
    Maze[sx][sy] = 0;
    //ここから処理
    while (que.size()) {
        P p = que.front();
        que.pop();
        if (p.first == gx && p.second == gy) break;
        for (int i = 0; i < 4; i++) {
            int nx, ny;
            nx = p.first + dx[i]; ny = p.second + dy[i];
            if (nx >= 0 && nx < N && ny >= 0 && ny < M && D[nx][ny] == INF && Maze[nx][ny] != '#') {
                que.push(P(nx, ny));
                D[nx][ny] = D[p.first][p.second] + 1;
            }
        }
    }
    if (D[gx][gy] == INF) return 0;
    else return D[gx][gy];
}


int main() {
    int H, W; cin >> H >> W;
    char C[51][51];
    int count = -1;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            cin >> C[i][j];
            if (C[i][j] == '.') count++;
        }
    }
    int kyori = maze_solve(C,H, W, 0, 0, H-1, W-1);
    if (kyori == 0) {
        cout << -1 << endl;
        return 0;
    }
    cout << count - kyori << endl;
    //cout << count << endl;
    //cout << kyori << endl;
}


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

using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep2(i, s, n) for (int i = (s); i < (int)(n); i++)
typedef long long ll;
using Graph = vector<vector<int>>;
typedef long long ll;
typedef pair<int, int> P;

const int MOD = 1000000007;
const int INF_32 = 1LL << 30;
const int64_t INF_64 = 1LL << 60;

int main()
{
    int n, m;
    cin >> n >> m;
    vector<int> a(n);
    int sum = 0;
    rep(i, n)
    {
        cin >> a.at(i);
        sum += a.at(i);
    }

    int cnt = 0;
    rep(i, n)
    {
        if (a.at(i) * 4 * m >= sum)
            cnt++;
    }

    if (cnt >= m)
        cout << "Yes" << endl;
    else {
        cout << "No" << endl;
    }
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#define rep(i,n); for(int i = 0;i < (n);i++)
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
long double pi = acos(-1);
const int INF = 1001001001;


// 最小公倍数を求める
int euqlid (int a, int b){
  int temp;
  temp = a % b;
  if(temp == 0)return b;
  return euqlid(b,temp);
}
ll conbination(ll a,ll b){
  ll u = 1;
  ll d = 1;
  while(b != 0){
    u *= a;
    d *= b;
    a--;
    b--;
  }
  return u / d;
}
int strtoint(char s){
  return (int(s-'0'));
}
int fact(int n){
  if(n == 1)return 1;
  return n * fact(n-1);
  }


int main(){
  int n;
  cin >> n;
  cout << n/3 << endl;
}


Measured memory_bytes: 256
import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int a=sc.nextInt();
		sc.nextLine();
		String b=sc.nextLine();
		String s = "",S="";
		for(int i=0;i<a/2;i++) {
			s+=b.charAt(i);
		}
		for(int i=a/2;i<a;i++) {
			S+=b.charAt(i);
		}
		String can = s.equals(S)?"Yes":"No";
		System.out.println(can);
	}
}


Measured memory_bytes: 21972
#include<bits/stdc++.h>
using namespace std;
string st;
int main()
{
	cin>>st;
	if(st.size()<5||st.size()>9)
	{
		cout<<"NO";
		exit(0);
	}
	if(st=="AKIHABARA"||st=="KIHBR")
	  cout<<"YES";else
	if(st=="KIHABARA"||st=="AKIHBARA"||st=="AKIHABRA"||st=="AKIHABAR")
	  cout<<"YES";else
	if(st=="KIHBARA"||st=="KIHABRA"||st=="KIHABAR"||st=="AKIHBRA"||st=="AKIHBAR"||st=="AKIHABR")
	  cout<<"YES";else
	if(st=="KIHBRA"||st=="KIHBAR"||st=="AKIHBR"||st=="KIHABR")
	  cout<<"YES";else
	  cout<<"NO";
	return 0;
}

Measured memory_bytes: 256
x = input().split()
N = int(x[0])
X = int(x[1])
Y = int(x[2])

L = [0 for _ in range(N+1)]

for i in range(1,N):
    for j in range(i+1,N+1):
        L[min(j-i,abs(X-i)+abs(Y-j)+1)] +=1
            
for k in range(1,N):
    print(L[k])


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

int main(){
    int N, M;
    cin >> N >> M;
    priority_queue<int> que;
    for(int i = 0; i < N; i++){
        int A;
        cin >> A;
        que.push(A);
    }
    
    for(int i = 0; i < M; i++){
        int tmp = que.top();
        tmp /= 2;
        que.pop();
        que.push(tmp);
    }
    ll ans = 0;
    for(int i = 0; i < N; i++){
        ans += que.top();
        que.pop();
    }
    cout << ans << "\n";
    return 0;
}


Measured memory_bytes: 892
object Main extends App {
  val Array(n, k) = io.StdIn.readLine().split(' ').map(_.toInt)
  val k2 = k*2
  val end = k2-1
  // 0 ≦ x,y ≦ 2K に圧縮
  val squares = Array.fill(k2)(Array.fill(k2)(0))
  for (i <- 1 to n) {
    val Array(x, y, color) = io.StdIn.readLine().split(' ')
    // 'W'はY方向にKずらした'B'と同値
    squares(x.toInt % k2)((y.toInt + (if (color == "B") 0 else k)) % k2) += 1
  }
  // 計算量削減のために累積和を事前算出
  for {
    i <- 0 to end
    j <- 1 to end
  } squares(i)(j) += squares(i)(j-1)
  for {
    j <- 0 to end
    i <- 1 to end
  } squares(i)(j) += squares(i-1)(j)
  val max = (for {
    i <- 0 to k-1
    j <- 0 to k-1
  } yield {
    // ex) k = 2
    //      ■ □ □ ■ 
    //  j+k □ ■ ■ □
    //      □ ■ ■ □
    //    j ■ □ □ ■
    //      i   i+k
    val cnt =
      (squares(i)(j)) +
      (squares(end)(j) - squares(i+k)(j)) +
      (squares(i+k)(j+k) - squares(i+k)(j) - squares(i)(j+k) + squares(i)(j)) +
      (squares(i)(end) - squares(i)(j+k)) +
      (squares(end)(end) - squares(end)(j+k) - squares(i+k)(end) + squares(i+k)(j+k))
    Math.max(cnt, n - cnt)
  }).par.max
  print(max)
}


Measured memory_bytes: 104488
// ------------------------------------
// Date:2018/ 3/ 4
// Problem:ABC 060 Sentou c.cpp
//
// ------------------------------------

#include <bits/stdc++.h>

using namespace std;

#define EACH(i,a) for (auto&& i : a)
#define FOR(i,a,b) for(int i=(int)a;i<(int)b;++i)
#define RFOR(i,a,b) for(int i=(int)b-1;i>=(int)a;--i)
#define REP(i,n) FOR(i,0,n)
#define RREP(i,n) RFOR(i,0,n)
#define ALL(a) (a).begin(),(a).end()
#define debug(x) cerr << #x << ":" << x << endl

typedef long long ll;

static const int MOD = 1000000007;

int N, T;

int main()
{
  cin.tie(0);
  ios::sync_with_stdio(false);
  
  cin >> N >> T;
  vector< int > t(N + 1, 0);
  REP(i, N)
    cin >> t[i + 1];

  ll ans = T;
  REP(i, N) {
    ans += min(T, t[i + 1] - t[i]);
  }

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



Measured memory_bytes: 1024
n = input()
S = []
H = []
C = []
D = []
i = 1
while True:
    if i > n:
        break

    card = raw_input().split()
    mark = card[0]
    num = int(card[1])

    if mark == 'S':
        S.append(num)
    elif mark == 'H':
        H.append(num)
    elif mark == 'C':
        C.append(num)
    elif mark == 'D':
        D.append(num)

    i += 1

diff_S = set(range(1, 14)) - set(S)
for s in sorted(diff_S):
    print "S %d" % s
diff_H = set(range(1, 14)) - set(H)
for h in sorted(diff_H):
    print "H %d" % h
diff_C = set(range(1, 14)) - set(C)
for c in sorted(diff_C):
    print "C %d" % c
diff_D = set(range(1, 14)) - set(D)
for d in sorted(diff_D):
    print "D %d" % d

Measured memory_bytes: 6384
#include <bits/stdc++.h>
#define IOS                           \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL);
#define ll long long
using namespace std;

ll mod(ll a)
{
    if (a < 0)
    {
        return -a;
    }
    else
    {
        return a;
    }
}

ll minimumCost(vector<ll> &v, ll cur, int k, vector<ll> &dp)
{
    if(cur >= v.size()){
        return 0;
    }

    if (dp[cur] != -1)
    {
        return dp[cur];
    }
    ll cost = INT_MAX;
    int i = 1;
    while (i <= k && cur + i < v.size())
    {
        cost = min (cost , mod(v[cur] - v[cur + i]) + minimumCost(v, cur + i, k, dp));
        i++;
    }
    if(cost == INT_MAX){
        return 0;
    }
    dp[cur] = cost;
    return cost;
}

void solve()
{

    int n, k;
    cin >> n >> k;

    vector<ll> h;
    vector<ll> dp(n + 1, -1);
    ll data;
    for (int i = 0; i < n; i++)
    {
        cin >> data;
        h.push_back(data);
    }
    cout << minimumCost(h, 0, k, dp) << endl;
}

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

Measured memory_bytes: 11380
#include<bits/stdc++.h>
#define rep(i,n) for(int (i) = 0;(i) < (n);(i)++)
using namespace std;
typedef long long ll;
// cd test ; rm -R ./*; cd .. 

int main(void) {
  int n;
  cin >> n;
  vector<int> h(n);
  rep (i, n) cin >> h[i];


  int ans = 0;
  while (1) {
    bool NotAdd = true;
    for (int i = 0; i < n; i++) {
      if (h[i] != 0) {
        NotAdd = false;
        h[i]--;
        if (i == n - 1) {
          ans++;
        }
      }
      else {
        if (!NotAdd) ans++;
        NotAdd = true;
      }
    }
    bool stop = true;
    rep (i, n) if (h[i]) stop = false;
    if (stop) break;
  }
  cout << ans << endl;
  return 0;
}

Measured memory_bytes: 256
#include <algorithm>
#include <bitset>
#include <climits>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>

#define MOD 1000000007
#define MOD2 998244353
#define int long long
#define double long double
#define EPS 1e-9
//#define PI 3.14159265358979

#define rep(i, n) for (int i = 0; i < (int)(n); i++)

using namespace std;

template < typename T >
ostream &operator<<(ostream &os, const vector< T > &A) {
	for (int i = 0; i < A.size(); i++)
		os << A[i] << " ";
	os << endl;
	return os;
}
template <>
ostream &operator<<(ostream &os, const vector< vector< int > > &A) {
	int N = A.size();
	int M;
	if (N > 0)
		M = A[0].size();
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < M; j++)
			os << A[i][j] << " ";
		os << endl;
	}
	return os;
}

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

struct edge {
	int from, to, d, c;
	edge(int _from = 0, int _to = 0, int _d = 0, int _c = 0) {
		from = _from;
		to = _to;
		d = _d;
		c = _c;
	}
	bool operator<(const edge &rhs) const {
		return (d == rhs.d) ? (c < rhs.c) : (d < rhs.d);
	}
};
struct aabb {
	int x1, y1, x2, y2;
	aabb(int x1, int y1, int x2, int y2) : x1(x1), y1(y1), x2(x2), y2(y2) {}
};

typedef vector< edge > edges;
typedef vector< edges > graph;
struct flow {
	int to, cap, rev, cost;
	flow(int to = 0, int cap = 0, int rev = 0, int cost = 0) : to(to), cap(cap), rev(rev), cost(cost) {}
};
typedef vector< vector< flow > > flows;

const int di[4] = {0, -1, 0, 1};
const int dj[4] = {-1, 0, 1, 0};
const int ci[5] = {0, 0, -1, 0, 1};
const int cj[5] = {0, -1, 0, 1, 0};
const ll LINF = LLONG_MAX / 2;
const int INF = INT_MAX / 2;
const double PI = acos(-1);

int pow2(int n) { return 1LL << n; }
template < typename T, typename U >
bool chmin(T &x, const U &y) {
	if (x > y) {
		x = y;
		return true;
	}
	return false;
}
template < typename T, typename U >
bool chmax(T &x, const U &y) {
	if (x < y) {
		x = y;
		return true;
	}
	return false;
}

struct initializer {
	initializer() {
		cout << fixed << setprecision(20);
	}
};
initializer _____;

int N, M, K, T, Q, H, W;
signed main() {
	cin >> N;
	vector< int > A(N);
	rep(i, N) cin >> A[i];
	vector< int > C(3, 0);
	rep(i, N) {
		if (A[i] % 4 == 0) {
			C[2]++;
		} else if (A[i] % 2 == 0) {
			C[1]++;
		} else {
			C[0]++;
		}
	}
	string ans = "Yes";
	if (C[0] == C[2] + 1 && C[1] == 0) {
		cout << "Yes" << endl;
		return 0;
	}
	if (C[0] > C[2]) {
		cout << "No" << endl;
		return 0;
	}
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 1024
import functools
N = int(input())
K = int(input())

@functools.lru_cache()
def func(num,counter):
    remain = num%10
    quotient = num//10
    
    
    if counter == 0:
        return 1
    
    if num<10:
        if counter ==1:
            return num
        else:
            return 0

    return func(quotient,counter-1)*remain + func(quotient-1,counter-1)*(9-remain) + func(quotient,counter)

print(func(N,K))

Measured memory_bytes: 63192
from collections import deque

N, M = map(int, input().split())
friends = [[] for _ in range(N)]

for _ in range(M):
    a, b = map(int, input().split())
    a, b = a-1, b-1
    friends[a].append(b)
    friends[b].append(a)

checked = [False] * N
ans = 0

for i in range(N):
    if checked[i] == False:
        checked[i] = True
        DQ = deque(friends[i])
        tmp = 1
        while DQ:
            f = DQ.popleft()
            if checked[f] == False:
               checked[f] = True
               tmp += 1
               for j in friends[f]:
                   DQ.append(j)
        ans = max(ans, tmp)

print(ans)

Measured memory_bytes: 112240
import java.util.Scanner; 
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] two = new int[3];
		for(int i=0; i<n; i++) {
			int cur = sc.nextInt();
			if(cur % 4 == 0) two[2]++;
			else if(cur % 2 == 0) two[1]++;
			else two[0]++;
		}
		if(two[0] <= two[2] || (two[0] - 1 == two[2] && two[0] + two[2] == n))
			System.out.println("Yes");
		else
			System.out.println("No");
	}
}


Measured memory_bytes: 48260
#include <bits/stdc++.h>
using namespace std;
#define PI 3.14159265358979323
#define ll long long int
#define vi vector <int>
#define vl vector <ll>
#define all(v) (v).begin(),(v).end()
#define pb push_back
#define MOD 1000000007
ll power(ll a, ll b) { //a^b
	ll res = 1;
	a = a % MOD;
	while (b > 0) {
		if (b & 1) {res = (res * a) % MOD; b--;}
		a = (a * a) % MOD;
		b >>= 1;
	}
	return res;
}

ll gcd(ll a, ll b) {return (b == 0) ? a : gcd(b, a % b);}

int main() {
#ifndef ONLINE_JUDGE
	// for getting input from input.txt
	freopen("input.txt", "r", stdin);
	// for writing output to output.txt
	freopen("output.txt", "w", stdout);
#endif
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n;
	cin>>n;
	if(n>=1800)
		cout<<1;
	else if(n>=1600)
		cout<<2;
	else if(n>=1400)
		cout<<3;
	else if(n>=1200)
		cout<<4;
	else if(n>=1000)
		cout<<5;
	else if(n>=800)
		cout<<6;
	else if(n>=600)
		cout<<7;
	else
		cout<<8;
}

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

#define FOR(i, a, b)  for (int i = (a); i < (b); i++)
#define FORd(i, a, b) for (int i = (a); i >= (b); i--)
#define REP(i, n) FOR(i, 0, n)
#define TRACE(x) cout << #x << " = " << x << "\n"
#define _ << " _ " <<
#define ll long long

using namespace std;

int bio1[200100];
int bio2[200100];

int main() {
  ios_base::sync_with_stdio(false);

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

  REP(i, m) {
    int a, b;
    cin >> a >> b;
    if (a > b) swap(a, b);
    if (a == 1) bio1[b] = 1;
    if (b == n) bio2[a] = 1;
  }

  REP(i, n) {
    if (bio1[i] && bio2[i]) {
      cout << "POSSIBLE\n";
      return 0;
    }
  }
  cout << "IMPOSSIBLE\n";

  return 0;
}


Measured memory_bytes: 1792
//E - Picking Goods
#include <iostream>
#include <vector>
#define ROW 3001
#define COL 3001
#define PICK 4
typedef long long ll;

std::vector<std::vector<std::vector<ll>>> dp(ROW,std::vector<std::vector<ll>>(COL,std::vector<ll>(PICK+1,0)));
std::vector<std::vector<ll>> V(ROW,std::vector<ll>(COL,0));

void chmax(ll& a,ll b){
    if(a < b) a = b;
    return;
}
int main(){
    int R,C,K;
    std::cin >> R >> C >> K;
    for(int i=0;i<K;i++){
        int r,c;
        std::cin >> r >> c;
        std::cin >> V[r][c];
    }

    for(int i=1;i<=R;i++){
        for(int j=1;j<=C;j++){
            for(int k=0;k<=3;k++){
                chmax(dp[i][j][0],dp[i-1][j][k]);               //上から遷移してそのマスを取らない場合
                chmax(dp[i][j][1],dp[i-1][j][k] + V[i][j]);     //上から遷移してそのマスを取る場合
                chmax(dp[i][j][k],dp[i][j-1][k]);               //左から遷移してそのマスを取らない場合
                if(k >= 1) {
                    chmax(dp[i][j][k], dp[i][j - 1][k - 1] + V[i][j]);   //左から遷移してそのマスをとる場合
                }
            }
        }
    }
    ll ans = 0;
    for(int k=0;k<=3;k++){
        chmax(ans,dp[R][C][k]);
    }
    std::cout << ans;
    return 0;
}


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

typedef long long int ll;
typedef unsigned long long int ull;
#define rep(i,n) for(auto i=0;i<(n);i++)

using namespace std;


int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    
    int n, k;
    cin >> n >> k;
    vector<ll> x(n);
    rep(i, n) cin >> x[i];

    ll minn = 1e10;
    for(int l = 0; l+k <= n; l++){
        int r = l+k-1;
        if(x[r] <= 0){
            minn = min(minn, abs(x[l]));
        }
        else if(0 <= x[l]){
            minn = min(minn, abs(x[r]));
        }
        else{
            minn = min(minn, abs(x[l])+abs(x[r])+min(abs(x[l]), abs(x[r])));
        }
    }
    
    cout << minn << endl;

    return 0;
}



Measured memory_bytes: 1024
#include <bits/stdc++.h>
#define INF LLONG_MAX
#define ll  long long
#define ull unsigned long long
#define rep(i,n) for(int i=0; i<n; ++i)
#define MOD 1000000007
using namespace std;
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;}

int main() {
  int A, B, C; cin >> A >> B >> C;
  cout << max(0,C-(A-B)) << endl;
}


Measured memory_bytes: 256
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
#include <bitset>
#include <cmath>
#include <functional>
#define vv(a, b, c, d) vector<vector<d> >(a, vector<d>(b, c))
#define vvi vector<vector<int> >
#define vvl vector<vector<ll> >
#define vll vector<ll>
#define rep(c, a, b) for(ll c=a;c<b;c++)
#define re(c, b) for(ll c=0;c<b;c++)
typedef long long int ll;
typedef long double ld;
using namespace std;

int main(int argc, char const *argv[]) {
  string s;std::cin >> s;ll n = s.size();
  string t = "";
  re(i, n) if(s[i]!='x') t+=s[i];
  for(int i=0;i<t.size()/2;i++){
    if(t[i]!=t[t.size()-1-i]){
      std::cout << -1 << '\n';
      return 0;
    }
  }
  vll spot(t.size()+1, 0);
  ll now = 0;
  for(int i=0;i<n;i++){
    if(s[i]=='x') spot[now]++;
    else now++;
  }
  ll ans = 0;
  re(i, (t.size()+1)/2){
    ans += max(spot[i], spot[t.size()-i]) - min(spot[i], spot[t.size()-i]);
  }
  std::cout << ans << '\n';
  return 0;
}


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

int ifpal(string s, int l, int r)
{
    int flag = 1;
    for(int i=l;i<=(r-l)/2;++i){
        if(s[i] == s[r - i]);
        else flag = 0;
    }

    return flag;
}

int main()
{
    string s;
    cin>>s;
    int length = s.length()-1;
    if(ifpal(s,0,length)==1 and ifpal(s,0,(length)/2-1)==1 and ifpal(s,(length+3)/2,length)==1)  cout<<"Yes\n";
    else    cout<<"No\n";

    return 0;
}

Measured memory_bytes: 256
import java.util.*;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		// 整数の入力
		int n = sc.nextInt();
		// スペース区切りの整数の入力
		int a = sc.nextInt();
		int b = sc.nextInt();

		int m;

		if (a * n < b) {
			m = a * n;

		} else {
			m = b;
		}

		// 出力
		System.out.println(m);
	}
}


Measured memory_bytes: 21972
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;


public class A
{
	public static void Main()
	{
		string[] args = Console.ReadLine().Split(' ');
		int[] A = new int[3];
		for(int i = 0; i < 3; i++)
			A[i] = Int32.Parse(args[i]);

		int ans = Int32.MaxValue;
		int[] perm = new int[3] {0,1,2};
		do
		{
			int tmp = 0;
			tmp += Math.Abs(A[perm[1]] - A[perm[0]]);
			tmp += Math.Abs(A[perm[2]] - A[perm[1]]);
			ans = Math.Min(ans,tmp);
		} while (nextPermutation(ref perm));

		Console.WriteLine(ans);
	}

	public static bool nextPermutation(ref int[] array)
	{
		int len = array.Length;

		int i = len - 1;
		while((i > 0) && (array[i-1] > array[i]))
			i--;
		if(i == 0)
			return false;
		
		int tmp = array[i-1];
		array[i-1] = array[i];
		array[i] = tmp;

		if(i < (len - 2))
			Array.Reverse(array,i + 1, len - i - 1);

		return true;
	}
}





Measured memory_bytes: 13140
//   _/                _/                 _/_/_/   _/
//_/_/_/_/   _/_/   _/_/_/_/   _/_/    _/       _/_/
// _/     _/    _/   _/     _/    _/  _/_/_/     _/
//_/     _/    _/   _/     _/    _/  _/    _/   _/
// _/_/   _/_/       _/_/   _/_/      _/_/     _/
#include<iostream>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<set>
#include<map>
#include<queue>
#include<vector>
#include<string>
using namespace std;
typedef long long ll;
const int MOD=1e9+7;
const double pi=3.14159265358979323846;
const int inf=2e9;
const ll INF=5e18;
typedef pair<int,int> P;
signed main() {
  cin.tie(0),cout.tie(0);
  ios::sync_with_stdio(false);
  int n,m,a,b,ans=0;
  vector<int> v[100005]={};
  cin >> n >> m;
  priority_queue<int> q;
  for(int i=0; i<n; i++) {
    cin >> a >> b;
    v[a].push_back(b);
  }
  for(int i=1; i<=m; i++) {
    for(auto p:v[i]) {
      q.push(p);
    }
    if(!q.empty()) {
      ans+=q.top();
      q.pop();
    }
  }
  cout << ans << endl;
}

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

std::vector<int> res;

int n, m, x;
std::vector<std::vector<int>> vec;
std::vector<int> book_prices;

int main() {
    std::cin >> n >> m >> x;
    book_prices.assign(n, 0);
    vec.assign(n, std::vector<int>(m, 0));
    for (int i = 0; i < n; i++) {
        std::cin >> book_prices[i];
        for (int j = 0; j < m; j++) {
            std::cin >> vec[i][j];
        }
    }
    for (int i = 0; i < (2 << n); i++) {
        std::vector<int> skill(m, 0);
        int total_price = 0;
        for (int j = 0; j < n; j++) {
            if ((i >> j) & 1) {
                total_price += book_prices[j];
                for (int k = 0; k < m; k++) {
                    skill[k] += vec[j][k];
                }
            }
        }
        int min_skill = *std::min_element(skill.begin(), skill.end());
        if (min_skill >= x) {
            res.push_back(total_price);
        }
        
    }
    if (res.size() > 0) {
        std::cout << *std::min_element(res.begin(), res.end()) << std::endl;
        return 0;
    }
    std::cout << -1 << std::endl;
    
    
    
}

Measured memory_bytes: 3660
#include <bits/stdc++.h>
using namespace std;
 
using ll=long long;
 
#define rng(i,a,b) for(int i=int(a);i<int(b);i++)
#define rep(i,b) rng(i,0,b)
#define gnr(i,a,b) for(int i=int(b)-1;i>=int(a);i--)
#define per(i,b) gnr(i,0,b)
#define pb push_back
#define eb emplace_back
#define a first
#define b second
#define bg begin()
#define ed end()
#define all(x) x.bg,x.ed
const int MOD = 1000000007; 

int main() {
    int n;
    cin >> n;
    string s;
    cin >> s;
    unordered_map<char, int> mp; 
    unordered_set<char> lset;
    int ret = 0; 
    for (char c : s) mp[c]++;
    for (char c : s) {
        mp[c]--;
        lset.insert(c);
        int cnt = 0;
        for (char c : lset) if (mp[c]) ++cnt;
        ret = max(ret, cnt);
    }
    cout << ret << endl;
    return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <numeric>
#include <algorithm>
#include <vector>
#include <array>
#include <string>
#include <queue>
#include <cmath>
#include <iterator>
#include <math.h>
#include <cstdio>
#include <map>
#include <set>
#include <unordered_map>
#include <sstream>
#include <tuple>

using namespace std;
using lli = long long int;
using ulli = unsigned long long int;

void judge_outer(bool judge_exp,string ok = "Yes",string ng = "No"){
    if(judge_exp){
        cout << ok << endl;
    }else{
        cout << ng << endl;
    }
}


int main(void){
    array<int,3> a;
    int answer =0;
    cin >> a[0] >> a[1] >> a[2];
    sort(a.begin(),a.begin()+3);
    while(a[1] != a[2]){
        a[0]++;
        a[1]++;
        answer++;
    }
    cerr << a[0] << " " << a[1] << " " << a[2] << endl;
    while(a[0]<a[2]){
        a[0]+=2;
        answer++;
    }
    cerr << a[0] << " " << a[1] << " " << a[2] << endl;
    if(a[0] != a[2]){
        a[1]++;
        a[2]++;
        answer++;
    }
    cerr << a[0] << " " << a[1] << " " << a[2] << endl;
    cout << answer << endl;
    
    return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
typedef pair<int,int> pii;
#define endl '\n'
#define F first
#define S second
const int MAX_N=1e5+5;

int n,m;
vector<int> G[MAX_N], topo;
int RG[MAX_N];
int len[MAX_N];
int ans;

void bfs()
{
	queue<int> q;
	for(int i=1;i<=n;i++) if(!RG[i]) q.push(i);
	while(!q.empty())
	{
		int now=q.front();
		q.pop();
		topo.emplace_back(now);
		for(auto &i:G[now])
			if(!(--RG[i])) q.push(i);
	}
}

int main()
{
	scanf("%d%d",&n,&m);
	for(int i=0,t1,t2;i<m;i++)
	{
		scanf("%d%d",&t1,&t2);
		G[t1].emplace_back(t2);
		RG[t2]++;
	}
	bfs();
	for(auto &i:topo)
		for(auto &j:G[i])
			len[j]=max(len[j],len[i]+1);
	for(int i=1;i<=n;i++) ans=max(ans,len[i]);
	printf("%d\n",ans);
	return 0;
}



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

using namespace std;

#define rep(i , l , r) for(int i = (l) , ___ = (r) ; i <= ___ ; ++i)
#define per(i , r , l) for(int i = (r) , ___ = (l) ; i >= ___ ; --i)

#define DEBUG(...) fprintf(stderr , __VA_ARGS__)

template<typename T>inline int chkmin(T &x , const T &y){ return x > y ? x = y , 1 : 0; }
template<typename T>inline int chkmax(T &x , const T &y){ return x < y ? x = y , 1 : 0; }

template<typename T>inline T read(T &f)
{
	f = 0 ; int x = 1 ; char c = getchar();
	while(!isdigit(c)) c = x == '-' ? -1 : 1 , c = getchar();
	while(isdigit(c)) (f *= 10) += c & 15 , c = getchar();
	return f *= x;
}

using int64 = long long;
using uint64 = unsigned long long;

const int N = 20 + 5;

int n , A[N] , B[N] , C[N];

int main()
{
	read(n);
	rep(i , 1 , n) read(A[i]);
	rep(i , 1 , n) read(B[i]);
	rep(i , 1 , n - 1) read(C[i]);
	int sum = 0;
	rep(i , 1 , n)
	{
		sum += B[A[i]];
		if(A[i + 1] == A[i] + 1) sum += C[A[i]];
	}
	cout << sum << endl;
	return 0;
}


Measured memory_bytes: 256
import heapq
import math

N,M = list(map(int,input().split()))
A = list(map(int,input().split()))
B = [-a for a in A]

heapq.heapify(B)
for i in range(M):
    b = heapq.heappop(B)
    heapq.heappush(B,math.ceil(b/2))
print(-1*sum(B))

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

void file() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
}

void fast()
{
    std::ios_base::sync_with_stdio(0);
    cin.tie(NULL); cout.tie(NULL);
}

string a, b;

int main(int argc, char const *argv[])
{
    // file();

    cin>>a>>b;

    deque<char>d;
    d.push_back('.');
    for (int i = (int)a.size() - 1; i > b.size(); --i)
    {
        d.push_front(a[i]);
    }
    for (int i = (int)a.size(); i >= 0; --i)
    {
        d.pop_back();
        d.push_front(a[i]);
        int cnt = 0;
        for (int j = 0; j < b.size(); ++j)
        {
            if (b[j] == d[j] or d[j] == '?')
            {
                cnt++;
            }
            else break;
        }
        if (cnt == (int)b.size())
        {
            for(int j = 0; j < i; j++)
                cout<<(a[j] == '?'?'a':a[j]);
            cout<<b;
            for(int j = b.size() + i; j < a.size(); j++)
                cout<<(a[j] == '?'?'a':a[j]);
            return 0;
        }
    }
    cout<<"UNRESTORABLE";

}

Measured memory_bytes: 256
N=int(input())
reds = set()
blues = []
for i in range(N):
    x,y=map(int,input().split())
    reds.add((x,y))
for i in range(N):
    x,y=map(int,input().split())
    blues.append((x,y))
blues.sort(key=lambda x: x[0])
ans = 0
for (bx,by) in blues:
    candidates = []
    for (rx,ry) in reds:
        if rx < bx and ry < by:
            candidates.append((rx,ry))
    if candidates:
        candidates.sort(key = lambda x: -x[1])
        ans += 1
        reds.remove(candidates[0])
    
print(ans)

Measured memory_bytes: 3192
#include<iostream>
using namespace std;
int main(){
    string x;
    while(1){
      cin >> x;
      if (x == "0") break;
      int n = 0;
      for(int i = 0; i < x.length(); i++){
        n += x[i] - '0';
      }
      cout<<n<<endl;
    }
    return 0;
}


Measured memory_bytes: 3236
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys,collections,itertools,re,math,fractions,decimal,random,array,bisect,heapq

# decimal.getcontext().prec = 50
# sys.setrecursionlimit(10000)
# MOD = 10**9 + 7

def solve(f):
    n = f.read_int()
    d = collections.defaultdict(int)
    for _ in xrange(n):
        s = f.read_str()
        ss = "".join(sorted(list(s)))
        d[ss] += 1

    ans = 0
    for k, v in d.items():
        ans += v*(v-1)/2

    return ans


class Reader(object):
    def __init__(self, filename=None):
        self.file = open(filename) if filename is not None else None
        self.case = 1

    def __readline(self):
        return self.file.next().strip() if self.file else raw_input()

    def next_case(self):
        self.file.next()
        self.case += 1

    def read_int(self): return int(self.__readline())
    def read_float(self): return float(self.__readline())
    def read_long(self): return long(self.__readline())
    def read_decimal(self): return decimal.Decimal(self.__readline())
    def read_str(self): return self.__readline()

    def read_int_list(self): return map(int, self.__readline().split())
    def read_float_list(self): return map(float, self.__readline().split())
    def read_long_list(self): return map(long, self.__readline().split())
    def read_decimal_list(self): return map(decimal.Decimal, self.__readline().split())
    def read_str_list(self): return self.__readline().split()

if __name__ == '__main__':
    filename = sys.argv[1] if len(sys.argv) > 1 else None
    f = Reader(filename)
    if f.file:
        while True:
            print "Case #%d\n"%f.case, solve(f)
            try:
                f.next_case()
            except StopIteration:
                break
    else:
        print solve(f)


Measured memory_bytes: 57112
#include <bits/stdc++.h>
#define fi first
#define se second

using namespace std;
using pii=pair<int,int>;
const int mxn = 1e5+10;
pii arr[mxn];

int main() {
    int n, m;
    cin >> n >> m;
    for(int i=0; i<n; i++) {
        cin >> arr[i].fi >> arr[i].se;
    }
    sort(arr, arr+n);
    long long sum=0;
    for(int i=0; (i<n) && m; i++) {
        for(; arr[i].se-- && m;) sum+=arr[i].fi, m--;
    } cout << sum;
    return 0;
}


Measured memory_bytes: 1152
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <cstring>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <iterator>
#include <bitset>
#include <ctime>
#include<complex>
#include<unordered_set>
using namespace std;

#define FOR(i,a,b) for(int i = (a); i < (b); i++)
#define RFOR(i,b,a) for(int i = (b) - 1; i >= (a); i--)
#define ITER(it, a) for(typeof(a.begin()) it = a.begin(); it != a.end(); it++)
#define FILL(a, value) memset(a, value, sizeof(a))

#define SZ(a) (int) a.size()
#define ALL(a) a.begin(),a.end()
#define PB push_back
#define MP make_pair

typedef long long LL;
typedef vector<int> VI;
typedef pair<int, int> PII;

const double PI = acos(-1.0);
const LL INF = 1000 * 1000 * 1000 + 7;
const LL LINF = INF * (LL)INF;

const int MOD = 1000 * 1000 * 1000 + 7;

const int MAX = 100 + 47;

string A[MAX];
int CNT[MAX];

bool canTake(int k, int cnt)
{
	FOR(i, 0, 26)
	{
		if (cnt == 0) break;
		while (CNT[i] >= k)
		{
			if (cnt == 0) break;
			CNT[i] -= k;
			cnt--;
		}
	}

	return cnt == 0;
}

void yes()
{
	cout << "Yes" << endl;
	exit(0);
}

void no()
{
	cout << "No" << endl;
	exit(0);
}

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	//ios::sync_with_stdio(false); cin.tie(0);
	int n, m, k;
	cin >> n >> m >> k;
	FOR(i, 0, n + 1)
	{
		FOR(j, 0, m + 1)
		{
			if (i * m + j * n - 2 * i * j == k)
			{
				cout << "Yes" << endl;
				return 0;
			}
		}
	}

	cout << "No" << endl;
}

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

int compare(const void *a,const void *b){
  return *(char*)a - *(char*)b;
}

int revcompare(const void *a,const void *b){
  return *(char*)b - *(char*)a;
}
int main(){
  char s[100] = {};
  char t[100] = {};
  int scnt = 0;
  int tcnt = 0;
  int i = 0;
  int j = 0;
  int flag = 0;
  
  scanf(" %s",s);
  scanf(" %s",t);
  for(i=0;i<100;i++){
    if(s[i]!='\0'){
      scnt++;
    }else{
      break;
    }
  }
  
  for(i=0;i<100;i++){
    if(t[i]!='\0'){
      tcnt++;
    }else{
      break;
    }
  }
  
  qsort(s,scnt,sizeof(char),compare);
  qsort(t,tcnt,sizeof(char),revcompare);

  flag = 0;
  if(scnt < tcnt){
    for(i=0;i<scnt;i++){
      if(s[i] > t[i]){
        flag  = -1;
        break;
      }else if(s[i] < t[i]){
        flag = 1;
        break;
      }
    }
    if(flag == 0){
      flag = 1;
    }
  }else{
    for(i=0;i<tcnt;i++){
      if(s[i] > t[i]){
        flag  = -1;
        break;
      }else if(s[i] < t[i]){
        flag = 1;
        break;
      }
    }
    if(flag == 0){
      flag = -1;
    }
  }
  if(flag == 1){
    printf("Yes");
  }else{
    printf("No");
  }
  return 0;
}
  
  

Measured memory_bytes: 128
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;
using ll = long long;
using pii = pair<int,int>;
const long long INF = 1LL << 60;

int x;

int main()
{
  rep(i,5)
  {
    cin >> x;
    if(x == 0) cout << i+1 << endl;
  }
}

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

int main(){
    int n; cin >> n;
    string S; cin >> S;
    vector <int> white_cnt(n);

    int max_white = 0;

    for (auto c: S){
        if (c == '.') max_white += 1;
    }

    rep(i, n){
        white_cnt.at(i) = max_white;
        if(S.at(i) == '.') max_white -= 1;
    }
    white_cnt.push_back(0);

    int black_cnt = 0;
    int ans = 10000000;

    rep(i, n + 1){
        int _ans;
        _ans = black_cnt + white_cnt.at(i);
        ans = min(ans, _ans);

        if(i == n) break;
        if (S.at(i) == '#') black_cnt += 1;
    }

    cout << ans << endl;

}

Measured memory_bytes: 5240
#include <bits/stdc++.h>
#define syosu(x) fixed<<setprecision(x)
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int,int> P;
typedef pair<double,double> pdd;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<string> vs;
typedef vector<P> vp;
typedef vector<vp> vvp;
typedef vector<pll> vpll;
typedef pair<int,P> pip;
typedef vector<pip> vip;
const int inf=1<<30;
const ll INF=1ll<<60;
const double pi=acos(-1);
const double eps=1e-9;
const ll mod=1e9+7;
const int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};

ll n,x,d;

ll f(ll m,ll t){
	if(m>=0) return m/d;
	return -((-m-1)/d)-1;
}

int main(){
	cin>>n>>x>>d;
	if(d==0){
		if(x==0) cout<<1<<endl;
		else cout<<n+1<<endl;
		return 0;
	}
	if(d<0){
		d*=-1;
		x*=-1;
	}
	ll mn=0,mx=0,id=0;
	map<ll,ll> mp;
	vector<vpll> a;
	for(int i=0;i<=n;i++){
		int t;
		if(mn>=0) t=mn%d;
		else t=(mn-mn/d*d+d)%d;
		assert(0<=t&&t<d);
		if(mp.find(t)==mp.end()){
			mp[t]=id++;
			a.push_back(vpll());
		}
//		cout<<t<<' '<<mn<<' '<<mx<<' '<<f(mn,t)<<' '<<f(mx,t)<<endl;
		a[mp[t]].push_back({f(mn,t),f(mx,t)});
		mn+=x+d*i;
		mx+=x+d*(n-i-1);
	}
	ll res=0,m=a.size();
	for(int i=0;i<m;i++){
		sort(a[i].begin(),a[i].end());
		mx=-INF;
		ll tmp=0;
//		set<int> st;
		for(auto p:a[i]){
//			cout<<p.first<<' '<<p.second<<endl;
			if(mx<p.first){
				tmp+=p.second-p.first+1;
				mx=p.second;
			}
			else if(mx<p.second){
				tmp+=p.second-mx;
				mx=p.second;
			}
//			for(int j=p.first;j<=p.second;j++) st.insert(j);
//			cout<<mx<<' '<<tmp<<endl;
		}
//		cout<<tmp<<endl;
//		cout<<st.size()<<endl;
		res+=tmp;
	}
//	cout<<st.size()<<endl;
	cout<<res<<endl;
}

Measured memory_bytes: 24492