akhauriyash/Code-Regression huggingface dataset:
#include "bits/stdc++.h"
#define in std::cin
#define out std::cout
#define rep(i,N) for(LL i=0;i<N;++i)
typedef long long int LL;

int main()
{
	std::string s;
	in >> s;

	std::string t;
	s += "#";
	rep(i, s.length())
	{
		if (s[i] == 'B' && s[i + 1] == 'C')
		{
			t += 'X';
			++i;
		}
		else t += s[i];
	}

	LL ans = 0, cnt = 0;
	rep(i, t.length())
	{
		if (t[i] == 'A') ++cnt;
		else if (t[i] == 'X') ans += cnt;
		else cnt = 0;
	}

	out << ans << std::endl;
}


Measured memory_bytes: 776
program sample
    implicit none
    character(100)::s,t
    integer(8) :: i,j,k,m,n
    integer(8)::a,b,c,d
    integer(8),allocatable::x(:),y(:)
  
    read(*,*) n
    allocate(x(n),y(n))
    read(*,*)x
    call msort(x)
    y(:)=x(:)
    a=n/2
    b=n/2
if(x(n)>0 .and. x(1)<0)then
    do i=1,n
        if(x(i)>=0)then
            a=i-1
            exit
        end if
    end do
    do i=a+1,n-1
        x(1)=x(1)-x(i)
    end do
    do i=1,a
       
        x(n)=x(n)-x(i)
    end do
    write(*,*)x(n)
    x(1)=y(1)
    x(n)=y(n)
    do i=a+1,n-1
        write(*,*)x(1),x(i)
        x(1)=x(1)-x(i)
    end do
    do i=1,a
        write(*,*)x(n),x(i)
        x(n)=x(n)-x(i)
    end do
    
elseif(x(n)<=0)then
    write(*,*)-1*sum(x)+x(n)*2
    do i=1,n-1
        write(*,*)x(n),x(i)
        x(n)=x(n)-x(i)
    enddo
elseif(x(1)>=0)then
    write(*,*)sum(x)-x(1)*2
    do i=2,n-1
        write(*,*)x(1),x(i)
        x(1)=x(1)-x(i)
    end do
    write(*,*)x(n),x(1)
end if
    
   
    stop
    contains
    recursive subroutine msort(x)
    implicit none
    integer(8), intent(inout) :: x(:)
 
    integer(8) :: n, mid, i, j, k
    integer(8), allocatable :: tmp(:)
    
    n = size(x)
    
    if(n == 1) then
      return
    end if
 
    !
    ! 前半と後半に分けてソート
    ! 1~midとmid+1~nをそれぞれソート済みにする
    !
    mid = n / 2
    call msort(x(:mid))
    call msort(x(mid+1:))
 
    !
    ! tmpという配列にxを一時的に保管
    ! マージソートは外部ソート
    !
    allocate(tmp(n))
    tmp = x
 
    ! tmpの後半部分を左右反転
    do k = n, mid+1, -1
      tmp(k) = x(mid + n - k + 1)
    end do
 
    ! iは前半のリストのうちまだ見ていないものの最小値
    ! jは後半のリストのうちまだ見ていないものの最小値
    ! kは見た回数の合計
    i = 1
    j = n
 
    do k = 1, n
      !
      ! 一番左と一番右のうち小さい方をxに入れていく
      ! ここが等号つき不等号なので、安定ソートとなる
      !
      if(tmp(i) <= tmp(j)) then
        x(k) = tmp(i)
        i = i + 1
      else
        x(k) = tmp(j)
        j = j - 1
      end if
    end do
    
    deallocate(tmp)
    return
  end subroutine msort
end program sample
  



Measured memory_bytes: 7220
// ABC054B - 

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

typedef unsigned long long int ull;
typedef long long int ll;

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

	string A[N];
	for (int i = 0; i < N; i++) {
		cin >> A[i];
	}
	string B[M];
	for (int i = 0; i < M; i++) {
		cin >> B[i];
	}

	for (int i = 0; i < N - M + 1; i++) {
		for (int j = 0; j < N - M + 1; j++) {
			bool temp = true;
			for (int k = 0; k < M; k++){
				if (A[k + i].substr(j, M) != B[k]) {
					temp = false;
					break;
				}
			}
			if (temp == true) {
				cout << "Yes" << endl;
				return 0;
			}
		}
	}

	cout << "No" << endl;

	return 0;
}


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

int main() {
  int n, answer, tmp;
  cin >> n;
  answer = 0;
  tmp = n + 1;
  
  for (int i = 0; i < n; i++) {
    int p;
    cin >> p;
    if (tmp > p) {
      tmp = p;
      answer++;
    }
  }
  cout << answer << endl;
}

Measured memory_bytes: 256
A = [None]*3
A[0] = list(map(int, input().split()))
A[1] = list(map(int, input().split()))
A[2] = list(map(int, input().split()))
N = int(input())
B = [None]*N
for i in range(N):
    B[i] = int(input())

for i in range(N):
    for j in range(3):
        for k in range(3):
            if B[i] == A[j][k]:
                A[j][k] = -1


S1 = 0
S2 = 0
for i in range(3):
    S1 += A[i][i]
    S2 += A[i][2-i]
if S1 == -3 or S2 == -3:
    print("Yes")
    quit()

for i in range(3):
    if sum(A[i]) == -3:
        print("Yes")
        break
    if A[0][i] + A[1][i] + A[2][i] ==-3:
        print("Yes")
        break
else:
    print("No")

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

int main() {
    int n;cin>>n;
    map<string,int> m;
    ll ans=0;
    for (int i=0;i<n;i++) {
        string s;cin>>s;
        sort(s.begin(),s.end());
        ans+=m[s];
        m[s]++;
    }
    cout<<ans<<endl;
}

Measured memory_bytes: 11136
INFTY = 10**4+10
H,W = map(int,input().split())
C = [list(map(int,input().split())) for _ in range(10)]
cost = [[INFTY for _ in range(10)] for _ in range(10)]
for i in range(10):
    for j in range(10):
        cost[i][j] = C[i][j]
for k in range(10):
    for i in range(10):
        for j in range(10):
            cost[i][j] = min(cost[i][j],cost[i][k]+cost[k][j])
A = [list(map(int,input().split())) for _ in range(H)]
tot = 0
for i in range(H):
    for j in range(W):
        if A[i][j]==1 or A[i][j]==-1:continue
        tot += cost[A[i][j]][1]
print(tot)

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

int main(){
    int n,x;
    
    while (true){
        cin >> n >> x;
        if (n==0 && x==0) break;
        int cnt=0;
        for (int i=1; i<=n-2; i++){
            for (int j=i+1; j<=n-1; j++){
                for (int k=j+1; k<=n; k++){
                    if (x==i+j+k) cnt++;
                }
            }
        }
        cout << cnt << "\n";
    }
    return 0;
}


Measured memory_bytes: 3084
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<math.h>
#include<stdlib.h>
#include<string>
#include<iostream>
#include<set>
#include<map>
#include<deque>
using namespace std;
typedef long long ll;
typedef pair<ll, ll>pii;
typedef pair<pii, ll>pi3;
ll mod = 1000000007;
int d[1000];
int main()
{
	string s;
	cin >> s;
	for (int i = 0; i < s.size(); i++)d[s[i]] ^= 1;
	int x = 0;
	for (int i = 'a'; i <= 'z'; i++)x += d[i];
	printf(x ? "No\n" : "Yes\n");
}

Measured memory_bytes: 256
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
//            while (true)// MAKE SURE TO REMOVE THIS
                solve(in);
        }
    }

    private static void solve(Scanner in) {
        int N = in.nextInt();
        String S = in.next();
        int x = 0;
        int max = 0;
        for (int i = 0; i < N; i++) {
            x += S.charAt(i) == 'I' ? 1 : (-1);
            max = max > x ? max : x;
        }
        System.out.println(max);
    }
}

Measured memory_bytes: 9044
#include  <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define inf 1000000007
//P pa(114,514);   ,vector<P>vec(N,0);
//vector<vector<int>> vec(縦, vector<int>(横));
#define REP(i,N) for(int i=0;i<N;i++)
int gcd(int a, int b) {
    if(a>b){
        swap(a,b);
        }
    while(b%a!=0){
        b%=a;
        swap(a,b);
    }
    return a;
}
//cout << setprecision(123);
//a=atoi(S.c_str());
//S=to_string(a);
int main(){
  int a,b;
  cin>>a>>b;
  if(a<10&&b<10){
    cout<<a*b<<endl;
  }
  else{
    cout<<-1<<endl;
  }
}

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

typedef long long ll;
#define vec vector<int>
#define vecll vector<ll>
#define vpair vector<pair<int, int>>
#define vpairll vector<pair<ll, ll>>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define rep(i,n)   for(int i=(int)0; i<(int)n; i++)
#define llrep(i,n)   for(ll i=(ll)0; i<(ll)n; i++)
#define REP(i,m,n) for(int i=(int)m; i<(int)n; i++)
#define all(var)     (var).begin(), (var).end()
#define prt(var)     cout << var << endl
#define prt_dbl(i,var) cout<<fixed<<setprecision(i)<<var<<endl;

//---------------------------------------------------------------

int main(){
  int N,R,ans;
  cin>>N>>R;
  if(N<10){
    ans =R+100*(10-N);
  }else{
    ans = R;
  }

  cout<<ans<<endl;

}


Measured memory_bytes: 256
#include<bits/stdc++.h>
#define ll long long int
#define ul unsigned long long int
#define mp make_pair
#define endl "\n"
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);
#define lb lower_bound
#define forn(i,n) for(ll i=0 ; i<n ; i++)
#define arr(a,n) for(ll i=0;i<n;i++){ cin>>a[i]; }
#define ub upper_bound
#define pb push_back
#define pi pair<int,int>
#define mod 1000000007
#define vectormax *max_element
#define vectormin *min_element
#define arraysize 1000000
#define setbit _builtin_popcountll
using namespace std;


ll ipow(ll x, ll n)
{
    ll result = 1;
    while (n) {
        if (n & 1)
            result = result * x ;
        n = n / 2;
        x = x * x;
    }
    return result;
}
const int MAX = 1000001; 
  
// array to store prime factors 
int factor[MAX] = { 0 }; 
  
// function to generate all prime factors 
// of numbers from 1 to 10^6 
void generatePrimeFactors() 
{ 
    factor[1] = 1; 
  
    // Initializes all the positions with their value. 
    for (int i = 2; i < MAX; i++) 
        factor[i] = i; 
  
    // Initializes all multiples of 2 with 2 
    for (int i = 4; i < MAX; i += 2) 
        factor[i] = 2; 
  
    // A modified version of Sieve of Eratosthenes to 
    // store the smallest prime factor that divides 
    // every number. 
    for (int i = 3; i * i < MAX; i++) { 
        // check if it has no prime factor. 
        if (factor[i] == i) { 
            // Initializes of j starting from i*i 
            for (int j = i * i; j < MAX; j += i) { 
                // if it has no prime factor before, then 
                // stores the smallest prime divisor 
                if (factor[j] == j) 
                    factor[j] = i; 
            } 
        } 
    } 
} 
  
// function to calculate number of factors 
int calculateNoOFactors(int n) 
{ 
    if (n == 1) 
        return 1; 
  
    int ans = 1; 
  
    // stores the smallest prime number 
    // that divides n 
    int dup = factor[n]; 
  
    // stores the count of number of times 
    // a prime number divides n. 
    int c = 1; 
  
    // reduces to the next number after prime 
    // factorization of n 
    int j = n / factor[n]; 
  
    // false when prime factorization is done 
    while (j != 1) { 
        // if the same prime number is dividing n, 
        // then we increase the count 
        if (factor[j] == dup) 
            c += 1; 
  
        /* if its a new prime factor that is factorizing n,  
           then we again set c=1 and change dup to the new  
           prime factor, and apply the formula explained  
           above. */
        else { 
            dup = factor[j]; 
            ans = ans * (c + 1); 
            c = 1; 
        } 
  
        // prime factorizes a number 
        j = j / factor[j]; 
    } 
  
    // for the last prime factor 
    ans = ans * (c + 1); 
  
    return ans; 
} 
int main() {
	
	int n;
	cin>>n;
	  generatePrimeFactors(); 
	//int temp=n-1;
	long sum=0;
	//cout<<calculateNoOFactors(4)<<endl;
	for(int i=1;i<n;i++){
		 sum+=calculateNoOFactors(i);
	}
	cout<<sum<<endl;
return 0;
}


Measured memory_bytes: 7520
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=2e5+10;
#define fi first
#define se second
#define pb push_back
int main() {
    set<int>x;
    ios::sync_with_stdio(false);
    for(int i=1;i<=3;i++)x.insert(i);
    for(int i=1;i<=2;i++){
        int y;
        cin>>y;
        x.erase(y);
    }
    cout<<*x.begin();
    return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,n) for(int i=0;i<(n);i++)
#define RREP(i,n) for(int i=(n)-1;i>=0;i--)
using namespace std;

int main()
{
    string w;
    cin >> w;
    int al[26];
    REP(i, 26){
        al[i] = 0;
    }
    REP(i, w.size()){
        al[w[i] - 'a']++;
    }
    REP(i, 26){
        if(al[i] % 2 == 1){
            printf("No\n");
            return 0;
        }
    }
    printf("Yes\n");
    return 0;
}

Measured memory_bytes: 256
import sys
sys.setrecursionlimit(1000000000)
ii = lambda: int(input())
mis = lambda: map(int,input().split())
lmis = lambda: list(mis())
INF = float('inf')

def main():
    N=ii()
    L=sorted(lmis(),reverse=True)
    ans=0
    for i in range(N-2):
        a=L[i]
        j=i+1
        k=N-1
        while j<k:
            if a<L[j]+L[k]:
                j+=1
                ans+=k-j+1
            else:
                k-=1
    print(ans)


if __name__ == "__main__":
    main()

Measured memory_bytes: 3188
a = [[0,0,0],[0,0,0],[0,0,0]]
for i in range(3):
  a[i] = list(map(int, input().split()))
 
n = int(input())
bs = [int(input()) for _ in range(n)]

for i in range(3):
  for j in range(3):
    for b in bs:
      if a[i][j] == b:
        a[i][j] = 0
y = "Yes"
c = "No"
for i in range(3):
  if a[0][i] == 0 and a[1][i] == 0 and a[2][i]==0:
    c = y
    break
  elif a[i][0]==0 and a[i][1] == 0 and a[i][2]==0:
    c = y
    break
  elif a[0][0]==0 and a[1][1]==0 and a[2][2]==0:
    c = y
    break
  elif a[0][2]==0 and a[1][1]==0 and a[2][0]==0:
    c = y
    break
print(c)

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

int main(){
  string S;
  cin>>S;
  sort(S.begin(),S.end());
  int cnt=0;
  int ans=0;
  char pre = 'a';
  for(int i=0; i<S.length(); i++){
    if(S[i]==pre){
      //cout<<"同じ"<<endl;
    }else if(S[i]==pre+1){
      //cout<<"次"<<endl;
    }else{
      ans=pre+1;
      break;
    }
    pre=S[i];
  }
  if(S[0]!='a'){
    cout<<'a'<<endl;
  }else if(pre!='z'){
    cout<<(char)(pre+1)<<endl;
  }else if(ans>0){
    cout<<(char)(ans)<<endl;
  }else{
    cout<<"None"<<endl;
  }
  return 0;
}


Measured memory_bytes: 512
use std::io::{stdin, Read};

#[allow(unused_macros)]
macro_rules! parse {
    ($it: ident ) => {};
    ($it: ident, ) => {};
    ($it: ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = parse_val!($it, $t);
        parse!($it $($r)*);
    };
    ($it: ident, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = parse_val!($it, $t);
        parse!($it $($r)*);
    };
}

#[allow(unused_macros)]
macro_rules! parse_val {
    ($it: ident, [$t:tt; $len:expr]) => {
        (0..$len).map(|_| parse_val!($it, $t)).collect::<Vec<_>>();
    };
    ($it: ident, ($($t: ty),*)) => {
        ($(parse_val!($it, $t)),*)
    };
    ($it: ident, $t: ty) => {
        $it.next().unwrap().parse::<$t>().unwrap()
    };
}

fn solve(s: &str) {
    let mut it = s.split_whitespace();
    parse!(it, n: usize);
    let mut g = vec![vec![]; n];
    for _ in 0..(n - 1) {
        parse!(it, a: usize, b: usize);
        g[a - 1].push(b - 1);
        g[b - 1].push(a - 1);
    }
    let mut types = vec![false; n];
    let mut q = std::collections::VecDeque::new();
    q.push_back((0, false));
    let mut seen = vec![false; n];
    seen[0] = true;
    while let Some((u, t)) = q.pop_front() {
        types[u] = t;
        for &v in g[u].iter() {
            if !seen[v] {
                q.push_back((v, !t));
                seen[v] = true;
            }
        }
    }
    let neven = types.iter().filter(|x| !**x).count();
    let nodd = n - neven;
    let majority = neven < nodd;
    let (na, nb) = if majority {
        (nodd, neven)
    } else {
        (neven, nodd)
    };
    let nac = n / 3 + if n % 3 != 0 { 1 } else { 0 };
    let nbc = n / 3 + if n % 3 == 2 { 1 } else { 0 };
    let mut ret = vec![0; n];
    let mut cura = 1;
    let mut curb = 2;
    let mut curc = 3;
    if nbc <= nb {
        for i in 0..n {
            let cur = if types[i] == majority {
                if cura <= n {
                    &mut cura
                } else {
                    &mut curc
                }
            } else {
                if curb <= n {
                    &mut curb
                } else {
                    &mut curc
                }
            };
            ret[i] = *cur;
            *cur += 3;
        }
    } else {
        for i in 0..n {
            let cur = if types[i] == majority {
                if cura <= n {
                    &mut cura
                } else if curb <= n {
                    &mut curb
                } else {
                    &mut curc
                }
            } else {
                &mut curc
            };
            ret[i] = *cur;
            *cur += 3;
        }
    }
    println!(
        "{}",
        ret.iter()
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join(" ")
    );
}

fn main() {
    let mut s = String::new();
    stdin().read_to_string(&mut s).unwrap();
    solve(&s);
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_input() {
        let s = "
        ";
        solve(s);
    }
}


Measured memory_bytes: 39396
#include <bits/stdc++.h>
using namespace std;
#define debug(x) cout << #x " = " << (x) << '\n';
#define P(x) cout << #x << '\n';    
#define int long long
typedef pair<int, int> pii;
const int mod = 1000000007;
 
int modpow(int x, int y, int p = mod) 
{ 
	int res = 1;       
	x %= p;   
	while (y > 0) 
	{ 
		if (y & 1) 
			res = (res * x) % p; 
		y >>= 1;
		x = (x * x) % p;   
	} 
	return res; 
} 
int add(int x, int y) 
{
	x += y;
	if (x >= mod) return x - mod;
	return x;
}
int sub(int x, int y) 
{
	x -= y;
	if (x < 0) return x + mod;
	return x;
}
int inv(int a, int m = mod)
{
	return modpow(a, m - 2, m);
}
int mul(int a, int b) 
{
	return (long long) a * b % mod;
}
 
const int maxn = 1e5 + 10;
int fac[maxn], invfac[maxn];
int ncr(int n, int r)
{
	int ans = mul(fac[n], mul(invfac[r], invfac[n - r]));
	return ans;
}
 
 
int a[maxn], pre[maxn], suf[maxn];
 
int32_t main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout << fixed << setprecision(9);
	#ifdef LOCAL_DEFINE
		freopen("in.txt", "rt", stdin);
	#endif
	
	fac[0] = invfac[0] = 1;
	for(int i = 1; i < maxn; ++ i)
	{
		fac[i] = mul(i, fac[i - 1]);
		invfac[i] = inv(fac[i]);
	}
	
	int n, k;
	cin >> n >> k;
	for(int i = 1; i <= n; ++ i)
	{
		cin >> a[i];
	}
	sort(a + 1, a + n + 1);
	for(int i = 1; i <= n; ++ i)
		pre[i] = add(pre[i - 1], a[i]);
	for(int i = n; i >= 1; -- i)
		suf[i] = add(a[i], suf[i + 1]);
	
	int ans = 0;
	
	for(int i = 1; i <= n; ++ i)
	{
		int bef = i - 1;
		int aft = n - i;
		int to = k - 1;
		if(a[i] < 0) a[i] += mod;
		if(aft >= to)
		{
			int mini = mul(ncr(aft, to), a[i]);
			ans = sub(ans, mini);
		}
		if(bef >= to)
		{
			int maxi = mul(ncr(bef, to), a[i]);
			ans = add(ans, maxi);
		}
	}
	cout << ans << '\n';
	
	return 0;
}
 

Measured memory_bytes: 4224
#include <stdio.h>
#define MAX 250
#define NIL -2000000001
int key[MAX];
int parent(int c);
int right(int c);
int left(int c);
int main(){
  int i, n, h;
  scanf("%d", &n);
  for(i = 0; i < MAX; i++){
    key[i] = NIL;
}
  for(i = 0; i < n; i++){
    scanf("%d", &h);
    key[i] = h;
}
  for(i = 0; i < n; i++){
    printf("node %d: key = %d, ", i+1, key[i]);
    if(key[parent(i)] != NIL && i != 0){
      printf("parent key = %d, ",key[parent(i)]);
    }
    if(MAX > left(i) &&  key[left(i)] != NIL){
      printf("left key = %d, ",key[left(i)]);
    }
    if(MAX > right(i) && key[right(i)] != NIL){
      printf("right key = %d, ",key[right(i)]);
    }
    printf("\n");
  }
return 0; }
int parent(int c){
  return (c-1)/2;
}
int right(int c){
  return 2*c+2;
}
int left(int c){
  return 2*c+1;
}



Measured memory_bytes: 2112
n = int(input())
rl = [0]*n

for i in range(n):
  rl[i] = input().split()
  
ans = []

for i in range(n):
  c = 0
  c = int(rl[i][1]) - int(rl[i][0]) + 1
  ans.append(c)
  
print(sum(ans))


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

int main() {
  int n;
  size_t o;
  string line;
  cin >> n;
  getline(cin, line);
  for (int i=0; i<n; i++) {
    getline(cin, line);
    o = 0;
    while (1) {
      o = line.find("Hoshino", o);
      if (o == string::npos) break;
      line.replace(o, 7, "Hoshina");
    }
    cout << line << endl;
  }
  return 0;
}

Measured memory_bytes: 1208
#include <stdio.h>
int main()
{
	char b;
	scanf("%c",&b);
	if(b=='A')
	{
		printf("T");
	}
	if(b=='T')
	{
		printf("A");
	}
	if(b=='C')
	{
		printf("G");
	}
	if(b=='G')
	{
		printf("C");
	}
	
	return 0;
}

Measured memory_bytes: 128
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
using vin=vector<int>;
using vll=vector<long long>;
using vvin=vector<vector<int>>;
using vvll=vector<vector<long long>>;
using vstr=vector<string>;
using vvstr=vector<vector<string>>;
using vch=vector<char>;
using vvch=vector<vector<char>>;
using vbo=vector<bool>;
using vvbo=vector<vector<bool>>;
using vpii=vector<pair<int,int>>;
using pqsin=priority_queue<int,vector<int>,greater<int>>;
#define mp make_pair
#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++)
#define all(v) v.begin(),v.end()
#define decp(n) cout<<fixed<<setprecision((int)n)
const int inf=1e9+7;
const ll INF=1e18;

//Marked Ancestor(AOJ)
//http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2170&lang=en
//about 45min
//参考解答 http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=584073#1
//union findでmarkされた親に対してそれらの子のうちmarkされていない子をもつことで, queryを後から見ていけばmarkの消失⇔そのnodeとそのnodeの親との結合で表現できるところが賢いなぁと。

vin par(100050);
void init(int n);
int root(int x);
void unite(int x,int y);
bool same(int x,int y);

ll ancestor(int n,int q){
    vin parent(n+1);parent[1]=1;
    rep2(i,2,n+1)cin>>parent[i];
    vch ope(q);
    vin v(q),marked(n+1,0);marked[1]=1;
    rep(i,q){
        cin>>ope[i]>>v[i];
        if(ope[i]=='M')marked[v[i]]++;
    }
    init(n);
    rep2(i,1,n+1){
        if(marked[i]==0)unite(i,parent[i]);//parent[i]を親にしてunite
    }
    ll res=(ll)0;
    for(int i=q-1;i>=0;i--){
        if(ope[i]=='Q')res+=(ll)root(v[i]);
        else if(--marked[v[i]]==0)unite(v[i],parent[v[i]]);
    }
    return res;
}

int main(){
    int n,q;
    queue<ll> ans;
    while(1){
        cin>>n>>q;
        if(n==0)break;
        ans.push(ancestor(n,q));
    }
    while(ans.size()){
        cout<<ans.front()<<endl;
        ans.pop();
    }
}

void init(int n){
    rep(i,n+1)par[i]=i;
}
int root(int x){
    if(par[x]==x)return x;
    else return par[x]=root(par[x]);
}
void unite(int x,int y){//deepを考慮しない
    x=root(x);
    y=root(y);
    if(x==y)return;
    par[x]=y;
}
bool same(int x,int y){
    return root(x)==root(y);
}


Measured memory_bytes: 4432
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cmath>
#include <numeric>
using namespace std;


int main(){
    int a,b,c,k ;
    cin >> a >> b >> c >> k ;
    int ans = 0 ;
    if (a >= k)
    {
        ans = k ;
    }else
    {
        ans += a ;
        k -= a ;
        if (b < k)
        {
            k -= b ;
            ans -= k ;
        }
        
    }
    
    cout << ans << endl ;
}


Measured memory_bytes: 3640
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program
{
    int N, Q;
    int[] markCount;
    int[] parent;

    void Solve()
    {
        while (true)
        {
            N = read.Int();
            Q = read.Int();
            if (N == 0) break;
            markCount = new int[N + 1];
            parent = new int[N + 1];
            markCount[1] = 1;

            for (int i = 2; i <= N; i++)
            {
                parent[i] = read.Int();
            }
            var isQuery = new bool[Q];
            var index = new int[Q];
            for (int i = 0; i < Q; i++)
            {
                isQuery[i] = read.String() == "Q";
                index[i] = read.Int();
                if (!isQuery[i]) markCount[index[i]]++;
            }
            long ans = 0;
            for (int i = Q - 1; i >= 0; i--)
            {
                if (isQuery[i]) { ans += GetParent(index[i]); }
                else { markCount[index[i]]--; }
            }
            Console.WriteLine(ans);
        }
    }

    int GetParent(int i)
    {
        if (markCount[i] > 0) return i;
        return parent[i] = GetParent(parent[i]);
    }


    static void Main() { new Program().Solve(); }
    static Read read = new Read(Console.In);
    class Read
    {
        private readonly TextReader reader;
        public Read(TextReader r) { reader = r; }
        private Queue<string> que = new Queue<string>();
        public string String() { return Dequeue(); }
        public int Int() { return int.Parse(Dequeue()); }
        public long Long() { return long.Parse(Dequeue()); }
        public double Double() { return double.Parse(Dequeue()); }
        public int[] IntArray() { return Array.ConvertAll(Line().Split(), int.Parse); }
        public int[][] IntGrid(int H) { return Enumerable.Range(0, H).Select(i => IntArray()).ToArray(); }
        public string[] StringArray(int N) { return Enumerable.Range(0, N).Select(i => Line()).ToArray(); }
        public string Line() { return reader.ReadLine().Trim(); }
        private string Dequeue()
        {
            if (que.Count == 0) foreach (var s in Line().Split()) que.Enqueue(s);
            return que.Dequeue();
        }
    }
}

Measured memory_bytes: 11020
parseInt(x) = parse(Int, x)
parseBigInt(x) = parse(BigInt, x)
parseFloat(x) = parse(Float64, x)
parseBigFloat(x) = parse(BigFloat, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
    k=parseInt(readline())
    s=readline()
    if length(s)<=k
        println(s)
    else
        println(s[1:k]*"...")
    end
end
main()

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

int main()
{
    int n;
    char s[10001] = {};
    cin >> n >> s;
    int lung = strlen(s);
    for (int i = 0; i < lung; ++i)
    {
        s[i] = s[i] + n;
        if (s[i] > 'Z') s[i] = 'A' + s[i] - 'Z' - 1;
    }
    cout << s;
    return 0;
}


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

from pprint import pprint
from collections import deque, defaultdict
import itertools
import math
import sys

sys.setrecursionlimit(10 ** 6)
INF = float('inf')


N = int(input())


def g(x, y, z):
    return (x + y + z) ** 2 - (x*y + y*z + z*x)


xyz_dict = defaultdict(int)
num_dict = defaultdict(int)
for x in range(1, 100):
    for y in range(1, 100):
        for z in range(1, 100):
            num = g(x, y, z)
            if (x, y, z) in xyz_dict:
                continue
            xyz_dict[(x, y, z)] = 1
            num_dict[num] += 1


for n in range(1, N+1):
    print(num_dict[n])


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

using namespace std;

int n, pos;
vector<int> pre, in, post;

void rec(int l, int r)
{
  if (l >= r)
  {
    return;
  }
  int root = pre[pos++];
  int m = distance(in.begin(), find(in.begin(), in.end(), root));
  rec(l, m);
  rec(m + 1, r);
  post.push_back(root);
}

void solve()
{
  pos = 0;
  rec(0, pre.size());
  for (int i = 0; i < n; i++)
  {
    if (i)
    {
      cout << " ";
    }
    cout << post[i];
  }
  cout << endl;
}

int main()
{
  int k;
  cin >> n;
  for (int i = 0; i < n; i++)
  {
    cin >> k;
    pre.push_back(k);
  }
  for (int i = 0; i < n; i++)
  {
    cin >> k;
    in.push_back(k);
  }

  solve();
  return 0;
}



Measured memory_bytes: 3180
n=gets.to_i
a=Array.new(2).map{Array.new(n,0)}
2.times do |i|
    a[i]=gets.split.map(&:to_i)
end

ans=a[0].sum+a[1][n-1]
cur=a[0].sum+a[1][n-1]
(n-1).downto(1) do |i|
    cur=cur-a[0][i]+a[1][i-1]
    ans=[ans, cur].max
end
puts ans


Measured memory_bytes: 14292
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
 
int main() {
  int n,m;
  cin >>n>>m;
  priority_queue<int> q;
  rep(i,n){
    int a;
    cin>>a;
    q.push(a);
  }
  rep(i,m){
    int a=q.top();q.pop();
    q.push(a/2);
  }
  long long sum=0;
  rep(i,n){
    sum+=q.top();q.pop();
  }
  cout<<sum<<endl;
  return 0;
}

Measured memory_bytes: 892
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<math.h>
#include<vector> 
using namespace std;
int a[110];
int main()
{int n,m,x,cnt0=0,cnt1=0;
 cin>>n>>m>>x;
 for(int i=0;i<m;i++)
 cin>>a[i];
 for(int i=0;i<m-1;i++)
 {if(a[i]<x) cnt0++;
  if(a[i]>x) cnt1++;
 }
 if(x*2>=n+1 && cnt0>cnt1){
 int ans=0;
 for(int i=0;i<=m-1;i++){
 for(int j=x;j<=n;j++){
 if(a[i]==j)
 ans++;
 }
 }
 cout<<ans<<endl;
 }
 else if(x*2>=n+1 && cnt0<=cnt1){
 int anoans=0;
 for(int i=m-1;i>=0;i--){
 for(int j=x;j>=0;j--){
 if(a[i]==j)
 anoans++;
 }
 }
 cout<<anoans<<endl;
 }
 else if(x*2<n+1){
 int oans=0,reoans=0;
 for(int i=m-1;i>=0;i--)
 {for(int j=x;j>=0;j--)
 {if(a[i]==j)
  oans++;
  }
  }
 for(int p=0;p<=m-1;p++)
 {for(int k=x;k<=n;k++)
 {if(a[p]==k)
  reoans++;
  }
 }
 cout<<min(oans,reoans)<<endl;
 }  
 system("pause");
 return 0;
}

Measured memory_bytes: 504
/*
 AUTHOR : ANSHU BABU RAJPUT
 
    JAI MAA SARASWATI
    OM NAMAH SHIVAY
    JAI SHRI KRISHNA
    JAI SHRI RAM
    BHARAT MATA KI JAI

    #PKMKB	
    #CKMKB
*/
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;

#define int  long long 
#define endl    ("\n")
#define ff       first
#define ss      second
#define pb   push_back
#define pf  push_front
#define ppb   pop_back
#define ppf  pop_front
#define mp   make_pair
#define mod 1000000007

#define L(x)    x.length()
#define B(x)     x.begin()
#define E(x)       x.end()
#define F(x)     x.front()
#define SZ(x)     x.size()
#define CLR(x)   x.clear()

#define all(x)                      x.begin(),x.end()
#define sortD(x) sort(x.begin(),x.end(),greater<int>)
#define rev(x)             reverse(x.begin(),x.end())

#define intV vector<int>

#define PI          (3.141592653589)
#define PMAX     priority_queue<int>
#define PMIN             priority_queue<int,vi,greater<int>>
#define setbits(x)                   __builtin_popcountll(x)
#define zrobits(x)                        __builtin_ctzll(x)

#define KING(i, n) for (int(i) = 0; (i) < n; (i)++)
#define MAHAKAL(i, n) for (int(i) = n-1; (i) >= 0; (i)--)

#define Anshu        int t; cin>>t; while(t--)
#define SITARAM(n,type) type* input=new type[n]

mt19937                          rng(chrono::steady_clock::now().time_since_epoch().count());
 
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;


void ViLiFY_KiNG()
{
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    freopen("error.txt","w",stderr);
#endif
}
 
int32_t main()
{
    ViLiFY_KiNG();
    // int n;
    // cin>>n;

    cout<<setprecision(12)<<fixed;

    double n;
    cin>>n;

    n = n/3;
    cout<<n*n*n<<endl;
    
    // if(n == 1) {
    //     cout<<0.036000000000<<endl;
    // } else if(n == 2) {
    //     cout<<0.250000000000<<endl;
    // } else {
    //     int num1 = n/3;
    //     int num2 = n/3;
    //     int num3 = n/3;

    //     int temp = n%3;
    //     if(temp == 1) {
    //         num1++;
    //     } else if(temp == 2) {
    //         num1++;
    //         num2++;
    //     }

    //     cout<<(num1*num2*num3*1.0);
    //     // cout<<".000000000000";
    // }
    return 0;
}

Measured memory_bytes: 3792
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"strings"
)

// 入る場合と入らない場合, 個数
var cnd = []int{1, 6, 9, 36, 81, 216, 729, 1296, 6561, 7776, 46656, 59049}

func (p *problem) solve() {
	N := p.NextInt()
	cmin := 100001
	q := []vec{{i: len(cnd) - 1, n: N}}
	for len(q) != 0 {
		next := q[0]
		if next.c > cmin {
			q = q[1:]
			continue
		}
		if next.n == 0 {
			cmin = min(cmin, next.c)
			q = q[1:]
			continue
		}
		if cnd[next.i] > next.n {
			q[0].i--
			continue
		}
		if next.i != 0 {
			q = append(q, vec{
				i: next.i - 1,
				n: next.n,
				c: next.c,
			})
		}
		q[0].n -= cnd[next.i]
		q[0].c++

	}
	p.PrintInt(cmin)
}

type vec struct {
	i, n, c int
}

// i = 現在試しているcnd, n = 残り, return 現在の試行回数
func rec(i, n int) int {
	switch {
	// 残りがなければend
	case n <= 0:
		return 0
	// 残り金額より大きい場合はcndを下げる
	case cnd[i] > n:
		return rec(i-1, n)
	case (i - 1) < 0:
		return rec(i, n-cnd[i]) + 1
	// 入れる場合と入れない場合で回数が小さい方を選択
	default:
		return min(rec(i, n-cnd[i])+1, rec(i-1, n))
	}
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

var (
	debug  bool
	output string
)

func main() {
	flag.BoolVar(&debug, "debug", false, "Print debug logs")
	flag.BoolVar(&debug, "d", false, "Print debug logs")
	flag.StringVar(&output, "output", "stdout", "Specify output target (Default: stdout)")
	flag.StringVar(&output, "o", "stdout", "Specify output target (Default: stdout)")
	flag.Parse()

	if debug {
		out := os.Stdout
		if output != "stdout" {
			logfile, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY, 0666)
			if err != nil {
				panic(err)
			}
			defer logfile.Close()
			out = logfile
		}
		log.SetOutput(out)
	} else {
		log.SetOutput(ioutil.Discard)
	}

	p := problem{
		in:  bufio.NewReader(os.Stdin),
		out: bufio.NewWriter(os.Stdout),
	}
	p.solve()

	if err := p.out.Flush(); err != nil {
		panic(err)
	}
}

type problem struct {
	in  *bufio.Reader
	out *bufio.Writer
}

func (p *problem) PrintInt(d int) {
	p.Printf("%d\n", d)
}

func (p *problem) Printf(format string, a ...interface{}) {
	if _, err := fmt.Fprintf(p.out, format, a...); err != nil {
		panic(err)
	}
}

func (p *problem) Printfln(format string, a ...interface{}) {
	if _, err := fmt.Fprintf(p.out, fmt.Sprintf("%v\n", format), a...); err != nil {
		panic(err)
	}
}

func (p *problem) NextInt() int {
	return stoi(p.Next())
}

func (p *problem) NextInts() []int {
	line := p.NextSSLine()
	ds := make([]int, len(line))
	for i, s := range line {
		ds[i] = stoi(s)
	}
	return ds
}

func (p *problem) NextSSLine() []string {
	return strings.Split(p.Next(), " ")
}

// Next reads line and return string.
func (p *problem) Next() string {
	var b []byte
	for {
		l, pre, err := p.in.ReadLine()
		if err != nil {
			panic(err)
		}
		b = append(b, l...)
		if !pre {
			break
		}
	}
	return string(b)
}

func stoi(s string) int {
	i, err := strconv.Atoi(s)
	if err != nil {
		fmt.Println(i)
		fmt.Println(err)
	}
	return i
}


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

int main() {
    int d;
    vector<int> c(26);
    vector<vector<int>> s(d, vector<int>(26)); 
    cin >> d;
    vector<int> ans(d);
    vector<int> mx(d);
    rep(i,26) {
        cin >> c.at(i);
    }
    rep(i,d) {
        rep(j,26) {
            cin >> s[i][j];
            if (mx.at(i) < s[i][j]) {
                ans.at(i) = j+1;
                mx.at(i) = s[i][j];
            }
        }
    }
    
    rep(i,d) {
        cout << ans.at(i) << endl;
    }
    return 0;
}

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

using namespace std;

int n, m, q;
char S[100100], T[100100];
int srr[100100], trr[100100];

int main() {
    int i;

    scanf("%s",S+1);
    scanf("%s",T+1);
    n = strlen(S+1); m = strlen(T+1);
    for (i=1;i<=n;i++) srr[i] = srr[i-1]+((S[i]=='A')?1:2);
    for (i=1;i<=m;i++) trr[i] = trr[i-1]+((T[i]=='A')?1:2);
    scanf("%d",&q);
    for (i=0;i<q;i++) {
        int a, b, c, d;
        scanf("%d%d%d%d",&a,&b,&c,&d);
        if ((srr[b]-srr[a-1])%3==(trr[d]-trr[c-1])%3) printf("YES\n");
        else printf("NO\n");
    }

    return 0;
}


Measured memory_bytes: 1536
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
	cin.tie(0);
	ios_base::sync_with_stdio(false);
	int N;
	cin >> N;
	vector<int> A(N), B(N), C(N);
	for (int i = 0; i < N; ++i) {
		cin >> A[i] >> B[i] >> C[i];
	}
	vector<int> dp(3);
	for (int i = 0; i < N; ++i) {
		dp = vector<int>({ max(dp[1], dp[2]) + A[i], max(dp[2], dp[0]) + B[i], max(dp[0], dp[1]) + C[i] });
	}
	cout << max({ dp[0], dp[1], dp[2] }) << '\n';
	return 0;
}

Measured memory_bytes: 1408
#include<bits/stdc++.h>
#define ll long long int
using namespace std;  
// A function to print all prime factors of a given number n 
ll primeFactors(ll p,ll n) 
{ 
    // Print the number of 2s that divide n 
    ll cnt_2=0;
    while (p%2 == 0) 
    { 
        //printf("%d ", 2); 
        p = p/2;
		cnt_2++; 
    } 
    //cout<<cnt_2<<endl;
  	ll ans1=(cnt_2/n);
  	//cout<<ans1<<endl;
  	if(cnt_2!=0)
  	ans1=pow(2,ans1);
  	//cout<<ans1<<endl;
  	ll ans=ans1;
  	cnt_2=0;
    // n must be odd at this point.  So we can skip  
    // one element (Note i = i +2)
	if(ans==0)
	ans=1; 
    for (ll i = 3; i <= sqrt(p); i = i+2) 
    { 
    	cnt_2=0;
        // While i divides n, print i and divide n 
        while (p%i == 0) 
        { 
            //printf("%lld ", i); 
            p = p/i;
			cnt_2++; 
        } 
        //cout<<i<<" "<<cnt_2<<endl;
        ans*=pow(i,cnt_2/n);
    } 
  	if (p > 2) 
        {
        	ans*=pow(p,1/n);
		}
    // This condition is to handle the case when n  
    // is a prime number greater than 2 
    return ans;
} 
  
/* Driver program to test above function */
int main() 
{ 
	ll n,p;
	cin>>n>>p;
    cout<<primeFactors(p,n); 
    return 0; 
}

Measured memory_bytes: 256
#include <stdio.h>

int main(void) {
  int max,min;
  int num;
  int avarage;
  int avsum;
  do{
    scanf(" %d",&num);
    int rawdata[1000] = {0};
    if(num == 0) return 0;
    else max = 0,min = 1000,avsum = num,avarage = 0;//initialize
    while(num > 0){
      num--;
      scanf(" %d", &rawdata[num]);
    }
    int i = 0;
    for(i = 0; i < avsum;i++) {
      avarage += rawdata[i];
      if(max < rawdata[i]) max = rawdata[i];
      if(min > rawdata[i]) min = rawdata[i];
    }
    
    avarage -= max;
    avarage -= min;

    avarage /= avsum - 2;
    printf("%d\n", avarage);
  }while(1);
}

Measured memory_bytes: 1032
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>
#include <functional>
using namespace std;

int main(){
    int N=4;
    char a[N];
    scanf("%s",a);
    
    if((a[0]==a[1] and a[2]==a[3] and a[1] != a[2]) ||
        (a[0] == a[2] and a[1]== a[3] and a[0] != a[1]) ||
        (a[0] == a[3] and a[1]== a[2] and a[0] != a[1])){
        printf("Yes\n");
    }
    else{
        printf("No\n");
    }
    return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
const int N = 9;
typedef long long ll;
typedef unsigned long long ull;
const int INF= 0x3f3f3f3f;
int main() {
	int n;
	cin>>n;
	string a;
    for(int i=1;i<=n;i++)
    {
        a.push_back(i+'0');
    }
    string s1,s2;
	for(int i=0;i<n;i++)
	{
		int b;
		cin>>b;
		s1.push_back(b+'0');
	}
	for(int i=0;i<n;i++)
	{
		int b;
		cin>>b;
		s2.push_back(b+'0');
	}
	int cnt=0;
    int beg=0x3f3f3f3f,en=0x3f3f3f3f;
    if(s1==a) beg=0;
    if(s2==a) en=0;
    while(next_permutation(a.begin(),a.end()))
    {
         cnt++;
         if(a==s1)
         { 
             beg=cnt;
             
         }
         if(a==s2)
         {
             en=cnt;
            
         }
       
    }
    cout<<abs(beg-en);
//    cout<<beg<<" "<<en<<endl;
    return 0;
}



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

using namespace std;

// Repetitions
#define FOR(i,a,n) for(ll i = ((ll) a); i < ((ll) n); ++i)
#define FORR(i, s, g) for(ll i = ((ll)s - 1); i >= ((ll) g); --i)
#define REP(i, n) FOR(i, 0, n)
#define REPR(i, n) FORR(i, n, 0)

// Container Utils
#define ALL(v) (v).begin(), (v).end()
#define RALL(v) (v).rbegin(), (v).rend()
#define SORTALL(v) sort(ALL(v))
#define SZ(a) int((a).size())
#define CLR(a) memset((a), 0 ,sizeof(a))
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())

// For Debug
#define DMP(x)  cerr << #x << " = " << (x) << endl
#define DBG(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl

// Aliases
#define PB push_back
#define MP make_pair
using ll = long long;
using ld = long double;
using str = string;
using vi = vector<int>;
using vvi = vector<vi>;
using vll = vector<ll>;
using vs = vector<str>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vpii = vector<pii>;
using vpll = vector<pll>;

// Constant variables
const ld PI = (acos(-1));
const ll MOD = 1000000007;

// I/O Asynchronizing
struct __io_async{
    __io_async(){
        cin.tie(0); ios::sync_with_stdio(0); cout<<fixed<<setprecision(20);
    };
};

int main() {
    ll n, a, b;
    cin >> n >> a >> b;
    cout << ((b - a) % 2 == 0 ? (b - a) / 2 : min(a - 1, n - b) + 1 + (b - a - 1) / 2) << endl;

    return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>
//C++11
#if __cplusplus == 201103L
#include <tuple>
#endif

using namespace std;

#define FOR(i,k,n) for(int i=(k); i<(int)n; ++i)
#define REP(i,n) FOR(i,0,n)
#define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)

template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cout<<*i<<" "; cout<<endl; }

typedef long long ll;
const int INF = 100000000;
const double EPS = 1e-8;
const int MOD = 1000000007;
typedef pair<int, int> P;

int main(){
  int W, H, T, ax, ay;
  while(cin>>W>>H && H){
    vector<string> grid(H);
    REP(i, H)cin>>grid[i];
    int time[1000][1000] = {};
    REP(y, H)REP(x, W){
      if(grid[y][x] == '#'){
        time[y][x] = INF;
      }
      if(grid[y][x] == 't'){
        ax = x, ay = y;
      }
    }
    cin>>T;
    REP(i, T){
      int x, y;
      cin>>x>>y;
      time[y][x] = min(time[y][x], i + 1);
    }
    int ans[1000][1000];
    REP(y, H)REP(x, W) ans[y][x] = INF;
    ans[0][0] = 0;
    queue<P> que;
    que.push(P(0, 0));
    while(!que.empty()){
      P p = que.front(); que.pop();
      int x = p.first, y = p.second;
      int dx[4] = {1, 0, -1, 0};
      int dy[4] = {0, 1, 0, -1};
      REP(r, 4){
        int nx = x + dx[r], ny = y + dy[r];
        if(nx >= 0 && nx < W && ny >= 0 && ny < H && time[ny][nx] != INF){
          int nexttime = max(time[ny][nx], ans[y][x]);
          if(nexttime < ans[ny][nx]){
            ans[ny][nx] = nexttime;
            que.push(P(nx, ny));
          }
        }
      }
    }
    if(ans[ay][ax] == INF) ans[ay][ax] = -1;
    cout<<ans[ay][ax] << endl;
  }
  return 0;
}

Measured memory_bytes: 9748
#include "bits/stdc++.h"
using namespace std;
#define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define ll long long int
#define int ll
//#define slld(t) scanf("%lld",&t)
//#define sd(t) scanf("%d",&t)
//#define pd(t) printf("%d\n",t)
//#define plld(t) printf("%lld\n",t)
#define vec vector < int >
#define vecp vector < pair < int , int > >
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
#define debug(x)   cerr<<#x<<": "<<x<<endl
#define pii pair < int , int >
#define pll pair < ll , ll > 
#define debug(x)   cerr<<#x<<": "<<x<<endl
#define mod  1000000007
#define N 200005
#define mod1 1000000007
#define mod2 998244353
#define bitcnt __builtin_popcount
#define PI acos(-1)
//#define endl "\n"

const int inf = (int)1e18 + 10;

bool dp[100005] = {0};
int a[103];
signed main(){
  fast;
 

 int n , k;
 cin >> n >> k;
 for(int i = 0 ; i < n ; i++)
 	cin >> a[i];
 
 for(int i = 1 ; i<= k ; i++){
 	
 		bool d = 1;
 	   for(int j = 0 ; j < n ; j++){
 	   	    if(i - a[j] > 0)
                d &= dp[i-a[j]];
            else if(i - a[j] == 0)
                d = 0;

 	   }

 	   dp[i] = 1 - d;
   // cout << i << " "<< dp[i] << endl;
 }


 if(dp[k] == 1)
 	cout << "First\n";
 else
 	cout << "Second\n";

}	

Measured memory_bytes: 384
use std::io::Read;

fn main() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();

    let answer = solve(&buf);

    println!("{}", answer);
}

fn solve(input: &str) -> String {
    let mut iterator = input.split_whitespace();

    let x1: usize = iterator.next().unwrap().parse().unwrap();
    let x2: usize = iterator.next().unwrap().parse().unwrap();
    let x3: usize = iterator.next().unwrap().parse().unwrap();
    let x4: usize = iterator.next().unwrap().parse().unwrap();
    let x5: usize = iterator.next().unwrap().parse().unwrap();

    if x1 == 0 {
        return "1".to_string();
    } else if x2 == 0 {
        return "2".to_string();
    } else if x3 == 0 {
        return "3".to_string();
    } else if x4 == 0 {
        return "4".to_string();
    }
    return "5".to_string();
}


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

const int maxn(1e5 + 5);

int n, m, b[maxn], que[maxn], len, vis[maxn];
ll k, f[maxn], g[maxn];

int main() {
	int i, j;
	scanf("%d", &n);
	for (i = 1; i <= n; ++i) scanf("%lld", &f[i]), b[i] = i;
	for (i = n; i; --i) f[i] -= f[i - 1];
	scanf("%d%lld", &m, &k);
	for (i = 1; i <= m; ++i) scanf("%d", &j), swap(b[j], b[j + 1]);
	for (i = 1; i <= n; ++i)
		if (!vis[i]) {
			j = i, len = 0;
			while (!vis[j]) que[len++] = j, vis[j] = 1, j = b[j];
			for (j = 0; j < len; ++j) g[que[j]] = f[que[(k + j) % len]];
		}
	for (i = 1; i <= n; ++i) g[i] += g[i - 1], printf("%lld\n", g[i]);
	return 0;
}

Measured memory_bytes: 3968
#include<stdio.h>

char tic(char map[10]){
  char flag;

  flag = 'd';
  if( map[0] == map[1] && map[1] == map[2] && map[0] != 's')flag = map[0];
  if( map[3] == map[4] && map[4] == map[5] && map[3] != 's')flag = map[3];
  if( map[6] == map[7] && map[7] == map[8] && map[6] != 's')flag = map[6];
  if( map[0] == map[3] && map[3] == map[6] && map[0] != 's')flag = map[0];
  if( map[1] == map[4] && map[4] == map[7] && map[1] != 's')flag = map[1];
  if( map[2] == map[5] && map[5] == map[8] && map[2] != 's')flag = map[2];
  if( map[0] == map[4] && map[4] == map[8] && map[0] != 's')flag = map[0];
  if( map[2] == map[4] && map[4] == map[6] && map[2] != 's')flag = map[2];

  return flag;
}
  

int main(void){
  char map[10];

  while(fscanf(stdin,"%s ",map)!=EOF)printf("%c\n",tic(map));

  return 0;
}

Measured memory_bytes: 0
while True:
    a, op, b = list(input().split())
    if op == '?':
        break

    a = int(a)
    b = int(b)
    ans = 0

    if op == '+':
        ans = a + b
    elif op == '-':
        ans = a - b
    elif op == '*':
        ans = a * b
    elif op == '/':
        ans = a // b

    print(ans)


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

using namespace std;
#define ll long long

#define rep(i, a) for (int i = 0; (i) < (int) (a); (i)++)
#define reps(i, a, b) for (int i = (int) (a); (i) < (int) (b); (i)++)
#define rrep(i, a) for (int i = (int) a-1; (i) >= 0; (i)--)
#define rreps(i, a, b) for (int i = (int) (a)-1; (i) >= (int) (b); (i)--)
#define MP(a, b) make_pair((a), (b))
#define PB(a) push_back((a))
#define all(v) (v).begin(), (v).end()
#define PERM(v) next_permutation(all(v))
#define UNIQUE(v) sort(all(v));(v).erase(unique(all(v)), v.end())
#define CIN(type, x) type x;cin >> x
#define TRUE__  "Yes"
#define FALSE__ "No"
#define PRINT(f) if((f)){cout << (TRUE__) << endl;}else{cout << FALSE__ << endl;}

#ifdef LOCAL
#define lcout(a) cout << a;
#define lcoutln(a) cout << a << endl;
#define lcerr(a) cerr << a;
#define lcerrln(a) cerr << a << endl;
#else
#define lcout(a) 
#define lcoutln(a) 
#define lcerr(a) 
#define lcerrln(a) 
#endif

#define MOD 1000000007

void init();
void solve();

signed main()
{
        init();
        solve();
}

ll N, X;
vector<ll> v;

void init()
{
        cin >> N >> X;
        v.resize(N+1);
        rrep(i, N) cin >> v[i+1];
        v[0] = 0;
        reps(i, 1, N+1) v[i] += v[i-1];
}

void solve()
{
        ll res = 8e18;
        rreps(i, N / 2 + 2, 1) {
                ll k = i * X + N * X;
                int st = 0;
                ll en = i;
                int x = 3;
                while (st < N) {
						if (res < k) break;
                        k += max(x, 5) * (v[en] - v[st]);
                        st = en;
                        en += i;
                        en = min(N, en);
                        x += 2;
                }
                res = min(res, k);
        }
        cout << res << endl;
}


Measured memory_bytes: 1792
#include <bits/stdc++.h>
using namespace std;
#define rep(i,N) for(int i=0;i<N;i++)
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef long long ll;
int main(){
  int N; cin>>N;
  vvi F(N,vi(10)), P(N,vi(11));
  rep(i,N) rep(j,10) cin>>F[i][j];
  rep(i,N) rep(j,11) cin>>P[i][j];
  ll ans = -1e9;
  for(int i=1;i<(1<<10);i++){
    ll bene = 0;
    rep(j,N) {
      int cnt = 0;
      rep(k,10) if(i & (1<<k) && F[j][k]) cnt++;
    bene += P[j][cnt];
    }
    ans = max(ans,bene);
  }
  cout<<ans<<endl;
  return 0;
}


Measured memory_bytes: 256