akhauriyash/Code-Regression huggingface dataset:
/**
 *    author:  tourist
 *    created: 11.05.2020 13:47:54       
**/
#include <bits/stdc++.h>

using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n, a, b, c;
  cin >> n >> a >> b >> c;
  vector<string> s(n);
  for (int i = 0; i < n; i++) {
    cin >> s[i];
  }
  string res(n, ' ');
  for (int i = 0; i < n; i++) {
    int& x = (s[i][0] == 'A' ? a : (s[i][0] == 'B' ? b : c));
    int& y = (s[i][1] == 'A' ? a : (s[i][1] == 'B' ? b : c));
    if (x + y == 0) {
      cout << "No" << '\n';
      return 0;
    }
    int id = -1;
    if (x != 1 || y != 1) {
      id = (x > y ? 1 : 0);
    } else {
      id = (i == n - 1 ? 0 : (s[i + 1].find(s[i][0]) != string::npos ? 0 : 1));
    }
    res[i] = s[i][id];
    x += (id == 0 ? 1 : -1);
    y += (id == 1 ? 1 : -1);
  }
  cout << "Yes" << '\n';
  for (char ch : res) {
    cout << ch << '\n';
  }
  return 0;
}


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

int main(){
  map <int,int> tisa;
  int64_t n,k; cin >> n >> k;
  for(int i=1; i<n+1; i++){
    int a; cin >> a;
    tisa[i] = a;
  }
  
  int ans = 1;
  map<int,int> itta; itta[1]=1;
  vector<int> trace(200000); trace.at(0) = 0; trace.at(1)=1;
  bool fl = false;
  int start; int time;
  
  for(int64_t i=1; i<k+1; i++){
    ans = tisa[ans];
    trace.at(i+1)=ans;
    if(itta.count(ans)){
      start = itta[ans];
      time = i+1-start;
      fl = true;
      break;
    }
    else{
      itta[ans]=i+1;
    }  
  }
  
  //cout << start << time << endl;
  if(fl){
    int q = (k+1-(start-1)) % time;
    //cout << k+1-(start-1) << endl;
    //cout << q << endl;
    if(q==0){
      q=time;
    }
    //cout << q << endl;
    ans = trace.at(start+q-1);
  }
      
  cout << ans << endl;
  
}

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

const int N = (int)1e5;

vector< pair<int,int> > adjList[N+5];
int res[N+5];

int dfs(int u, int weight=0, int par=-1) {
    res[u] = weight % 2;

    for (pair<int,int> v: adjList[u]) {
        if (v.first != par) {
            dfs(v.first, weight+v.second, u);
        }
    }

    return 0;
}

int main() {
    for (int i=0; i<N+3; i++) {
        adjList[i].clear();
        res[i] = -1;
    }

    int n; scanf("%d", &n);
    for (int i=1; i<n; i++) {
        int u,v,w; scanf("%d %d %d", &u, &v, &w);
        adjList[u].push_back( make_pair(v,w%2) );
        adjList[v].push_back( make_pair(u,w%2) );
    }

    dfs(1);

    for (int i=1; i<=n; i++) {
        printf("%d\n", res[i]);
    }
    return 0;
}


Measured memory_bytes: 8448
package main

import (
	"bufio"
	"os"
	"strconv"
)

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	sc.Scan()
	N, _ := strconv.Atoi(sc.Text())

	sc.Scan()
	Q, _ := strconv.Atoi(sc.Text())

	parents := make([]int, N)
	for i := 0; i < N-1; i++ {
		sc.Scan()
		a, _ := strconv.Atoi(sc.Text())

		sc.Scan()
		b, _ := strconv.Atoi(sc.Text())

		parents[b-1] = a - 1
	}

	scores := make([]int, N)
	for i := 0; i < Q; i++ {
		sc.Scan()
		p, _ := strconv.Atoi(sc.Text())

		sc.Scan()
		x, _ := strconv.Atoi(sc.Text())

		scores[p-1] += x
	}

	for i := 1; i < N; i++ {
		p := parents[i]
		scores[i] += scores[p]
	}

	writer := bufio.NewWriter(os.Stdout)
	writer.WriteString(strconv.Itoa(scores[0]))
	for i := 1; i < N; i++ {
		writer.WriteString(" " + strconv.Itoa(scores[i]))
	}
	writer.Flush()
}


Measured memory_bytes: 9856
import java.util.*;

class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int jdg = 0;
        for(int i = 1;i <= 9;i++){
            for(int j = 1;j <= 9;j++){
                jdg = i*j;
                if(jdg == n)
                break;
            }
            if(jdg == n)
            break;
        }
        System.out.println(jdg == n?"Yes":"No");
    }
}


Measured memory_bytes: 21716
#include <cstdio>
#include <stack>
using namespace std;

stack<int> car;

int main()
{
	int n;
	while(scanf("%d",&n) != EOF) {
		if(n != 0) {
			car.push(n);
		} else {
			printf("%d\n",car.top());
			car.pop();
		}
	}	
	return 0;
}

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

int main()
{
    int N;
    long long A, B;
    cin >> N;
    cin >> A >> B;

    vector<long long> h(N);
    long long h_max = 0;
    for (int i = 0; i < N; i++)
    {
        cin >> h[i];
        h_max = max(h_max, h[i]);
    }

    // binary search
    long long left_idx = 0;
    long long right_idx = h_max / B;
    if (h_max % B != 0)
    {
        right_idx++;
    }

    long long idx = (left_idx + right_idx) / 2;
    long long diff = A - B;

    // binary search
    while (right_idx - left_idx > 1)
    {
        long long count = 0;
        for (int i = 0; i < N; i++)
        {
            if (h[i] > idx * B)
            {
                count += (h[i] - idx * B) / diff;
                if ((h[i] - idx * B) % diff != 0)
                {
                    count++;
                }
            }
        }
        if (count <= idx)
        {
            right_idx = idx;
        }
        else
        {
            left_idx = idx;
        }
        idx = (left_idx + right_idx) / 2;
    }
    cout << right_idx << endl;
}


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

using namespace std;

int main(void) {
	int n;
	cin >> n;
	vector<int> a(n);
	for (int i = 0; i < n; ++i) {
		cin >> a[i];
	}
	for (int i = 0; i < n; ++i) {
		cout << a[n-i-1];
		if (i < n-1) {
			cout << " ";
		}
	}
	cout << endl;
	return 0;
}



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

using namespace std;

int main() {
#ifdef  DEBUG
  ifstream in("input.txt");
  cin.rdbuf(in.rdbuf());
#endif  // for local.
  int m_1, d_1, m_2, d_2;
  cin >> m_1 >> d_1 >> m_2 >> d_2;
  if (m_1 != m_2) {
    cout << 1;
  } else {
    cout << 0;
  } cout << endl;
  
  return 0;
}

Measured memory_bytes: 256
def num2alpha(num):
    if num<=26:
        return chr(64+num)
    elif num%26==0:
        return num2alpha(num//26-1)+chr(90)
    else:
        return num2alpha(num//26)+chr(64+num%26)
      
N = int(input())

print(num2alpha(N).lower())



Measured memory_bytes: 9156
class binaryTree:
    def __init__(self,key,p=None,l=None,r=None):
        self.key = key
        self.p = p
        self.l = l
        self.r = r

N = int(input())
treelist = [list(input().split()) for i in range(N)]
root = None

def inorder(root):
    x = root
    if x == None:
        return
    inorder(x.l)
    
    global inlist
    inlist.append(x.key)
    
    inorder(x.r)

def insert(root,z):
    y = None
    x = root
    while x != None:
        y = x
        if z.key < x.key:
            x = x.l
        else:
            x = x.r
    z.p = y

    if y == None:
        root = z
    elif z.key < y.key:
        y.l = z
    else:
        y.r = z
    return root
    
def outorder(root):
    x = root
    if x == None:
        return
    global outlist
    outlist.append(x.key)
    
    outorder(x.l)
    outorder(x.r)

for data in treelist:
    if data[0] == "insert":
        z = binaryTree(int(data[1]))
        root = insert(root,z)
        
    if data[0] == "print":
        inlist = []
        outlist = []
        
        inorder(root)
        indata = " " + " ".join([str(num) for num in inlist])
        print(indata)
 
        outorder(root)
        outdata = " " + " ".join([str(num) for num in outlist])
        print(outdata)


Measured memory_bytes: 262480
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <cstdio>
#include <functional>
#include <set>
#include <sstream>
#include <map>
#include <queue>
 
using namespace std;
  
const double eps=1e-10;
 
const int dy[]={-1,-1,0,1,1, 1, 0,-1};
const int dx[]={ 0, 1,1,1,0,-1,-1,-1};
 
int main()
{
 
	vector<long> prime;
	prime.push_back(2);
	prime.push_back(3);
	prime.push_back(5);
 
	for(int i=7;prime.back()<=50000;i+=2){
		bool ok=true;
		for(int j=0;prime[j]*prime[j]<=i && ok;j++){
			if(i%prime[j]==0) ok=false;
		}
		if(ok) prime.push_back(i);
//	  if(ok) cout<<i<<endl;
	}
 
	long n;
	while(cin>>n,n){
		long res=0;
		for(int i=0;prime[i]<=n/2;i++){
			if(binary_search(prime.begin(),prime.end(),n-prime[i])) res++;
		}
		cout<<res<<endl;
	}
 
 
	return 0;
}

Measured memory_bytes: 1324
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<tuple>
#include<cmath>


#define mod 1000000007
#define rep(i,k,N) for(int i=k;i<N;i++)
#define MP make_pair
#define MT make_tuple //tie,make_tuple は別物
#define PB push_back

using namespace std;

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

int main() {
	int M,D;
	int ans=0;
	cin>>M>>D;

	rep(i,2,M+1){
		rep(j,2,D+1){
			if(j/10<2)continue;
			if(j%10<2)continue;
			if(i==((j/10)*(j%10)))ans++;
		}
	}

	cout<<ans;
	return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#define REP(i,n) for(int i=0;i<n;i++)
#define LOOP(i,x,n) for(int i=x;i<n;i++)
#define ALL(v) (v).begin(),(v).end()
#define PB push_back
#define MP make_pair
#define FR first
#define SC second
#define int long long
using namespace std;
const int MOD=1000000007;
const int INF=9000000009;

int dp[51][51][51*51];
signed main(){
  int n,a;
  cin>>n>>a;
  vector<int> x(n);
  REP(i,n)cin>>x[i];

  dp[0][0][0]=1;
  LOOP(i,1,51)REP(j,51)REP(k,51*51){
    dp[i][j][k]=dp[i-1][j][k];
    if(j>=1&&k>=x[i-1])dp[i][j][k]+=dp[i-1][j-1][k-x[i-1]];
  }

  int ans=0;
  LOOP(i,1,n+1)ans+=dp[n][i][a*i];
  cout<<ans<<endl;

  return 0;
}


Measured memory_bytes: 52096
n, k = map(int, input().split())
h_list = list(map(int, input().split()))
dp = [0]
for i in range(1, n):
    mi = min([abs(h_list[i] - h_list[j]) + dp[j] for j in range(max(0, i - k), i)])
    dp.append(mi)
print(dp[-1])

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

#define min(a, b) ((a) > (b) ? (b) : (a))
#define max(a, b) ((a) > (b) ? (a) : (b))

int main(void) {
  int i, j, k, l;
  int a[] = {1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51};
  int K;
  scanf("%d", &K);
  printf("%d", a[K - 1]);
  return 0;
}


Measured memory_bytes: 256
w, h, n = map(int, input().split())

x=[0]*n
y=[0]*n
a=[0]*n
white=[0,h,w,0]
for i in range(n):
    line = list(map(int, input().split()))
    x[i] = line[0]
    y[i] = line[1]
    a[i] = line[2]

    if a[i] == 1:
        white[0] = max(white[0],x[i])
    elif a[i] == 2:
        white[2] = min(white[2], x[i])
    elif a[i] == 3:
        white[3] = max(white[3], y[i])
    elif a[i] == 4:
        white[1] = min(white[1], y[i])

newh = (white[1] - white[3])
neww = (white[2] - white[0])
print(newh * neww if newh >=0 and neww >=0 else 0)

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

int a, b;
bool con[20][20];
int memo[20][20];

inline bool inside(int y, int x) {
  return 0 <= y && y < b && 0 <= x && x < a;
}

int dfs(int y = 0, int x = 0) {
  if (!inside(y, x)) return 0;
  if (con[y][x]) return 0;
  if (y == b - 1 && x == a - 1) return 1;
  if (~memo[y][x]) return memo[y][x];

  return memo[y][x] = dfs(y + 1, x) + dfs(y, x + 1);
}

int main() {
  while (cin >> a >> b, a || b) {
    memset(memo, -1, sizeof(memo));
    memset(con, false, sizeof(con));
    int n;
    cin >> n;
    for (int i = 0; i < n; ++i) {
      int x, y;
      cin >> x >> y;
      con[y - 1][x - 1] = true;
    }
    cout << dfs() << endl;
  }
}

Measured memory_bytes: 3008
#include <bits/stdc++.h>
#include <atcoder/convolution>

using namespace std;
using namespace atcoder;
 
int main() {
  int n, m;
  cin >> n >> m;

  vector<int> a(n), b(m);
  for(int& e: a) cin >> e;
  for(int& e: b) cin >> e;

  for(int& e: convolution(a, b)) cout << e << " ";
  cout << endl;

  return 0;
}


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

int main(){
  int N;
  string S;
  int count = 0;
  char temp = 'A';
  cin >> N >> S;
  
  for(int i = 0; i < N; ++i){
    if(!(temp == S[i])){
      ++count;
      temp = S[i];
    }
  }
  
  cout << count << endl;
  
}
  

Measured memory_bytes: 512
#include <stdio.h>

int abs(int n){
  if(n >= 0){
    return n;
  }
  else{
    return -n;
  }
};

int
main(int argc, char *argv[])
{
  long int integer;
  scanf("%ld", &integer);

  int X[8];
  int j = 0;

  while(integer >= 100){
    X[j] = integer % 1000;
    integer /= 10;
    j++;
  }

  int m = 1000;

  for(int i = 0; i < j; i++){
    if(m > abs(X[i] - 753)){
      m = abs(X[i] - 753);
    }
  }

  printf("%d\n", m);

  return 0;
}
      


Measured memory_bytes: 128
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <set>
#include <map>
typedef long long ll;
using namespace std;

int main(){
  int N;
  ll x;
  cin >> N >> x;
  ll a[N];
  for(int i = 0; i < N; i++) cin >> a[i];

  sort(a, a + N);

  ll cnt = 0;
  int ans = 0;
  int ind = 0;
  for(int i = 0; i < N; i++){
    if(cnt + a[i] <= x){
      cnt += a[i];
      ans++;
      ind = i;
    }
    else{
      break;
    }
  }

  if(ind == N - 1 && cnt != x){
    ans--;
  }

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



Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using V = vector<int>;
using VV = vector<V>;
using VVV = vector<VV>;
using VL = vector<ll>;
using VVL = vector<VL>;
using VVVL = vector<VVL>;
template<class T> using P = pair<T, T>;
#define rep(i,n) for(int i=0;i<(n);i++)
#define rep1(i,n) for(int i=1;i<=(n);i++)
#define REP(i,k,n) for(int i=(k);i<(n);i++)
#define all(a) (a).begin(),(a).end()
#define output(x,y) cout << fixed << setprecision(y) << x << endl;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
const ll MOD = 1e9 + 7;
// const ll MOD = 998244353;
ll upper = MOD + MOD;
ll under = -upper;
ll UPPER = MOD * MOD;
ll UNDER = -UPPER;
const long double pi = 3.141592653589793;
int main() {
	int a, b, k;
	cin >> a >> b >> k;
	for (int i = min(a, b); i >= 1; i--) {
		if (a % i == 0 && b % i == 0) k--;
		if (k == 0) {
			cout << i << endl;
			return 0;
		}
	}
	return 0;
}

Measured memory_bytes: 256
import scala.io.StdIn.readLine

object Main {
  def main(args:Array[String]) {
    val in = readLine().split(" ").map(_.toInt)
    val (w, h, x, y, r) = (in(0), in(1), in(2), in(3), in(4))

    if (0 <= x - r && 0 <= y - r && x + r <= w && y + r <= h) {
      println("Yes")
    } else {
      println("No")
    }
  }
}

Measured memory_bytes: 43836
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//                       _oo0oo_                         //
//                      o8888888o                        //
//                      88" . "88      ------ hzt1       //
//                      (| -_- |)                        //
//                      0\  =  /0                        //
//                    ___/`---'\___                      //
//                  .' \|     |// '.                     //
//                 / \|||  :  |||// \                    //
//                / _||||| -:- |||||- \                  //
//               |   | \  -  /// |     |                 //
//               | \_|  ''\---/''  |_/ |                 //
//               \  .-\__  '-'  ___/-. /                 //
//             ___'. .'  /--.--\  `. .'___               //
//          ."" '<  `.___\_<|>_/___.' >' "".             //
//         | | :  `- \`.;`\ _ /`;.`/ - ` : | |           //
//         \  \ `_.   \_ __\ /__ _/   .-` /  /           //
//     =====`-.____`.___ \_____/___.-`___.-'=====        //
//                       `=---='                         //
//                                                       //
//                                                       //
//     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~       //
//                                                       //
//                 God-He Bless All.                     //
//           This Code Will Never Explode.               //
//                                                       //
//                                                       //
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
#include<cstdio>
#include<cstring>
#include<cctype>
#include<algorithm>
#define rep(i,a,b) for(int i=(a),i##_end_=(b);i<=i##_end_;i++)
#define dwn(i,a,b) for(int i=(a),i##_end_=(b);i>=i##_end_;i--)
using namespace std;
inline int read() {
    int x=0,f=1;char c=getchar();
    for(;!isdigit(c);c=getchar()) if(c=='-') f=-1;
    for(;isdigit(c);c=getchar()) x=x*10+c-'0';
    return x*f;
}
typedef long long ll;
const int maxn=3010;
const int mod=1000000007;
int n,m;
int mn[maxn],mx[maxn];
char s[maxn],ansl[maxn],ansr[maxn];
int f[maxn][maxn];
int main() {
	n=read();m=read();
	scanf("%s",s+1);
	rep(i,1,n) ansl[i]=ansr[i]=s[i];
	rep(i,1,m) {
		int l=read(),r=read();
		sort(ansl+l,ansl+r+1);
		sort(ansr+l,ansr+r+1);
		reverse(ansr+l,ansr+r+1);
	}
	rep(i,1,n) {
		mn[i]=mn[i-1];mx[i]=mx[i-1];
		if(ansl[i]=='1') mn[i]++;
		if(ansr[i]=='1') mx[i]++;
	}
	f[0][0]=1;
	int res=0;
	rep(i,0,n) rep(j,mn[i],mx[i]) {
		int& ans=f[i][j];
		if(i==n) (res+=ans)%=mod;
		else (f[i+1][j]+=ans)%=mod,(f[i+1][j+1]+=ans)%=mod;
	}
	printf("%d\n",res);
	return 0;
}


Measured memory_bytes: 33792
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll dp[100005],arr[6]={100,101,102,103,104,105};
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll n;
    cin>>n;
    dp[0]=1;
    for(ll i=0;i<100005;i++)
    for(ll j=0;j<6;j++)
    if(i-arr[j]>=0)
    dp[i]=max(dp[i],dp[i-arr[j]]);
    cout<<dp[n];
}


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

#define REP(i, n) for (int i = 0; i < n; i++)
#define FOR(i, n, m) for (int i = n; i < m; i++)
#define ll long long int

using namespace std;

int main()
{
  int n, k;
  cin >> n >> k;
  ll v[50];
  REP(i, n)
  {
    cin >> v[i];
  }

  ll result = 0;
  // i回操作する
  FOR(i, 1, k + 1)
  {
    REP(j, i + 1)
    {
      int res = k - i;
      priority_queue<ll, vector<ll>, greater<ll>> que;
      if (i >= n)
      {
        // 全部取る
        REP(p, n)
        {
          que.push(v[p]);
        }
      }
      else
      {
          
               // 左からi-j個、右からj個取る
               REP(p, min(i - j, n))
               {
                 que.push(v[p]);
               }
               REP(q, min(j, n))
               {
                 int p = n - 1 - q;
                 que.push(v[p]);
               }
      }

      REP(p, res)
      {
        if (que.empty())
        {
          break;
        }
        ll t = que.top();
        if (t >= 0)
        {
          break;
        }
        que.pop();
      }

      ll tmp = 0;
      while (!que.empty())
      {
        tmp += que.top();
        que.pop();
      }
      result = max(result, tmp);
    }
  }

  std::cout << result << endl;
 return 0;
}
                 

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

void solve() {
    int N; cin >> N;
    vector<int> d(N);
    rep(i, N) cin >> d[i];
    long long ans = 0;
    for(int i = 0; i < N; ++i) {
        for(int j = i + 1; j < N; ++j) {
            ans += d[i] * d[j];
        }
    }
    cout << ans << '\n';
}

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


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

int main() {
  ll n,c,k;
  cin>>n>>c>>k;
  ll t[n];
  for(int i=0;i<n;i++) {
    cin>>t[i];
  }
  sort(t,t+n);
  ll bus=0;
  ll count=0;
  vector<int> person(c);
  for(int i=0;i<n;i++){
    if(count==0){
      person.at(count)=t[i];
      count++;
    }
    else if(count<c){
      if(t[i]-person.at(0)<=k){
        person.at(count)=t[i];
        count++;
      }
      else{
        bus++;
        person.at(0)=t[i];          
        count=1;
      }
   }
    else{
      bus++;
      count=1;
      person.at(0)=t[i];
    }
    if(i==n-1) bus++;
  }
  cout<<bus<<endl;
  return 0;
}

Measured memory_bytes: 1280
#include "iostream"

using namespace std;

class Q {
	int fast, last;

	int num[100005];

public:
	Q() {
		fast = 0;	//???????????´???
		last = 0;	//???????°??????´???

	}

	void enqueue(int n) {
		
		if (last >= 100000) {

			last -= fast;
			for (int i = 0; i < last; i++) {
				num[i] = num[fast+i];
			}
			fast = 0;
		}

		num[last] = n;

		last++;
	}

	int dequeue() {
		fast++;
		return num[fast - 1];
	}

	int getlengh() {
		return last - fast;
	}

};


int main() {

	Q queue;
	//cout << sizeof(queue);

	int n, q;
	char name[100000][10];
	int time[100000];

	int total = 0;

	cin >> n;
	cin >> q;

	for (int i = 0; i < n; i++) {
		cin >> name[i];
		cin >> time[i];
		
		queue.enqueue( i );

	}

	for (int i = 0; queue.getlengh() > 0; i++) {
		int num = queue.dequeue();
		if (time[num] <= q) {
			total += time[num];
			cout << name[num] << " " << total << endl;
		}
		else {
			total += q;
			time[num] -= q;
			queue.enqueue(num);
		}
	}

	cin >> n;

	return 0;
}

Measured memory_bytes: 2248
import sys 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
A = []
while(N>26):
    s = N % 26
    if s == 0:
      A.append(26)
      N = (N-26) // 26
    else:
      A.append(s)
      N = (N-s) // 26
A.append(N)
A = A[::-1]
ans = ''
d = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in A:
  ans += d[i-1]
print(ans)

Measured memory_bytes: 9264
#include<cstdio>
#include<queue>
#include<vector>
#define put(x,y) make_pair(x,y)

using namespace std;
const int SIZE=1e6;
deque< pair<int,int> > p;
bool vis[SIZE];
int k;

void bfs() {
	while(p.size()) {
		pair<int,int> now=p.front(); p.pop_front();
		if(vis[now.first]) continue;
		vis[now.first]=true;
		if(!now.first) {
			printf("%d\n",now.second);
			return;
		}
		p.push_front(put(now.first*10%k,now.second));
		p.push_back(put((now.first+1)%k,now.second+1));
	}
	
}
int main() {
	scanf("%d",&k);
	p.push_front(put(1,1));
	bfs();
	return 0;
}

Measured memory_bytes: 1152
#include <stdio.h>
int main()
{
	int i,a,b,c,ans;
	scanf("%d %d %d",&a,&b,&c);
	for(i=0;i<=1000;i++)
	{
		ans=a*i;
		if(ans%b==c)
		{
			printf("YES\n");
			return 0;
		}
	}
	printf("NO\n");
}

Measured memory_bytes: 128
//
//  main.cpp
//  B - Buffet
//
//  Created by Hashizo on 2019/09/07.
//  Copyright © 2019 Hashizo. All rights reserved.
//

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <regex>

using namespace std;

#undef LONG_MAX
#undef LONG_MIN

#define LONG_MAX	9223372036854775807
#define LONG_MIN	(-LONG_MAX  -1)

#define ll long long

#define FOR(i, a, b) for (ll i = (a); i < (b); i++)
#define REP(i, n) FOR(i, 0, n)

#define SORT(c) sort((c).begin(), (c).end())
#define REVERSE(v) reverse((v).begin(), (v).end())

int main(int argc, const char * argv[]) {
	ll total = 0;
	ll n;
	cin >> n;

	vector<ll> a(n);
	REP(i, n) {
		cin >> a[i];
	}

	vector<ll> b(n);
	REP(i, n) {
		cin >> b[i];
	}

	vector<ll> c(n-1);
	REP(i, n-1) {
		cin >> c[i];
	}

	total = b[a[0]-1];
	
	FOR(i, 1, n) {
		total += b[a[i]-1];
		if ((a[i-1]+1) == (a[i])) {
			total += c[(a[i-1]-1)];
		}
	}
	
	cout << total << endl;
	return 0;
}


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

int main(){
  int n,k;
  cin >> n >> k;
  int a = 0;
  if (n>k){
    while (n>=k){
      n = n-k+1;
      a++;
    }
    cout << a+(n>1) << endl;
  }
  else {
    cout << 1 << endl;
  }
}

Measured memory_bytes: 256
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies          #-}

import           Control.Applicative
import           Control.Monad
import qualified Data.ByteString.Char8 as B

import           Data.Array.IArray
import           Data.Array.IO
import           Data.Array.MArray
import           Data.IORef

readi :: B.ByteString -> Int
readi b | Just (n, _) <- B.readInt b = n

-- Union/Find
-- Mutable Algorithms in Immutable Languages, Part 1
-- http://jspha.com/thoughts/2016/8/23/from-the-archive-mutable-algorithms-in-immutable-languages-part-1

newtype Node a = Node (IORef (Node_ a))

data Node_ a = Node_
    { parent :: Maybe (IORef (Node_ a))
    , rank   :: Int
    , value  :: a
    }

makeSet :: a -> IO (Node a)
makeSet a = do
    n <- newIORef (Node_ { parent = Nothing, rank = 0, value = a })
    return (Node n)

findSet :: Node a -> IO (Node a)
findSet (Node a) = do
    Node p <- findRec (Node a)
    when (a /= p) $ do
        modifyIORef' a (\n -> n { parent = Just p })
    return (Node p)
  where
    findRec :: Node a -> IO (Node a)
    findRec (Node a) = do
        n <- readIORef a
        case parent n of
            Nothing -> return (Node a)
            Just p  -> findSet (Node p)

unite :: Node a -> Node a -> IO ()
unite n1 n2 = do
    Node p1 <- findSet n1
    Node p2 <- findSet n2
    when (p1 /= p2) (adopt p1 p2)
  where
    adopt x y = do
        nx <- readIORef x
        ny <- readIORef y
        case compare (rank nx) (rank ny) of
            EQ -> do
                writeIORef x (nx { rank = rank nx + 1 })
                writeIORef y (ny { parent = Just x })
            LT -> writeIORef x (nx { parent = Just y })
            GT -> writeIORef y (ny { parent = Just x })

same :: Node a -> Node a -> IO Bool
same n1 n2 = do
    Node p1 <- findSet n1
    Node p2 <- findSet n2
    return (p1 == p2)

--

type Forest = IOArray Int (Node Int)

unite' :: Int -> Int -> Forest -> IO ()
unite' x y dsf = do
    nx <- readArray dsf x
    ny <- readArray dsf y
    unite nx ny

same' :: Int -> Int -> Forest -> IO Bool
same' x y dsf = do
    nx <- readArray dsf x
    ny <- readArray dsf y
    same nx ny

main :: IO ()
main = do
    [n, q] <- fmap readi . B.words <$> B.getLine
    xss <- replicateM q $ do
        [a, b, c] <- fmap readi . B.words <$> B.getLine
        return (a, b, c)
    forest <- newListArray (0, n - 1) =<< mapM makeSet [0 .. n - 1]
              :: IO Forest

    forM_ xss $ \(a, b, c) -> do
        case a of
            0 -> unite' b c forest
            1 -> do
                isSame <- same' b c forest
                if isSame
                    then putStrLn "1"
                    else putStrLn "0"



Measured memory_bytes: 64988
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main() {
  ll n,k;
  cin>>n>>k;
  ll a[n+1];
  for(int i = 1 ; i <= n ; i++) {
      cin >> a[i];
  }
  ll dp[n+1] = {0};
  dp[1] = 0;
  ll p = INT_MAX;
  for(int i = 2 ; i <= n ; i++){
      p = INT_MAX;
      for(int j = 1 ; j <= k ; j++){
          if(i-j<=0){
              break;
          }
          p = min(p,dp[i-j]+abs(a[i]-a[i-j]));
      }
      dp[i] = p;
  }
  cout<<dp[n]<<endl;
}

Measured memory_bytes: 5216
#include <cstdio>
#include <cstring>
#include <map>
#include <set>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <queue>
#define maxn 809
using namespace std;
char s[maxn][maxn];
bool vis[maxn][maxn];
int d[maxn][maxn];
int n, m, k;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
queue<pair<int,int> >Q;
bool in(int x, int y){
	return 0 <= x && x < n && 0 <= y && y < m;
}
void bfs(int x, int  y){
	vis[x][y] = 1;
	Q.push(make_pair(x, y));
	d[x][y] = 0;
	while(!Q.empty()){
		int u = Q.front().first;
		int v = Q.front().second;
		Q.pop();
		for(int i = 0; i < 4; i++){
			int nx = dx[i] + u;
			int ny = dy[i] + v;
			if(in(nx, ny) && !vis[nx][ny] && s[nx][ny] != '#'){
				vis[nx][ny] = 1;
				d[nx][ny] = d[u][v] + 1;
				Q.push(make_pair(nx, ny));
			}
		}
	}
}
int D(int x){
	return (x + k - 1) / k;
}
int main(){
	int x, y;
	cin >> n >> m >> k;
	for(int i = 0 ; i < n; i++){
		scanf("%s", s[i]);
		for(int j = 0; j < m; j++){
			if(s[i][j] == 'S'){
				x = i;
				y = j;
			}
		}
	}
	if(x == 0 || x == n - 1 || y == 0 || y == m - 1){
		puts("0");
		return 0;
	}
	bfs(x, y);
	int ans = n  * m + 1;
	for(int i = 0; i < n; i++){
		for(int j = 0; j < m; j++){
			if(vis[i][j]){
				if(d[i][j] <= k){
					int cur = D(abs(i - 0));
					cur = min(cur, D(abs(n - 1 - i)));
					cur = min(cur, D(abs(j)));
					cur = min(cur, D(abs(m - 1 - j)));
					ans = min(ans, cur);
				}
			}
		}
	}
	cout << ans + 1 << endl;
	return 0;
}

Measured memory_bytes: 4096
import heapq
import copy
n = int(input())

size = 2*10**5
def f(ary):
    t_ans = 10**100
    for i in range(len(ary)):
        t_ud = ary[i]
        if len(t_ud) != 0:
            #print(t_ud)
            t_ud.sort()
            t_u = -10**100
            for j in range(len(t_ud)):
                if t_ud[j][1] == 'U':
                    t_u = t_ud[j][0]
                elif t_u == -10**100:
                    continue
                else:
                    t_ans = min(t_ans, (t_ud[j][0] - t_u))
    return t_ans

xyu = []

for i in range(n):
    x,y,u = input().split()
    x = int(x)
    y = int(y)
    xyu.append([x,y,u])

ud = [[] for i in range(size+1)]
rl = [[] for i in range(size+1)]
ul = [[] for i in range(size*2+2)]
ur = [[] for i in range(size*2+2)]
dl = [[] for i in range(size*2+2)]
dr = [[] for i in range(size*2+2)]

for i in range(n):
    if xyu[i][2] == 'U':
        ud[xyu[i][0]].append([xyu[i][1],'U'])
        ul[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'U'])
        ur[xyu[i][1]+xyu[i][0]].append([xyu[i][1],'U'])
    if xyu[i][2] == 'D':
        ud[xyu[i][0]].append([xyu[i][1],'D'])
        dl[xyu[i][0]+xyu[i][1]].append([xyu[i][1],'D'])
        dr[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'D'])
    if xyu[i][2] == 'R':
        rl[xyu[i][1]].append([xyu[i][0],'U'])
        ur[xyu[i][1]+xyu[i][0]].append([xyu[i][1],'D'])
        dr[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'U'])
    if xyu[i][2] == 'L':
        rl[xyu[i][1]].append([xyu[i][0],'D'])
        ul[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'D'])
        dl[xyu[i][0]+xyu[i][1]].append([xyu[i][1],'U'])
                  
ans = 10**100
ans = min(ans,f(ud)*5)
ans = min(ans,f(rl)*5)
ans = min(ans,f(ul)*10)
ans = min(ans,f(ur)*10)
ans = min(ans,f(dl)*10)
ans = min(ans,f(dr)*10)
if ans == 10**100:
    print('SAFE')
else:
    print(ans)


Measured memory_bytes: 269144
#include <bits/stdc++.h>
#define FASTIO ios::sync_with_stdio(false);cin.tie(0);
#define ADD +
#define SUBTRACT -
#define MULTIPLY *
#define DIVIDE /
#define MOD %
#define INCREMENT(x) ++x
#define DECREMENT(x) --x
#define in(a,b) cin>>a>>b;
#define out(a,b) cout<<a<<endl<<b<<endl;
#define scan(a) scanf("%d",&a);
#define print(a) printf("%d\n",a);
#define scanii(a,b) scanf("%d %d",&a,&b);
#define printii(a,b) printf("%d\n%d\n",a,b);
#define scaniii(a,b,c) scanf("%d %d %d",&a,&b,&c);
#define pub push_back
#define pob pop_back
#define puf push_front
#define pof pop_front
#define ll long long
#define ull unsigned long long
#define sll signed long long
#define pi acos(-1)
#define mod 1000000007
#define TRUE 1
#define FALSE 0
#define ZERO 0
#define MP make_pair
#define F first
#define S second
#define f1(i,a) for(int i=0;i<a;++i)
#define f2(i,a) for(int i=a-1;i>=0;--i)
#define en puts("");
#define elif else if
typedef ll int lli;
typedef sll int slli;
typedef ull int ulli;
const int sz=10000;
using namespace std;

int clue();
int result();
void show();
bool check(int n) {
    for(int i=2;i*i<=n;++i) {
        if(n%i==0)
        return false;
    }
    return true;
}


// bool cmp(pair<int,int>p,pair<int,int>q) {
//     // return p.first>q.first;//descending by first
//     // return p.first<q.first;//ascending by first
//     // return p.second>q.second;//descending by second
//     return p.second<q.second;//ascending by second
// }

bool cmp(int p,int q) {
    return p>q;//descending
    // return p<q;//ascending
}


int main() {

    int t;
    // cin>>t;
    t=1;
    while(t-->0) {
        clue();
    }

    return 0;
}
int clue() {

    string s;
    cin>>s;
    if(s=="Sunny") {
        cout<<"Cloudy"<<endl;
    }
    elif(s=="Cloudy") {
        cout<<"Rainy"<<endl;
    }
    else
    {
        cout<<"Sunny"<<endl;
    }
    
    // ()?cout<<"Yes"<<endl:cout<<"No"<<endl;
    
    return 0;
}

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

vector<pair<long long, int>> v;
vector<long long> u;

void search(int index, long long cur) {
    if (index == v.size()) {
        u.emplace_back(cur);
        return;
    }
    for (int i = 0; i <= v[index].second; i++) {
        search(index+1, cur);
        cur *= v[index].first;
    }
    return;
}

long long gcd(long long a, long long b) {
    if (a < b) swap(a, b);
    if (b == 0) return a;
    if (a % b == 0) return b;
    else return gcd(b, a%b);
}

int main() {    
    int n; cin >> n;
    vector<long long> a(n);
    for (int i = 0; i < n; i++) cin >> a[i];
    sort(a.begin(), a.end());
    long long c = a[n-1];
    for (long long i = 2; i * i <= c; i++) {
        int tmp = 0;
        while (c % i == 0) {
            c /= i; tmp++;
        }
        if (tmp) v.emplace_back(i, tmp);
    }
    if (c != 1) v.emplace_back(c, 1);
    search(0, 1);
    long long ans = 0;
    for (int i = 0; i < n-1; i++) {
        ans = gcd(ans, a[i]);
    }
    for (auto x: u) {
        int cnt = 0;
        for (int i = 0; i < n-1; i++) {
            if (a[i] % x == 0) cnt++;
        }
        if (cnt >= n-2) ans = max(ans, x);
    }
    cout << ans << endl;
    return 0;
}

Measured memory_bytes: 1024
#include <iostream>
#include <string>
#include <cmath>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<iomanip>
#define _USE_MATH_DEFINES
#include <math.h>
#include <functional>
using namespace std;

#define rep(i,x) for(int i=0;i<x;i++)
#define repn(i,x) for(int i=1;i<=x;i++)

typedef long long ll;
const ll INF = 1e17;
const ll MOD = 1000000007;
const ll MAX = 1000001;

ll max(ll a, ll b) {
	if (a > b) { return a; }
	return b;
}

ll min(ll a, ll b) {
	if (a > b) { return b; }
	return a;
}

ll gcd(ll a, ll b) {
	if (b == 0) { return a; }
	if (a < b) { return gcd(b, a); }
	return gcd(b, a%b);
}

ll lcm(ll a, ll b) {
	return a * b / gcd(a, b);
}



///////////////////////////

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

void COMinit() {
	fac[0] = fac[1] = 1;
	finv[0] = finv[1] = 1;
	inv[1] = 1;
	for (int i = 2; i < MAX; i++) {
		fac[i] = fac[i - 1] * i % MOD;
		inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
		finv[i] = finv[i - 1] * inv[i] % MOD;
	}
}

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


ll p(ll n) {
	if (n == 0) { return 1; }
	else {return 4 * p(n - 1)%MOD; }
}

int main() {

	ll N;
	cin >> N;
	vector<ll> a(N), b(N);
	rep(i, N) cin >> a[i];
	rep(i, N) cin >> b[i];

	vector<ll> c(2 * N), d(N);

	rep(i, N) {
		c[i] = a[i] ^ a[(i + 1) % N];
		d[i] = b[i] ^ b[(i + 1) % N];
		c[N + i] = c[i];
		//cout << c[i] << d[i]<<endl;
	}

	vector<ll> pma(N + 1);

	pma[0] = -1;
	int j = -1;

	repn(i,N) {
		while (j >= 0) {
			if (d[j] == d[i - 1]) { pma[i] = j + 1; j++; break; }
			j = pma[j];
		}
		if (j < 0) { pma[i] = 0; j = 0; }
		//cout << pma[i] << endl;
	}

	
	

	int k = 0;//何文字一致しているか
	int i = 0;

	while (i<=2*N-2) {

		//cout << k << i << endl;

		if (d[k] == c[i]) {
			k++; i++;
		if (k == N) {
			cout << i - N << " " << (a[i - N] ^ b[0]) << endl;
			k = pma[k];
		}
		}

		else if (k > 0) { k = pma[k]; }

		else { i++; k = 0; }

		
	}



	system("PAUSE");

}


Measured memory_bytes: 13044
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<list>
#include<set>
#include<map>
#include<utility>
#include<queue>
#include<cmath>

#define rep(i,x) for(int i=0;i<(int)(x);i++)
#define reps(i,x) for(int i=1;i<=(int)(x);i++)
#define rrep(i,x) for(int i=((int)(x)-1);i>=0;i--)
#define rreps(i,x) for(int i=((int)(x));i>0;i--)

#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define INF 2e12

template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
typedef long long ll;
typedef std::pair<ll, ll> P;
int gcd(int a,int b){return b?gcd(b,a%b):a;}

using namespace std;


int main()
{
    ll A, B, Q;
    cin >> A >> B >> Q;
    vector<ll> s(A);
    vector<ll> t(B);
    rep(i, A) cin >> s[i];
    rep(i, B) cin >> t[i];

    rep(i, Q){
        ll x;
        cin >> x;
        auto itr1 = lower_bound(all(s), x);
        auto itr2 = lower_bound(all(t), x);
        ll m = INF;
        ll idx1 = itr1 - s.begin();
        ll idx2 = itr2 - t.begin();
        if(idx1 <= A-1 && idx2 <= B-1){
            ll tmp = max(s[idx1], t[idx2]);
            m = min(m, tmp - x);
        }
        if(idx1 >= 1 && idx2 >= 1){
            ll tmp = min(s[idx1-1], t[idx2-1]);
            m = min(m, x-tmp);
        }
        if(idx1 <= A-1 && idx2 >= 1){
            ll tmp = (s[idx1] - t[idx2-1]) + min(s[idx1]-x, x-t[idx2-1]);
            m = min(m, tmp);
        }
        if(idx1 >= 1 && idx2 <= B-1){
            ll tmp = (t[idx2] - s[idx1-1]) + min(x - s[idx1-1], t[idx2]-x);
            m = min(m, tmp);
        }
        cout << m << endl;
    }
}

Measured memory_bytes: 2944
/*
 *  stay hungry, stay foolish, stay home.
 */
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
#define rep(i,a,b)  for(ll i=a;i<b;i++)
#define ml cout<<"\n"
 
#define pii pair<ll,ll>
#define vi  vector<ll>
#define vii vector<pii>
#define mi  map<ll,ll>
#define all(a)  (a).begin(),(a).end()

#define pb push_back
#define in insert
#define ff first
#define ss second
#define mod 1000000007

#define yes cout<<"YES"<<endl;
#define no cout<<"NO"<<endl;
#define test4(x,y,z,a) cout<<"x is "<<x<<"		y is "<<y<<"		z is "<<z<<"		a is "<<a<<endl;
#define test3(x,y,z) cout<<"x is "<<x<<"		y is "<<y<<"		z is "<<z<<endl;
#define test2(x,y) cout<<"x is "<<x<<"		y is "<<y<<endl;
#define test1(x) cout<<"x is "<<x<<endl;

int main(){
	ios_base::sync_with_stdio(false);
     	cin.tie(NULL);
    	cout.tie(NULL);    
	long double n;
	cin>>n;
	
	long double p = ((long double)22 / 7 ) * 2 * n;
	cout<<fixed<<setprecision(20)<<p<<endl;
	return 0;
}

Measured memory_bytes: 3804
import java.util.*;

public class Main {
    final static int MOD = 1000000007;
    
    public static void main(String[] args) {
        MyScanner in = new MyScanner();
        int a = in.nextInt();
        int b = in.nextInt();
        
        int ans = a - b * 2;
    
        if (ans > 0) {
            System.out.println(ans);
        } else {
            System.out.println(0);
        }
        
        
    }
    
    static class MyScanner {
        static Scanner sc = new Scanner(System.in);
        
        String next() {
            return sc.next();
        }
        
        String nextLine() {
            return sc.nextLine();
        }
        
        int nextInt() {
            return Integer.parseInt(sc.next());
        }
        
        double nextDouble() {
            return Double.parseDouble(next());
        }
        
        long nextLong() {
            return Long.parseLong(next());
        }
        
        int[] nextIntArray(int n) {
            int[] array = new int[n];
            for (int i = 0; i < n; i++) {
                array[i] = nextInt();
            }
            return array;
        }
        
        double[] nextDoubleArray(int n) {
            double[] array = new double[n];
            for (int i = 0; i < n; i++) {
                array[i] = nextDouble();
            }
            return array;
        }
        
        long[] nextLongArray(int n) {
            long[] array = new long[n];
            for (int i = 0; i < n; i++) {
                array[i] = nextLong();
            }
            return array;
        }
        
        String[] nextLineArray(int n) {
            String[] array = new String[n];
            for (int i = 0; i < n; i++) {
                array[i] = nextLine();
            }
            return array;
        }
        
        int[][] nextIntMatrix(int n, int m) {
            int[][] matrix = new int[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    matrix[i][j] = nextInt();
                }
            }
            return matrix;
        }
        
        double[][] nextDoubleMatrix(int n, int m) {
            double[][] matrix = new double[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    matrix[i][j] = nextDouble();
                }
            }
            return matrix;
        }
        
        long[][] nextLongMatrix(int n, int m) {
            long[][] matrix = new long[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    matrix[i][j] = nextLong();
                }
            }
            return matrix;
        }
    }
}

Measured memory_bytes: 24276
#include "bits/stdc++.h"
using namespace std;
typedef long long li;

const int inf = 1 << 29;

li dp[2000][2000];
li dp_maxx[2000];
li dp_maxy[2000];
li dp_max = -inf;

void update(const li x, const li y, const li v) {
    dp[x][y] = max(dp[x][y], v);
    dp_maxx[y] = max(dp_maxx[y], v);
    dp_maxy[x] = max(dp_maxy[x], v);
    dp_max = max(dp_max, v);
};

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

    li n;
    cin >> n;
    vector<li> xs(3 * n);
    for (int i = 0; i < 3 * n; ++i) {
        cin >> xs[i];
        xs[i]--;
    }

    for (int i = 0; i < n; ++i) {
        dp_maxx[i] = -inf;
        dp_maxy[i] = -inf;
        for (int j = 0; j < n; ++j) {
            dp[i][j] = -inf;
        }
    }

    update(xs[0], xs[1], 0);

    li offset = 0;
    for (int itr = 0; itr < n - 1; ++itr) {
        const li p = xs[2 + itr * 3];
        const li q = xs[2 + itr * 3 + 1];
        const li r = xs[2 + itr * 3 + 2];

        // add, use 3
        if (p == q && q == r) {
            offset++;
            continue;
        }

        vector<tuple<li, li, li>> updates;

        // add, use 2
        if (p == q || q == r || p == r) {
            li pair, rem;
            if (p == q) {
                pair = p;
                rem = r;
            } else if (q == r) {
                pair = q;
                rem = p;
            } else {
                pair = r;
                rem = q;
            }
            for (int k = 0; k < n; ++k) {
                updates.emplace_back(k, rem, dp[k][pair] + 1);
                updates.emplace_back(k, rem, dp[pair][k] + 1);
            }
        }

        // add, use 1
        updates.emplace_back(q, r, dp[p][p] + 1);
        updates.emplace_back(p, r, dp[q][q] + 1);
        updates.emplace_back(p, q, dp[r][r] + 1);

        // no-add, use 3
        // reusing the dp table to avoid O(n^2) updates.

        // no-add, use 2
        for (int k = 0; k < n; ++k) {
            updates.emplace_back(k, p, dp_maxx[k]);
            updates.emplace_back(k, p, dp_maxy[k]);
            updates.emplace_back(k, q, dp_maxx[k]);
            updates.emplace_back(k, q, dp_maxy[k]);
            updates.emplace_back(k, r, dp_maxx[k]);
            updates.emplace_back(k, r, dp_maxy[k]);
        }

        // no-add, use 1
        updates.emplace_back(p, q, dp_max);
        updates.emplace_back(p, r, dp_max);
        updates.emplace_back(q, r, dp_max);

        for (auto &upd: updates) {
            update(get<0>(upd), get<1>(upd), get<2>(upd));
        }
    }

    li ans = dp_max;
    for (int x = 0; x < n; ++x) {
        for (int y = 0; y < n; ++y) {
            if (x == y && y == xs[3 * n - 1]) {
                ans = max(ans, dp[x][y] + 1);
            }
        }
    }

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

Measured memory_bytes: 35328
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics;



class Myon
{
    public Myon() { }
    public static int Main()
    {
        new Myon().calc();
        return 0;
    }


    Scanner cin;

    long mod = 998244353;
    void calc()
    {
        cin = new Scanner();
        string S = cin.next();
        dic = new Dictionary<string, long>();
        Console.WriteLine(dfs(S));
    }

    Dictionary<string, long> dic;

    long dfs(string S)
    {
        if (dic.ContainsKey(S)) return dic[S];
        if (S == "") return 1;
        if (S == "0") return 1;
        if (S == "1") return 2;
        //Console.WriteLine(S);

        long ans = (long)(S[0] - '0' + 1) * dfs(S.Substring(1));
        for (int r = 1; r < S.Length; r++)
        {
            StringBuilder sb = new StringBuilder(S.Substring(0, r));
            int cnt = 0;
            while(cnt + r <= S.Length)
            {
                for (int k = 0; k < r; k++)
                {
                    if (S[cnt] == '0') sb[k] = '0';
                    cnt++;
                }
                if (cnt != r)
                {
                    ans += dfs(sb.ToString()) * dfs(S.Substring(cnt));
                    ans %= mod;
                }
            }
        }
        return dic[S] = ans;
    }

}


class Scanner
{
    string[] s;
    int i;

    char[] cs = new char[] { ' ' };

    public Scanner()
    {
        s = new string[0];
        i = 0;
    }

    public string next()
    {
        if (i < s.Length) return s[i++];
        string st = Console.ReadLine();
        while (st == "") st = Console.ReadLine();
        s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries);
        if (s.Length == 0) return next();
        i = 0;
        return s[i++];
    }

    public int nextInt()
    {
        return int.Parse(next());
    }
    public int[] ArrayInt(int N, int add = 0)
    {
        int[] Array = new int[N];
        for (int i = 0; i < N; i++)
        {
            Array[i] = nextInt() + add;
        }
        return Array;
    }

    public long nextLong()
    {
        return long.Parse(next());
    }

    public long[] ArrayLong(int N, long add = 0)
    {
        long[] Array = new long[N];
        for (int i = 0; i < N; i++)
        {
            Array[i] = nextLong() + add;
        }
        return Array;
    }

    public double nextDouble()
    {
        return double.Parse(next());
    }


    public double[] ArrayDouble(int N, double add = 0)
    {
        double[] Array = new double[N];
        for (int i = 0; i < N; i++)
        {
            Array[i] = nextDouble() + add;
        }
        return Array;
    }
}


Measured memory_bytes: 25332
#include <cstdio>
#include <vector>
using namespace std;
int main(void){
  while(1){
    long long int c[55];
    vector<int> d[33];
    int n;
    scanf("%d",&n); if(!n) break;
    for(int i = 0; i < n; i++){
      c[i] = 1LL << i;
      int f;
      scanf("%d",&f);
      for(int j = 0; j < f; j++){
	int a;
	scanf("%d",&a);
	d[a].push_back(i);
      }
    }
    bool f = false;
    for(int i = 1; i <= 30; i++){
      for(int j = 0; j < (int)d[i].size(); j++){
	//printf("%d:%d-%d\n",i,j,d[i][j]);
	for(int k = 0; k < (int)d[i].size(); k++){
	  //printf("%lld | %lld = ",c[d[i][k]],c[d[i][j]]);
	  c[d[i][k]] |= c[d[i][j]];
	  //printf("%lld\n",c[d[i][k]]);
	  if(c[d[i][k]] == (1LL << n) - 1){
	    f = true;
	    printf("%d\n",i);
	    break;
	  }
	}
	if(f) break;
      }
      if(f) break;
    } 
    if(!f) puts("-1");
  }
}

Measured memory_bytes: 1072