akhauriyash/Code-Regression huggingface dataset:
while True:
    n, m = map(int, input().split())
    if n == m == 0:
        break
    a = []
    b = []
    for i in range(n):
        a.append(int(input()))
    masu = 1
    cnt = 0

    for i in range(m):
        b.append(int(input()))

    for i in range(m):
        cnt += 1
        masu += b[i]
        if masu >= n:
            print(cnt)
            break
        masu += a[masu-1]
        if masu >= n:
            print(cnt)
            break



Measured memory_bytes: 5632
from math import gcd
from functools import reduce
from sys import exit

# O(A+N)解
MAX_A = 1000000
lowerst_prime = [0] * (MAX_A + 1) # 最小の素因数をいれる(2以上をみていけばいい)
primes = [] # MAX_A以下の素数の集合
count = [0] * (MAX_A + 1) # 約数として出てくる回数を数える
for i in range(2, MAX_A + 1): # 線形時間で処理してくれる
    if lowerst_prime[i] == 0:
        lowerst_prime[i] = i
        primes.append(i)
    for p in primes:
        if p > lowerst_prime[i] or i * p > MAX_A:
            break
        lowerst_prime[i * p] = p # p がi * p のもっとも小さな素因数となるときのみ更新されるので、線形時間アルゴリズムとなる
# 入力
N = int(input())
A = [*map(int, input().split())]
if reduce(gcd, A) != 1:
    print("not coprime")
    exit(0)
for i in range(N):
    while A[i] > 1:
        divide = lowerst_prime[A[i]]
        if count[divide]:
            # A[x] % i == A[y] % i == 0 となるx != yが存在するので、i | gcd(x, y)となる
            print("setwise coprime")
            exit(0)
        count[divide] += 1
        while A[i] % divide == 0: # 割れるだけ割る
            A[i] //= divide
print("pairwise coprime")

Measured memory_bytes: 215480
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}


template <typename T>
vector<T> dijkstra(int s,vector<vector<pair<int, T> > > & G){  
  const T INF = numeric_limits<T>::max();    
  using P = pair<T, int>;
  int n=G.size();
  vector<T> d(n,INF);
  vector<int> b(n,-1);
  priority_queue<P,vector<P>,greater<P> > q;
  d[s]=0;
  q.emplace(d[s],s);
  while(!q.empty()){
    P p=q.top();q.pop();
    int v=p.second;
    if(d[v]<p.first) continue;
    for(auto& e:G[v]){
      int u=e.first;
      T c=e.second;
      if(d[u]>d[v]+c){
        d[u]=d[v]+c;
        b[u]=v;
        q.emplace(d[u],u);
      }
    }
  }
  return d;
}

//INSERT ABOVE HERE
const int MAX = 101;
int ans[MAX][MAX];
signed main(){
  int n;
  cin>>n;
  using P = pair<int, int>;
  vector<vector<P> > G(n*n);
  for(int i=0;i<2*n*n-2*n;i++){
    int a,b;
    cin>>a>>b;
    a--;b--;
    G[a].emplace_back(b,1);
    G[b].emplace_back(a,1);
  }
  vector<int> cs;
  for(int i=0;i<n*n;i++)
    if(G[i].size()==2u) cs.emplace_back(i);

  vector<vector<int> > ds;
  for(int c:cs) ds.emplace_back(dijkstra(c,G));
  
  map<P, P> pos;
  for(int i=0;i<n;i++)
    for(int j=0;j<n;j++)
      pos[P(i+j,i+(n-1-j))]=P(i,j);

  int x=0;
  int y=ds[x][cs[1]]==n-1?1:2;
  for(int i=0;i<n*n;i++){
    int p,q;
    tie(p,q)=pos[P(ds[x][i],ds[y][i])];
    ans[p][q]=i;
  }
  
  for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
      if(j) cout<<" ";
      cout<<ans[i][j]+1;
    }
    cout<<endl;
  }
  return 0;
}



Measured memory_bytes: 4496
import java.util.*;
public class Main {

	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		String n =sc.nextLine();
		n.trim();
		int sum=0;
		char line[] = n.toCharArray();
		for(int c : line)
			sum+=c-'0';
		System.out.println(sum%9==0?"Yes":"No");
	}

}


Measured memory_bytes: 41460
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long ll;
const int M=2e5+5;
const ll INF=1e12;
ll a[M],f[M];
ll n;ll k;
int check(ll x)
{
    ll cost=0;
    for(int i=1;i<=n;i++)cost+=max(a[i]-x/f[i],0LL);
    if(cost<=k)return 1;return 0;
}
inline ll read()
{
    ll x=0,f=1; char ch=getchar();
    while(ch<'0'||ch>'9') { if(ch=='-') f=-1; ch=getchar(); }
    while(ch>='0'&&ch<='9') { x=(x<<1)+(x<<3)+(ch^48); ch=getchar(); }
    return x*f;
}
int main()
{
    n=read(),k=read();
    for(int i=1;i<=n;i++) a[i]=read();
    for(int i=1;i<=n;i++) f[i]=read();
    sort(a+1,a+n+1); sort(f+1,f+n+1);
    reverse(f+1,f+n+1);
    ll L=0,R=INF,ans=0;
    while(L<=R)
    {
        ll mid=L+R>>1;
        if(check(mid)) R=mid-1,ans=mid;
        else L=mid+1;
    }
    printf("%lld\n",ans);
    return 0;
}

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

int main(){
	int n;
	int x;
	int a;
	int b;
	int c;
	int t;
	while(true) {
		cin >> n >> x;
		if ( n==0 && x==0 ) break;
		t=0;
		for ( a = 1 ;a<=n ;a++ ) {
			for ( b = a+1 ;b<=n ;b++ ) {
				for ( c = b+1 ;c<=n ;c++ ) {
					if ( a + b + c == x ) t++;
				}
			}
		}
		cout << t << endl;
	}
    return 0;
}

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





int main() {
    int N;
    cin >> N;
    string S1, S2;
    cin >> S1 >> S2;
    ll mod = 1000000007;
    ll d;
    int idx = 0;
    if (S1[0] == S1[1]) {
        d = 6;
        idx = 2;
    } else {
        d = 3;
        idx = 1;
    }
    while (idx < N) {
        if (idx + 1 < N && S1[idx] == S1[idx + 1]) {
            if (S1[idx - 1] == S2[idx - 1]) {
                d *= 2;
            } else {
                d *= 3;
            }
            idx += 2;
        } else if (S1[idx - 1] == S2[idx - 1]){
            d *= 2;
            idx++;
        } else {
            idx++;
        }
        d %= mod;
    }
    cout << d << "\n";
    return 0;
}

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

int main(){
    long long N, Q;
    scanf("%lld%lld", &N, &Q);

    vector<long long> A(N), AS(N + 2), S(N + 1), X((N - 1) / 2), a((N + 1) / 2);
    for(int i = 0; i < N; ++i){
        scanf("%lld", &A[i]);
        AS[i + 2] = A[i] + AS[i];
        S[i + 1] = A[i] + S[i];
    }

    for(int i = 1; i <= (N + 1) / 2; ++i){
        a[i - 1] = S[N] - S[N - i] + AS[N - i * 2 + 1];
    }

    for(int i = 1; i <= (N - 1) / 2; ++i){
        X[i - 1] = A[N - i - 1] + A[N - i * 2 - 1];
    }

    reverse(a.begin(), a.end());
    reverse(X.begin(), X.end());

    for(long long i = 0, x = 0; i < Q; ++i){
        scanf("%lld", &x);
        printf("%lld\n", a[lower_bound(X.begin(), X.end(), x * 2) - X.begin()]);
    }
    return 0;
}

Measured memory_bytes: 4864
#include <iostream>
#include <cmath>

using namespace std;

int Bsort(int *arr,int n) {
	bool flag = true;
	int i = 0;
	int count = 0;
	while (flag) {
		flag = false;
		for (int j=n-1; j>i; j--) {
			if (arr[j] < arr[j-1]) {
				int t = arr[j];
				arr[j] = arr[j-1];
				arr[j-1] = t;
				flag = true;
				count++;
			}
		}
		i++;
	}
	return count;
}
int main() {
	int n;
	cin >> n;
	int *arr = new int[n];
	for (int i=0; i<n; i++) {
		cin >> arr[i];
	}
	int c = Bsort(arr,n);
	for (int i=0; i<n; i++) {
		if (i) cout << " ";
		cout << arr[i];
	}
	cout << endl;
	cout << c << endl;
	return 0;
}


Measured memory_bytes: 3108
import Data.List
import Data.Ord
import Data.Char
import Data.Ratio
import Data.Maybe

main = do
  xy <- map (read::String->Int) . words <$> getLine
  sq xy

sq [x1,y1,x2,y2] = (putStrLn .unwords .map show) [x3,y3,x4,y4]
  where x3 = x2-(y2-y1)
        y3 = y2+(x2-x1)
        x4 = x3-(y3-y2)
        y4 = y3+(x3-x2)

Measured memory_bytes: 3896
#include <cstdio>
int main()
{
    float left,right;
    int lA=0,rA=0,lB=0,rB=0,lC=0,rC=0,lD=0,rD=0;
    while (scanf("%f %f",&left,&right)!=EOF) {
        if (left<0.2) lD++;
        else if (left<0.6) lC++;
        else if (left<1.1) lB++;
        else lA++;
        if (right<0.2) rD++;
        else if (right<0.6) rC++;
        else if (right<1.1) rB++;
        else rA++;
    }
    printf("%d %d\n%d %d\n%d %d\n%d %d\n",lA,rA,lB,rB,lC,rC,lD,rD);
}

Measured memory_bytes: 0
import java.util.*;

class Main {
    private static final Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        // ??\????????????
        // ??¬??\??§????????°???????????§????????´???????????????????????°???????????°?????????????????\????????????
        int[] a = new int[3];
        for (int i = 0;i < 3;i++) {
            a[i] = sc.nextInt();
        }
        // ?????????
        Arrays.sort(a);
        // StringBuilder???????????§???
        StringBuilder sb = new StringBuilder();
        for (int i = 0;i < 3;i++) {
            sb.append(a[i]).append(" ");
        }
        // ????°????????§????????????????????????????
        System.out.println(sb.substring(0,sb.length()-1));
   }
}

Measured memory_bytes: 26264
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
	static char[][] map = new char[8][8];
	public static void main(String[] args) {
		Scanner stdIn = new Scanner(System.in);
		while(true) {
			int n = stdIn.nextInt();
			if(n == 0) break;
			char[][] list = new char[n][];
			for(int i = 0; i < n; i++) {
				list[i] = stdIn.next().toCharArray();
			}
			for(int i = 0; i < n; i++) {
				for(int j = 1; j < list[i].length; j++) {
					if(list[i][j] != '.' && list[i][j-1] == '.') {
						for(int k = 0; k < j-1; k++) {
							list[i][k] = ' ';
						}
						list[i][j-1] = '+';
						for(int k = i-1; k >= 0; k--) {
							if(j-1 < list[k].length && list[k][j-1] == ' ') {
								list[k][j-1] = '|';
								continue;
							}
							else {
								break;
							}
						}
						break;
					}
				}
			}
			PrintWriter out = new PrintWriter(System.out);
			for(int i = 0; i < n; i++) {
				out.println(list[i]);
			}
			out.flush();

		}
	}
	static char[] retS(char a, int b) {
		char[] tmp = new char[b];
		for(int i = 0; i < b; i++) {
			tmp[i] = ' ';
		}
		return tmp;
	}
}

Measured memory_bytes: 69260
#include<bits/stdc++.h>
#define ll long long
#define pii pair<int,int> 
#define mp make_pair
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define all(c) c.begin(),c.end()
#define pb push_back
#define fi first
#define se second
#define chmin(x,y) x=min(x,y)
#define chmax(x,y) x=max(x,y)
using namespace std;
int main(){
    int n;
    string s;
    int a=0,b=0;
    cin>>n>>s;
    for(int i=0;i<s.size();i++)
        if(s[i]=='R')
            a++;
        else
            b++;
    cout<<((a>b)?"Yes":"No")<<endl;
    return 0;
}

Measured memory_bytes: 256
n, k = map(int, input().split())
r, s, p = map(int, input().split())
t = list(input())
pattern = []

point = {"r" : p, "s" : r, "p" : s}

for i in range(0, k):
    pattern.append(t[i::k])

ans = 0
tmp = ""

for i in pattern:
    tmp = ""
    count = 0
    for j in range(len(i)):
        if tmp == i[j]:
            if count == 1:
                ans += point[i[j]]
                count = 0

            else:
                count = 1

        else:
            count = 0
            tmp = i[j]
            ans += point[i[j]]

print(ans)


Measured memory_bytes: 12712
n, m = map(int, input().split())
used = [False] * (n+1)
ball = [1] * (n+1)
used[1] = True
for _ in range(m):
    x,y = map(int, input().split())
    ball[x] -= 1
    ball[y] += 1
    if used[x]:
        used[y] = True
    if ball[x] == 0:
        used[x] = False
res = 0
for i in range(1, n + 1):
    if used[i] and ball[i] != 0:
        res += 1
print(res)
#print(ball)
#print(used)

Measured memory_bytes: 51672
# coding: utf-8
# Your code here!
N=int(input())
List = list(map(int, input().split()))
List=sorted(List)
List=List[::-1]
#print(List)
if List.count(0)!=0:
    print(0)
    quit()
ANS=List[0]
i=1
while i<N:
    ANS=ANS*List[i]
    if ANS>1000000000000000000:
        print(-1)
        quit()
    i+=1

print(ANS)





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

int main() {
  int N, A, B, x;
  cin >> N >> A >> B ;
  x = N * A;
  if (x > B) {
    cout << B << endl;
  } else if (x < B) {
    cout << x << endl;
  } else cout << x << endl;
  return 0;
}

Measured memory_bytes: 3548
#include <algorithm>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <tuple>
#include <vector>

using namespace std;

typedef long long ll;
constexpr ll MOD = 1000000007;

// struct UnionFind {
//     vector<int> par;
    
//     UnionFind(int N): par(N) {
//         for (int i=0;i<N;i++) 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) {
//         int rx = root(x);
//         int ry = root(y);
//         if (rx == ry) return;
//         par[rx] = ry;
//     }

//     bool same(int x, int y) {
//         int rx = root(x);
//         int ry = root(y);
//         return rx == ry;
//     }
// };

int main(void) {
    ll A, B;
    cin >> A >> B;
    if ((A+B)%2 == 0) cout << (A+B)/2 << endl;
    else cout << "IMPOSSIBLE" << endl;

    return 0;
}


Measured memory_bytes: 256
#include<iostream>
#include <stdlib.h>
#include <algorithm>
#include <string>
#include <math.h>
#include <vector>
#include <numeric>
typedef long long int ll;
using namespace std;
int main(){ 
	ll N,K,num,num1,count=0;
	cin >> N>>K;
	if(K==0){
		cout<<N*N<<endl;
		return 0;
	}
	for(ll i=K+1;i<=N;i++){
		count+=(i-K)*(N/i)+max((ll)0,(N-i*(N/i))-K+1);
	}
	cout<< count << endl;
	return 0;
}

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

#ifdef LOCAL
#define debug(var) cerr << (#var) << " = " << (var) << endl;
#else
#define debug(var)
#endif

void init() {
  ios_base::sync_with_stdio(0);
  cin.tie(0); cout.tie(0);
}

const int mod = 1e9+7;
const int N = 1e5+23;

long long dp[N];

void solve() {
  dp[0] = 0;
  dp[1] = 1;
  for (int i = 2; i < N; ++i) {
    dp[i] = (dp[i-1]+dp[i-2]) % mod;
  }
  int n, m; scanf("%d%d", &n, &m);
  long long ans = 1;
  int p = 0;
  for (int c, i = 0; i < m; ++i, p = c) {
    scanf("%d", &c);
    if (!p)
      ans = (ans * dp[c-p]) % mod;
    else
      ans = (ans * dp[c-p-1]) % mod;
  }
  if (p)
    ans = (ans * dp[n-p]) % mod;
  else
    ans = (ans * dp[n-p+1]) % mod;
  printf("%lld", ans);
}

int main() {
  init();
  int t = 1; //scanf("%d", &t);
  while (t--) {
    solve();
  }
  return 0;
}


Measured memory_bytes: 4568
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pi 3.141592653589793116
#define mod 1e9+7
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>ordered_set;
int main() {
    off;
    int t;
    //cin>>t;
    t=1;
    while(t--){    
        int a,b;
        cin>>a>>b;
        cout<<(3*a+b)/2<<'\n';
    }
      return 0;
}

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

const int N = 105;
int A[2][N];
int P[2][N];
int main(){
	int n;
	cin >> n;
	for(int j = 0; j < 2; j++)
	for(int i = 1; i <= n; i++) cin >> A[j][i], P[j][i] = P[j][i - 1] + A[j][i];
	int ans = 0;
	for(int i = 1; i <= n; i++){
		ans = max(ans, P[0][i] + P[1][n] - P[1][i - 1]);
	}
	cout << ans;
}

Measured memory_bytes: 256
let solve h w h0 w0 = (h - h0) * (w - w0)

let read_ints () = read_line () |> Str.split (Str.regexp " ") |> List.map int_of_string

let _ =
  match read_ints () with
  | [h; w] ->
    (match read_ints () with
    | [h0; w0] -> solve h w h0 w0 |> string_of_int |> print_endline
    | _ -> ())
  | _ -> ()

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

int main(){
  long long N;
  cin >> N;
  vector<long long> ai(N);
  int botton=0,count=0;
  
  for(int i=0;i<N;i++){
    cin >> ai.at(i);
  }
  while(botton<N){
    botton = (ai.at(botton)-1);
    count++;
    if(botton==1){
      cout << count << endl;
      break;
    }
    if(count >= N){
      cout << -1 << endl;
      break;
    }
  }
}

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


using namespace std;

const int maxi=1e6;
int sme[maxi],cnt[maxi],t[maxi];
int a[1000][1000];
int pok;
int n,m;
int main()
{
   cin>>n>>m;

   for (int i=1;i<=n;i++)
    for (int j=1;j<=m;j++)
     cin>>a[i][j];

   int ans=n;

  for (int i=1;i<=n;i++)
    t[i]=1;

   for (int j=1;j<=m;j++){

    for (int i=1;i<=m;i++)
        cnt[i]=0;
   int mm=0;
   for (int i=1;i<=n;i++){
    while(sme[a[i][t[i]]]==1 && t[i]<=m) t[i]++;
     if (t[i]>m) pok=1;
     cnt[a[i][t[i]]]++;
     mm=max(mm,cnt[a[i][t[i]]]);
   }
   if (pok) break;
   ans=min(ans,mm);
   for (int i=1;i<=m;i++)
    if (sme[i]==0 && cnt[i]>=ans) sme[i]=1;
 }
     cout<<ans;
     return 0;
}


Measured memory_bytes: 7552
#include <bits/stdc++.h>
#include<algorithm>
#define int long long
using namespace std;
typedef pair<int,int> P;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define INF 1000000000000
int MOD=1000000007;
int modpow(int a,int x){
  int ans=1;
  while(x>0){
    if(x&1) ans=ans*a%MOD;
      a=a*a%MOD;
      x>>=1;
  }
  return ans;
}
int gyaku(int n){
    return modpow(n,MOD-2);
}
signed main() {
  int n;
  cin>>n;
  if(n%1000==0)cout<<0;
  else cout<<1000-n%1000;
}


Measured memory_bytes: 3596
#include <iostream>
#include <cstring>
#include <algorithm>

void block(int n, int m, int* stack, int top)
{
	if( n==0 ){
		for(int i=0; i<top-1; i++)
			printf("%d ",stack[i],i);
		printf("%d\n",stack[top-1],top-1);
		return;
	}
	for(int i=std::min(n,m); i>0; i--){
		stack[top] = i;
		//for(int j=0; j<=top; j++)printf("%d,",stack[j]);puts("");
		block(n-i,i,stack,top+1);
	}
	return ;
}

int main()
{
	int n;
	int stack[32];
	while(std::cin>>n,n){
		block(n,n,stack,0);
	}
	return 0;
}

Measured memory_bytes: 0
#define __USE_MINGW_ANSI_STDIO 0
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
#define int ll
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VL;
typedef vector<VL> VVL;
typedef pair<int, int> PII;

#define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define ALL(x) x.begin(), x.end()
#define IN(a, b, x) (a<=x&&x<b)
#define MP make_pair
#define PB push_back
#ifdef int
const ll INF = (1LL<<60);
#else
const int INF = (1LL<<30);
#endif
const double PI = 3.14159265359;
const double EPS = 1e-12;
const int MOD = 1000000007;

template <typename T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template <typename T> T &chmax(T &a, const T &b) { return a = max(a, b); }
template<class S,class T>
ostream &operator <<(ostream& out,const pair<S,T>& a){
  out<<'('<<a.first<<','<<a.second<<')';
  return out;
}

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

signed main(void)
{
  int x, y;
  cin >> x >> y;

  x *= 2;
  int cnt = 1;
  while(x < y) {
    // cout << x << endl;
    x *= 2;
    cnt++;
  }
  if(x == y) cnt++;

  cout << cnt << endl;

  return 0;
}


Measured memory_bytes: 256
#!/usr/bin/env python3
import sys
import string

l = [c for c in string.ascii_lowercase]
def f(N: int):
    N -= 1
    if N // 26:
        return f(N//26) + l[N%26]
    else:
        return l[N%26]

def solve(N):
    print(f(N))

# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    solve(N)

if __name__ == '__main__':
    main()


Measured memory_bytes: 9916
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<ll> vl;
#define rep(i, n) for(ll i = 0;i < n;i++)
#define all(i) i.begin(), i.end()
template<class T, class U> void cmax(T& a, U b) { if (a<b) a = b; }
template<class T, class U> void cmin(T& a, U b) { if (a>b) a = b; }

template<typename T>
struct BIT {
  // 1-indexed
  int n;
  vector<T> bit;

  BIT(int n_, T d):n(n_), bit(n_+1, d) {}

  void add(int i, T a) {
    if (i == 0) return;
    for (int x = i; x <= n; x += x&-x) {
      bit[x] += a;
    }
  }

  T sum(int i) {
    T s = bit[0];
    for (int x = i; x > 0; x -= x&-x) {
      s += bit[x];
    }
    return s;
  }

  T sum_between(int l, int r) {
    return sum(r) - sum(l-1);
  }

  // bit[1] + bit[2] + ... + bit[x] >= w;
  int lower_bound(T w){
    if (w <= 0) return 0;
    int x = 0, r = 1;
    while (r < n) r <<= 1;
    for (int k = r; k > 0; k >>= 1){
      if(x+k <= n && bit[x+k] < w){
        w -= bit[x+k];
        x += k;
      }
    }
    return x+1;
  }

  void add0(int i, T a) {
    add(i+1, a);
  }

  T sum0(int i) {
    return sum(i+1);
  }

  T sum_between0(int l, int r) {
    return sum(r+1) - sum(l);
  }
};

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

  int n;
  cin >> n;
  vector<int> q(n), a(n), b(n), aa;
  rep(i, n) {
    cin >> q[i];
    if (q[i] == 1) {
      cin >> a[i] >> b[i];
      aa.push_back(a[i]);
    }
  }

  sort(all(aa));
  aa.erase(unique(all(aa)), aa.end());
  map<int, int> dict;
  int size = aa.size();
  rep(i, size) {
    dict[aa[i]] = i;
  }

  BIT<ll> bitnum(size, 0);
  BIT<ll> bitsum(size, 0);

  ll cnt = 0, fconst = 0;
  rep(i, n) {
    if (q[i] == 1) {
      bitnum.add(dict[a[i]]+1, 1);
      bitsum.add(dict[a[i]]+1, a[i]);
      cnt++;
      fconst += b[i];
    } else {
      int idx = bitnum.lower_bound((cnt+1)/2);

      ll ans = 0;
      ans += aa[idx-1] * bitnum.sum_between(1, idx-1);
      ans -= bitsum.sum_between(1, idx-1);
      ans += bitsum.sum_between(idx+1, size);
      ans -= aa[idx-1] * bitnum.sum_between(idx+1, size);

      cout << aa[idx-1] << " " << ans+fconst << endl;
    }
  }
}







































































































Measured memory_bytes: 11640
#include <algorithm>
#include <iostream>
#include <vector>
#include <math.h>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <queue>
#include <iomanip>
#include <numeric>
#include <tuple>
#include <bitset>
#include <complex>
#include <unistd.h>
#include <cassert>
#include <cctype>
#include <random>
#include <time.h>
#define _USE_MATH_DEFINES
#define _GLIBCXX_DEBUG
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> plglg;
typedef pair<double, ll> pdlg;
typedef tuple<int, int, int> tiii;
typedef tuple<ll, ll, ll> tlglglg;
typedef tuple<double, double, double> tddd;
typedef complex<double> xy_t;
typedef vector<ll> vll;
typedef vector< vector<ll> > matrix;
#define REP(i, x, y) for(ll i = (ll)x; i < (ll)y; i++)
#define DREP(i, x, y, d) for(ll i = (ll)x; i < (ll)y; i += (ll)d)
#define PER(i, x, y) for(ll i = (ll)x; i > (ll)y; i--)
#define DPER(i, x, y, d) for(ll i = (ll)x; i > (ll)y; i -= (ll)d)
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
double pi = 3.141592653589793;
ll mod = 1000000007;
int intmax = 2147483647;
int intmin = -2147483648;
ll llmax = 9223372036854775807;
ll llmin = -9223372036854775807;
int iinf = intmax / 8;
ll inf = llmax / 8;
double eps = 1e-12;

int main() {
    ll A, B;
    cin >> A >> B;
    if (B % A == 0) {
        cout << A + B << endl;
    } else {
        cout << B - A << endl;
    }
}


Measured memory_bytes: 256
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <set>
#include <map>
#include <queue>
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <cctype>
#include <cassert>
#include <limits>
#include <functional>
#include <iomanip>
#include <complex>
#include <bitset>
#include <stack>
 
using namespace std;
 
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define rer(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i))
#define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i))
#if defined(_MSC_VER) || __cplusplus > 199711L
#define aut(r,v) auto r = (v)
#else
#define aut(r,v) __typeof(v) r = (v)
#endif
#define each(it,o) for(aut(it, (o).begin()); it != (o).end(); ++ it)
#define all(o) (o).begin(), (o).end()
#define pb(x) push_back(x)
#define mp(x,y) make_pair((x),(y))
#define mset(m,v) memset(m,v,sizeof(m))
#define INF 0x3f3f3f3f3f3f3f3fLL
#define SIZE 200105
#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
 
typedef vector<int> vi; typedef pair<int, int> pii; typedef vector<pair<int, int> > vpii; typedef long long ll;
typedef pair<int,ll> pill; typedef pair<ll,int> plli; 
typedef pair<double, int> pdi;
template<typename T, typename U> inline void amin(T &x, U y) { if(y < x) x = y; }
template<typename T, typename U> inline void amax(T &x, U y) { if(x < y) x = y; }
typedef complex<double> P;
ll MOD = 1000000007;
//ll MOD=998244353;
typedef ll Weight;
struct Edge {
	int src, dst;
	Weight weight;
};
bool operator < (const Edge &e, const Edge &f) {
	return e.weight != f.weight ? e.weight > f.weight : // !!INVERSE!!
	e.src != f.src ? e.src < f.src : e.dst < f.dst;
}
typedef vector<Edge> Edges;
int N,M;
pair<int,pii > dp[3005][3005];
int main(){
	string s,t;
	cin>>s>>t;
	int n=s.size(),m=t.size();
	rep(i,n)rep(j,m)dp[i][j]=mp(0,mp(-1,-1));
	for(int i=n-1;i>=0;i--){
		
		for(int j=m-1;j>=0;j--){
			if(s[i]==t[j]){
				dp[i][j]=mp(1+dp[i+1][j+1].first,mp(i,j));
				
			}else{
				dp[i][j]=dp[i+1][j];
				if(dp[i][j+1].first>dp[i+1][j].first){
					dp[i][j]=dp[i][j+1];
				}
			}
		}
	}
	int cnt=dp[0][0].first;
	int x=0,y=0;
	while(cnt--){
		pii num = dp[x][y].second;
		cout<<s[num.first];
		x=num.first+1;
		y=num.second+1;
	}
	cout<<endl;
}

Measured memory_bytes: 105856
#define DEBUG 0

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

#if DEBUG
// basic debugging macros
int __i__,__j__;
#define printLine(l) for(__i__=0;__i__<l;__i__++){cout<<"-";}cout<<endl
#define printLine2(l,c) for(__i__=0;__i__<l;__i__++){cout<<c;}cout<<endl
#define printVar(n) cout<<#n<<": "<<n<<endl
#define printArr(a,l) cout<<#a<<": ";for(__i__=0;__i__<l;__i__++){cout<<a[__i__]<<" ";}cout<<endl
#define print2dArr(a,r,c) cout<<#a<<":\n";for(__i__=0;__i__<r;__i__++){for(__j__=0;__j__<c;__j__++){cout<<a[__i__][__j__]<<" ";}cout<<endl;}
#define print2dArr2(a,r,c,l) cout<<#a<<":\n";for(__i__=0;__i__<r;__i__++){for(__j__=0;__j__<c;__j__++){cout<<setw(l)<<setfill(' ')<<a[__i__][__j__]<<" ";}cout<<endl;}

// advanced debugging class
// debug 1,2,'A',"test";
class _Debug {
    public:
        template<typename T>
        _Debug& operator,(T val) {
            cout << val << endl;
            return *this;
        }
};
#define debug _Debug(),
#else
#define printLine(l)
#define printLine2(l,c)
#define printVar(n)
#define printArr(a,l)
#define print2dArr(a,r,c)
#define print2dArr2(a,r,c,l)
#define debug
#endif

// define
#define MAX_VAL 999999999
#define MAX_VAL_2 999999999999999999LL
#define EPS 1e-6
#define mp make_pair
#define pb push_back

// typedef
typedef unsigned int UI;
typedef long long int LLI;
typedef unsigned long long int ULLI;
typedef unsigned short int US;
typedef pair<int,int> pii;
typedef pair<LLI,LLI> plli;
typedef vector<int> vi;
typedef vector<LLI> vlli;
typedef vector<pii> vpii;
typedef vector<plli> vplli;

// ---------- END OF TEMPLATE ----------

int A[18];
LLI dp[2600][2600],dp2[2600][2600];
int main() {
    int i;
    int N;
    scanf("%d",&N);
    for (i = 0; i < N; i++) scanf("%d",&A[i]);
    if (N == 2) {
        printf("%d\n",A[0]+A[1]);
        return 0;
    }

    int j,k,l;
    for (i = 0; i < 2600; i++) {
        for (j = 0; j < 2600; j++) dp[i][j] = 1e18;
    }
    for (i = 2; i < N+10; i++) dp[1][i] = A[0]+(LLI) i*A[1];
    for (i = 2; i < N; i++) {
        for (j = 0; j < 2600; j++) {
            for (k = 0; k < 2600; k++) dp2[j][k] = 1e18;
        }
        for (j = 1; j < 2600; j++) {
            for (k = 1; k < 2600; k++) {
                if (dp[j][k] > 1e17) continue;
                for (l = k-(j % k); l < 2600; l += k) {
                    if ((i == N-1) || (l >= 2)) dp2[k][l] = min(dp2[k][l],dp[j][k]+(LLI) l*A[i]);
                }
            }
        }
        for (j = 0; j < 2600; j++) {
            for (k = 0; k < 2600; k++) dp[j][k] = dp2[j][k];
        }
    }
    LLI ans = 1e18;
    for (i = 2; i < N+10; i++) ans = min(ans,dp[i][1]);
    printf("%lld\n",ans);

    return 0;
}



Measured memory_bytes: 105984
#include <iostream>
#include <vector>

using namespace std;

vector<int> Prime;
void PrimeCalc()
{
	bool IsPrime[1000000];
	for(int i = 0; i < 1000000; ++i)
	{
		IsPrime[i] = true;
	}
	IsPrime[0] = IsPrime[1] = false;
	for(int i = 2; i < 1000000; ++i)
	{
		if(IsPrime[i])
		{
			Prime.push_back(i);
			for(int j = 2 * i; j < 1000000; j += i)
			{
				IsPrime[j] = false;
			}
		}
	}
}

void solve()
{
	PrimeCalc();
	int n;
	while(cin >> n)
	{
		int ans = 0;
		int pos = 0;
		for(int i = 0; i < Prime.size(); ++i)
		{
			if(Prime[i] <= n)
			{
				++ans;
			}
			else
			{
				break;
			}
		}
		cout << ans << endl;
	}
}

int main()
{
	solve();
	return(0);
}

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

#define int long long

const int MAX = 1e6 + 10; 
const int OO = 0x3f3f3f3f3f3f3f3f;
const double EPS = 1e-6; 
const long long MOD = 1000000007;

#define bug(x) cout << #x << " = " << x << '\n'
#define _ << " , " <<
#define FOR(i, a, n) for(int i = a; i < n; i++)
#define REP(i, n) FOR(i, 0, n)
#define fi first
#define se second
#define pb push_back
#define mt make_tuple
#define all(vetor) vetor.begin(), vetor.end()
#define X real()
#define Y imag()
#define sc(a) scanf(" %lld", &a)
//#define gc getchar_unlocked

typedef long long ll;
typedef long double ld;
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
typedef complex<ll> Pll;
typedef complex<ld> Pld;

int n, dp[5005][5005];
ii arr[MAX];

int32_t main()
{
	cin >> n;
	REP(i, n) cin >> arr[i + 1].fi >> arr[i + 1].se;
	sort(arr + 1, arr + n + 1, [](ii a, ii b){ return a.fi + a.se < b.fi + b.se; });
	memset(dp, 63, sizeof dp);
	for(int i = 0; i <= n; i++)
		dp[i][0] = 0;
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= n; j++)
			if(dp[i - 1][j - 1] > arr[i].fi)
				dp[i][j] = dp[i - 1][j];
			else
				dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1] + arr[i].se);
	int ans = 0;
	for(int i = 1; i <= n; i++) if(dp[n][i] < OO) ans = i;
	cout << ans << '\n';

	return 0;
}

Measured memory_bytes: 197376
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
    int a,b;
    while(cin >> a >> b) {
        double ans = a * b / 33057850.0;
        printf("%lf\n", ans * 10000000);
    }
    return 0;
}

Measured memory_bytes: 1188
import math

def read():
    X = int(input().strip())
    return X,


def solve(X):
    if X >= 2000:
        return 1
    A = [100 ,101, 102, 103, 104, 105]
    NA = 6
    dp = [[False for j in range(X+1)] for i in range(NA+1)]
    for i in range(NA+1):
        dp[i][0] = True
    for i in range(NA):
        for x in range(0, X+1):
            j = 0
            while x - j * A[i] >= 0:
                if dp[i][x - j * A[i]]:
                    dp[i+1][x] = True
                j += 1
    return 1 if dp[NA][X] else 0
    
if __name__ == '__main__':
    inputs = read()
    output = solve(*inputs)
    print("%d" % output)


Measured memory_bytes: 39408
import java.util.Scanner;
import java.util.*;
import java.util.Arrays;
public class Main{
    public static void main(String[] args) {
        Scanner sca = new Scanner(System.in);
        
        seSearch(sca);
        }
    public static int seSearch(Scanner c){
        int n = c.nextInt();
         int[] count = new int[n];
       
        for(int i = 0 ; i < n ; ++i){
            count[i]=c.nextInt();
        }
        for(int i = 1 ; i <= n ; i ++){
            System.out.print("node "+i+": key = "+count[i-1]+", ");
            if(i/2>0){
                System.out.print("parent key = "+count[i/2-1]+", ");
            }
            if(2*i<=n){
                System.out.print("left key = "+count[i*2-1]+", ");
            }
            if(2*i+1<=n){
                System.out.print("right key = "+count[i*2]+", ");
            }    
            System.out.println("");
        }
    return n;

    }
}


Measured memory_bytes: 27504
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Math;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            A();
        }

        static void A()
        {
            var N = ReadInt();
            var d = ReadSplitInt();

            var ans = 0;
            for (int i = 0; i < N-1; i++)
            {
                for (int j = i + 1; j < N; j++)
                    ans += d[i] * d[j];
            }
            Println(ans);
        }

        static List<long> ReadLines(long n)
        {
            var l = new List<long>();
            for (long i = 0; i < n; i++)
            {
                l.Add(ReadLong());
            }
            return l;
        }

        static void YESOrNO(bool e) => Println(e ? "YES" : "NO");

        static void YesOrNo(bool e) => Println(e ? "Yes" : "No");

        static IEnumerable<int> Range(int start, int stop)
        {
            if (start < 0 || stop < 0 || start > stop || (start <= 0 && stop <= 0))
                return new List<int>();

            return Enumerable.Range(start, stop - start);
        }

        static bool IsDigit(string str)
        {
            var i = 0;
            return int.TryParse(str, out i);
        }

        static int SumDigits(long num)
        {
            return num.ToString().Select(x => x.ToString()).Sum(int.Parse);
        }

        static int[] ToIntArray(string str)
        {
            return str.Select(x => x.ToString()).Select(int.Parse).ToArray();
        }

        static long Gcd(long a, long b) => b == 0 ? a : Gcd(b, a % b);
        static long Lcm(long a, long b) => a / Gcd(a, b) * b;

        static bool IsPrime(int x)
        {
            if (x <= 1 || (x != 2 && x % 2 == 0)) return false;
            if (x == 2) return true;

            for (int i = 3; i < x; i += 2)
                if (x % i == 0) return false;

            return true;
        }

        static string Read() => Console.ReadLine();
        static int ReadInt() => int.Parse(Read());
        static long ReadLong() => long.Parse(Read());

        static List<string> ReadSplit() => Read().Split().ToList();
        static List<int> ReadSplitInt() => Read().Split().Select(int.Parse).ToList();
        static List<long> ReadSplitLong() => Read().Split().Select(long.Parse).ToList();

        static void Print(object value) => Console.Write(value.ToString());
        static void Println(object value) => Console.WriteLine(value.ToString());
        static string Join<T>(IEnumerable<T> list) => string.Join("", list);
    }

    public static class MyExtensions
    {
        public static string Slice(this string str, int start = 0, int stop = 0)
        {
            if (start > str.Length || stop > str.Length || start < 0 || stop < 0)
                return "";

            if (stop == 0) stop = str.Length;
            return str.Substring(start, stop - start);
        }
    }
}



Measured memory_bytes: 11476
fn main(){
    let mut sc = Scanner::new();
    while sc.read() {
        let n = sc.next();
        let m = sc.next();
        let mut a = vec![];
        let mut b = vec![];
        for _ in 0..n {
            let l: String = sc.next();
            a.push(l.into_bytes());
        }
        for _ in 0..m {
            let l: String = sc.next();
            b.push(l.into_bytes());
        }

        let mut yes = false;
        'outer: for i in 0..(n-m+1) {
            for j in 0..(n-m+1){
                let mut same = true;
                'innter: for k in 0..m {
                    for l in 0..m {
                        if a[i+k][j+l] != b[k][l] {
                            same = false;
                            break 'innter;
                        }
                    }
                }
                if same {
                    yes = true;
                    break 'outer;
                }
            }
        }
        println!("{}", if yes { "Yes" } else { "No" });
    }
}

#[allow(dead_code)]
struct Scanner {
    buf: Vec<u8>, i: usize, next: Option<String>,
}

#[allow(dead_code)]
impl Scanner {
    fn new() -> Scanner {
        Scanner { buf: vec![], i: 0, next: None, }
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        self.wrapped::<T>().unwrap()
    }

    fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        let mut res = Vec::<T>::with_capacity(n);
        for _ in 0..n { res.push(self.next()) }
        res
    }

    fn wrapped<T: std::str::FromStr>(&mut self) -> Option<T> {
        self.read();
        self.next.take().and_then(|s| s.parse::<T>().ok())
    }

    fn read(&mut self) -> bool {
        if self.next.is_some() { return true }
        let mut s = String::with_capacity(16);
        while let Some(c) = self.get_char() {
            if !c.is_whitespace() { s.push(c); }
            else if !s.is_empty() { break; }
        }
        self.next = if !s.is_empty() { Some(s) } else { None };
        self.next.is_some()
    }

    fn get_char(&mut self) -> Option<char> {
        if self.i >= self.buf.len() {
            use std::io::BufRead;
            let reader = std::io::stdin();
            let mut buffer = reader.lock();
            let len = match buffer.fill_buf() {
                Ok(bytes) => {
                    self.buf.resize(bytes.len(), b'\0');
                    self.buf.copy_from_slice(bytes);
                    Some(bytes.len())
                },
                Err(_) => None,
            };
            self.i = 0;
            if len.is_some() { buffer.consume(len.unwrap()); }
            if len.is_none() || len.unwrap() == 0 { return None }
        }
        self.i += 1;
        Some(self.buf[self.i - 1] as char)
    }
}


Measured memory_bytes: 4352
#include<stdio.h>

int main(){
  long n = 0;
  long a[200000] = {};
  long b[500000] = {};
  long i = 0;
  scanf("%ld",&n);
  for(i=0;i<n;i++){
    scanf("%ld",&a[i]);
  }
  for(i=0;i<500000;i++){
    b[i] = -1;
  }
  if(n != 1){
    b[249999]=a[1];
  }
  b[250000]=a[0];
  
  for(i=2;i<n;i++){
    if(i % 2 == 0){
      b[250000 + i/2] = a[i];
    }else{
      b[249999 - i/2] = a[i];
    }
  }
  if(n%2==0){
    for(i=0;i<500000;i++){
      if(b[i] != -1){
        printf("%ld ",b[i]);
      }
    }
  }else{
    for(i=499999;i>0;i--){
      if(b[i] != -1){
        printf("%ld ",b[i]);
      }
    }
  }
  return 0;
}
  

Measured memory_bytes: 7552
# あなたは整数 x を持っています。最初、x=0 です。
# あなたは、長さ N の文字列 S をもらったので、
# これを使って N 回の操作を行いました。 
# i 回目の操作では、Si=I ならば x の値を 1 増やし、
# Si=D ならば x の値を 1 減らしました。
# 操作の途中( 1 回目の操作の前、N 回目の操作の後も含む)で 
# x がとる値の最大値を答えてください。

# 情報を準備、取得
x = 0
n = gets.chomp.to_i
s = gets.chomp

# それぞれの操作ごとのxの状態を格納する配列を宣言
state = [x]

# 操作を実行
n.times do |i|
  case s[i]
  when "I"
    x += 1
  when "D"
    x -= 1
  end
  
  state << x
end

# 結果を出力
puts state.sort.last

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

using namespace std;
#define rep(i,n) for(long long i=0; i<(long long)(n);i++)
//rep…「0からn-1まで」の繰り返し
#define rep2(i,s,n) for(long long i=s; i<=(long long)(n);i++)
//rep2…「sからnまで」の繰り返し
#define repr(i,s,n) for(long long i=s;i>=(long long)(n);i--)
//repr…「ｓからnまで」の降順の繰り返し

typedef long long ll;

const int inf = 1e9+7;
const int mod = 1e9+7;

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

    int ans=0;

    if(n.size()==1){
        cout<<n<<endl;
    }

    else {
        bool jdg=true;
        rep2(i,1,n.size()-1){
            if(n[i]!='9'){
                jdg=false;
                break;
            }
        }

        if(jdg) ans=(n[0]-'0')+9*(n.size()-1);
        else ans=(n[0]-'1')+9*(n.size()-1);

        cout<<ans<<endl;
    }
}


Measured memory_bytes: 3592
#include <stdio.h>
#include <cmath>
#include <bits/stdc++.h>



using namespace std;

typedef vector<int> VI;
typedef vector<string> VS;


//container util
#define SORT(c) sort((c).begin(),(c).end())

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



int main(void){

	int A,B,K; scanf("%d %d %d", &A, &B, &K);

	int count = 0;
	int ans = 0;
	for(int i=min(A+1,B+1); i >= 0; --i){

		if(count == K) break;
		else{
			if(A%i == 0 and B%i == 0){
				count++;
				ans = i;
				// printf("%d\n", ans);
			}
		}
	}

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

	return 0;

}


Measured memory_bytes: 256
from math import gcd
from collections import defaultdict as d
n=int(input())
m=10**9+7
s=d(lambda:[0,0])
p=-1
for i in range(n):
    a,b=map(int,input().split())
    if a==b==0:p+=1
    else:
        g=gcd(a,b)
        a=a//g
        b=b//g
        if a<0 or a==0<b:a,b=-a,-b
        if b<0:s[(-b,a)][1]+=1
        else:s[(a,b)][0]+=1
q=1
for i in s:
    k,l=s[i]
    q=q*(pow(2,k,m)+pow(2,l,m)-1)%m
print((q+p)%m)

Measured memory_bytes: 60588
d = int(input())
c_l = list(map(int,input().split()))
s_l = [list(map(int,input().split())) for i in range(d)]

def calc(t_l, last_l, day):
  ans = 0
  for day in range(d):
#    print(t_l,day)
    contest_num = t_l[day]
    contest_num -= 1

    contest_val = s_l[day][contest_num]
    ans += contest_val

    t_last_l = last_l[:]
    t_last_l[contest_num] = day

    for i in range(26):
      ans -= c_l[i] * (day - t_last_l[i])

    return ans

last_l = [-1 for i in range(26)]
ans = []
point = 0

for day in range(d):
  each_point = 0
  each_contest_num = 0

  t_ans = ans[:]
  for temp_contest_num in range(26):
    temp_point = calc(t_ans+[temp_contest_num], last_l, day)
    if temp_point > each_point:
      each_point = temp_point
      each_contest_num = temp_contest_num

  last_l[each_contest_num] = day
  ans.append(each_contest_num + 1)
  point += each_point

for i in ans:
  print(i)

Measured memory_bytes: 68584
#include <algorithm>
#include <bitset>
#include <cmath>
#include <iostream>
#include <iterator>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <utility>
#include <unordered_map>
#include <unordered_set>
using namespace std;

#define ABS(a) (((a) >= 0) ? (a) : -(a))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#define FOR(i, a, b) for (int i = (a); i <= (b); ++i)
#define RFOR(i, a, b) for (int i = (a); i >= (b); --i)
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define NINTH_POWER_OF_TEN 1000000000
#define int long long

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

const int kMaxM = 60;

int L;
int N, M;
int u[kMaxM], v[kMaxM], w[kMaxM];

int Pow(int a, int b) {
  int r = 1;
  REP(i, b) { r *= a; }
  return r;
}

signed main() {
  cin >> L;

  int n = 0;
  int L2 = L;
  while (L2 != 1) {
    L2 /= 2;
    ++n;
  }

  N = n+1;

  M = 0;
  int tmpw = 1;
  REP(i, n) {
    u[2*i] = i; v[2*i] = i+1; w[2*i] = tmpw;
    u[2*i+1] = i; v[2*i+1] = i+1; w[2*i+1] = 0;
    tmpw *= 2;
    M += 2;
  }
  int ii = 2*n;
  L -= tmpw;
  int tmpb = tmpw/2;
  REP(i, n) {
    if (L/tmpb == 1) {
      u[ii] = n-(i+1); v[ii] = n; w[ii] = tmpw;
      ++ii; ++M;
      tmpw += tmpb;
    }
    L %= tmpb;
    tmpb /= 2;
  }

  cout << N << " " << M << endl;
  REP(i, M) { cout << u[i]+1 << " " << v[i]+1 << " " << w[i] << endl; }
  return 0;
}


Measured memory_bytes: 256
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
 
 
public class Main {
     
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        while(true){
        	final int n = sc.nextInt();
        	
        	if(n == 0){
        		break;
        	}
        	
        	double[] pos = new double[9];
        	
        	for(int i = 0; i < 9; i++){
        		pos[i] = 0;
        	}
        	
        	final int start = sc.next().toCharArray()[0] - 'A';
        	final int end = sc.next().toCharArray()[0] - 'A';
        	final int not = sc.next().toCharArray()[0] - 'A';
        	
        	pos[start] = 1;
        	
        	double[] next = new double[9];
        	
        	for(int i = 0; i < n; i++){
        		
        		for(int j = 0; j < 9; j++){
        			next[j] = 0;
        		}
        		
        		//System.out.println(Arrays.toString(pos));
        		
        		for(int j = 0; j < 9; j++){
        			if(j % 3 != 0 && not != j - 1){
        				next[j-1] += pos[j] / 4;
        			}else{
        				next[j] += pos[j] / 4;
        			}
        			
        			if(j % 3 != 2 && not != j + 1){
        				next[j+1] += pos[j] / 4;
        			}else{
        				next[j] += pos[j] / 4;
        			}
        			
        			if(j / 3 != 0 && not != j - 3){
        				next[j-3] += pos[j] / 4;
        			}else{
        				next[j] += pos[j] / 4;
        			}
        			
        			if(j / 3 != 2 && not != j + 3){
        				next[j+3] += pos[j] / 4;
        			}else{
        				next[j] += pos[j] / 4;
        			}
        		}
        		
        		double[] tmp = next;
        		next = pos;
        		pos = tmp;
        	}
        	//System.out.println(Arrays.toString(pos));
        	System.out.printf("%.8f\n",pos[end]);
        }
    }
 
}

Measured memory_bytes: 12000
from collections import defaultdict
from heapq import heappop, heappush


class Graph(object):
    """
    隣接リストによる有向グラフ
    """

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()


class Dijkstra(object):
    """
    ダイクストラ法（二分ヒープ）による最短経路探索
    計算量: O((E+V)logV)
    """

    def __init__(self, graph, start):
        self.g = graph.graph

        # startノードからの最短距離
        # startノードは0, それ以外は無限大で初期化
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[start] = 0

        # 最短経路での1つ前のノード
        self.prev = defaultdict(lambda: None)

        # startノードをキューに入れる
        self.Q = []
        heappush(self.Q, (self.dist[start], start))

        while self.Q:
            # 優先度（距離）が最小であるキューを取り出す
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, weight in self.g[u]:
                alt = dist_u + weight
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q, (alt, v))

    def shortest_distance(self, goal):
        """
        startノードからgoalノードまでの最短距離
        """
        return self.dist[goal]

    def shortest_path(self, goal):
        """
        startノードからgoalノードまでの最短経路
        """
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]
        return path[::-1]
    
N, u, v = map(int, input().split())
g = Graph()
for i in range(N-1):
    a, b = map(int, input().split())
    g.add_edge(a, b, 1)
    g.add_edge(b, a, 1)
d1 = Dijkstra(g, u)
d2 = Dijkstra(g, v)

max_dist = 0
same_dist = 0

flag = d1.shortest_distance(v)%2

for i in range(1,N+1):
    s1 = d1.shortest_distance(i)
    s2 = d2.shortest_distance(i)
    if s1 < s2:
        if flag == 1:
            if s2-1 > max_dist:
                max_dist = s2-1
        else:
            if s2-1 > max_dist:
                max_dist = s2-1
    elif s1 == s2:
        if s1 < same_dist or same_dist==0:
            same_dist = s1

print(max(max_dist,same_dist))

Measured memory_bytes: 78632