akhauriyash/Code-Regression huggingface dataset:
def main():
    n = int(input())
    inlis= list(map(int, input().split()))
    ans = 0

    for i in range(n-1, -1, -1):
        #print(i)
        if inlis[i] != i+1:
            #print(i, inlis[i], i+1)
            break
        else:
            #print(inlis)
            #print("mae", inlis[i])
            if i-1 >= 0:
                a = inlis[i-1]
                inlis[i] = a
                inlis[i-1] = i+1
                ans += 1
                #print(inlis)
                
    if ans < n-1:
        #print(inlis)
        for i in range(n):
            if inlis[i] == i+1 and i+1 <= n-1:
                #print("ato", inlis[i])
                b = inlis[i+1]
                inlis[i] = b
                inlis[i+1] = i
                ans += 1
        
    print(ans)


    
if __name__ == "__main__":
    main()


Measured memory_bytes: 52332
fun main() {
  val n = readLine()!!.toInt()
  val s = Array(n) { readLine()!!.reversed() }.sortedArrayWith(compareBy { it.length })
  val trie = Trie()
  var x = 0L
  for (si in s) {
    x += trie.count(si)
    trie.insert(si)
  }
  println(x)
}
class Trie {
  private var size = 0
  private val childs = Array<Trie?>(26) { null }

  fun insert(s: String) {
    var node = this
    for (c in s) {
      val n = c - 'a'
      if (node.childs[n] == null) node.childs[n] = Trie()
      node = node.childs[n]!!
    }
    node.size++
  }

  fun count(s: String): Long {
    val cnt = IntArray(26)
    for (c in s) {
      val n = c - 'a'
      cnt[n]++
    }
    var res = 0L
    var node = this
    for (c in s) {
      for (i in cnt.indices) {
        if (cnt[i] > 0 && node.childs[i] != null) {
          res += node.childs[i]!!.size
        }
      }
      val n = c - 'a'
      if (node.childs[n] == null) break
      node = node.childs[n]!!
      cnt[n]--
    }
    return res
  }
}

Measured memory_bytes: 212112
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.next();
        int len = s.length();
        char prev = s.charAt(0);
        int streakLen = 1;
        List<Integer> l = new ArrayList<>();
        for(int i=1; i<len; i++) {
            char c = s.charAt(i);
            if(c==prev) {
                streakLen++;
            }
            else {
                l.add(streakLen * (prev == '>' ? -1 : 1));
                streakLen = 1;
                prev = c;
            }
        }
        l.add(streakLen * (prev == '>' ? -1 : 1));

        long sum = 0;
        for(int i=0; i<l.size(); i++) {
            int n = l.get(i);
            if(n>0) {
                sum += (long)n * (long)(n-1) / 2;
                if(i==l.size()-1) {
                    sum += n;
                }
            }
            else {
                n *= -1;
                sum += (long)n * (long)(n+1) / 2;
                if(i>0) {
                    sum += Math.max(n, l.get(i-1)) - n;
                }
            }
        }
        System.out.println(sum);
    }
}


Measured memory_bytes: 29596
n=int(input())
import queue
q=queue.Queue()
for i in range(1,10):
    q.put(i)
while n!=1:
    x=q.get();k=x%10
    for i in range(max(0,k-1),min(10,k+2)) :
        q.put(10*x+i)
    n-=1
print(q.get())

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

using namespace std;

int main(void){
    int n, m;
    cin>>n >> m;
    vector<int> l(m), r(m);

    for(int i = 0;i < m;i++)    cin >> l[i] >> r[i];

    int ans_bottom = l[0], ans_upper = r[0];

    for(int i = 1;i < m;i++){
        if(ans_bottom < l[i])   ans_bottom = l[i];
        if(ans_upper > r[i])    ans_upper = r[i];
    }

    if(ans_bottom > ans_upper)  cout << 0 << endl;
    else                        cout << ans_upper - ans_bottom + 1 << endl;

    return 0;
}

Measured memory_bytes: 1024
#include <stdio.h>

#define MAX 150000

void makePrime( int * prime, int * sum )
{
        int i = 0, num = 0, tmp = 0, j;
        for ( i = 0 ; i < MAX+1 ; i++ ) {
                prime[i] = 1;
                sum[i]   = 0;
        }

        prime[0] = 0;
        prime[1] = 0;

        for ( i = 2 ; i < MAX+1 ; i++ ) {
                if ( prime[i] == 1 )
                {
                        num++;
                        for ( j = i + i ; j < MAX+1 ; j = i + j ) {
                                prime[j] = 0;
                        }
                        sum[num] = sum[num-1] + i;
                }
        }
}

int main()
{
        int prime[MAX] = {};
        int sum[MAX] = {};
        int num;

        makePrime( prime, sum );
        while( 1 ) {
                scanf( "%d", &num );
                if ( num == 0 ) break;
                printf( "%d\n", sum[num] );
                num = 0;
        }
        return 0;
}



Measured memory_bytes: 2904
#include <bits/stdc++.h>
using namespace std;
int main() {
	int n;
	map<int, int> cnt;
	scanf("%d", &n);
	for (int i = 0; i < n; ++ i) {
		int x;
		scanf("%d", &x);
		cnt[x] ++;
	}
	set<int> tmp;
	long long ans = 0;
	for (auto t : cnt) if (t.second >= 2) {
		tmp.insert(t.first);
		if (t.second >= 4) ans = max(ans, 1LL * t.first * t.first);
	}
	if (tmp.size() >= 2) ans = max(ans, 1LL * *--tmp.end() * *----tmp.end());
	printf("%lld\n", ans);
}



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

using namespace std;

typedef long long int ll;

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

  ll n, m;
  cin >> n >> m;
  string s;
  cin >> s;
  reverse(s.begin(), s.end());
  vector < ll > v;
  for(int i = 0; i <= n; i++){
    if(s[i] == '0') v.push_back(i);
  }

  vector < ll > ans;
  for(int i = 0; i <= n; i++){
    if(i == n) break;
    auto it = upper_bound(v.begin(), v.end(), i + m);
    --it;
    if(*it == i){
      cout << -1 << endl;
      return 0;
    }
    ans.push_back(*it - i);
    i = *it - 1;
  }
  reverse(ans.begin(), ans.end());
  for(auto i : ans) cout << i << " ";
  cout << endl;
}


Measured memory_bytes: 2628
N = int(input())
h = list(map(int,input().split()))
count = 0
previousNum = 0
allNumberIsZero = False
while not allNumberIsZero:
    nonZeroExists = False
    for i in range(N):
        if h[i] > 0: nonZeroExists = True
        if previousNum == 0:
            if h[i] > 0:
                count += 1
                previousNum = h[i]
                h[i] -= 1
            else:
                previousNum = 0
        else:
            if h[i] > 0:
                previousNum = h[i]
                h[i] -= 1
            else:
                previousNum = 0
    previousNum = 0
    if not nonZeroExists: allNumberIsZero=True
print(count)

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

int main()
{
    int a[5];
    cin >> a[0] >> a[1] >> a[2] >> a[3] >> a[4];
    int b[5];
    for (size_t i = 0; i < 5; i++)
    {
        b[i] = ((a[i] - 1) / 10 + 1) * 10;
    }
    int ans = 100000;
    for (size_t i = 0; i < 5; i++)
    {
        int sum = 0;
        for (size_t j = 0; j < 5; j++)
        {
            if (i != j)
            {
                sum += b[j];
            }
            else
            {
                sum += a[j];
            }
        }
        ans = min(ans, sum);

        /* code */
    }
    cout << ans << endl;

    return 0;
}

Measured memory_bytes: 256
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int compare_int(const void *a, const void *b)
{
    return *(int*)a - *(int*)b;
//    return *(long long*)a - *(long long*)b;
}
//  qsort(A, b, sizeof(int), compare_int);

long long  factorial(long long n) {
    if (n > 0) {
        return n * factorial(n - 1);
    } else {
        return 1;
    }
}

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

int distance(int a, int b) {
  return abs(a-b)*abs(a-b);
}

//int ()



int main()
{
  int a ,b, c, d, e, X, Y;
//  long long  a, b, c, d, e, X, Y;
  //  double  c;
//  int  A[200003]={};
  int  A[100003]={};
  int  B[100003]={};
  int  C[100003][11]={};

  int  flg=0;

//  long long  a, b, c, d, X, Y;
  char s[101][101]={};
  char t[101]={};
//  int N, M;
//  int A[1000000001]={};
//  long long  C[101]={};
  int i,j,k;
  long long p,q;
//  int flag=0;
//  int tmp=0;
//  char tmp[101]={};
//  long long min=10000000000;
//  long long min=100000001;
  int len=0;
  int l=0;
  int r=1000001;
  int cnt=0;
  int num=0;
  int num1=0;
  int num2=0;
  int ans=0;
  int max=0;
  int sum=0;
  int addr=0;
  int ptn=0;
  long long  tmp=0;
//  bool on_off[100]={};
  
//  char alp[26]={'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'};

  //  a=0;
//  scanf("%lld %lld", &a, &b);
  scanf("%d%d", &a, &b);
  for(i=0;i<a;i++){
    scanf("%d", &c);

    if(c>=b) cnt++;
  }
   
  printf("%d\n",cnt);
  
return 0;
}


Measured memory_bytes: 128
#include <bits/stdc++.h>
#define err(args...) {}
#ifdef DEBUG
#include "_debug.cpp"
#endif
using namespace std;
using ll = long long;
using ld = long double;
template <typename T> using lim = numeric_limits<T>;
template <typename T> istream& operator>>(istream& is, vector<T>& a) { for(T& x : a) { is >> x; } return is; }
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n, T;
    cin >> n >> T;
    vector<int> c(n), t(n);
    for(int i = 0; i < n; i++) {
        cin >> c[i] >> t[i];
    }
    int ans = lim<int>::max();
    for(int i = 0; i < n; i++) {
        if(t[i] <= T) {
            ans = min(ans, c[i]);
        }
    }
    if(ans == lim<int>::max()) {
        cout << "TLE" << endl;
    } else {
        cout << ans << endl;
    }
    return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int i = 0; i < (n); i++)
#define all(v) v.begin(), v.end()
#define MOD 1000000007
const int INF = 1LL<<30;

int main(){
    int n;
    string s;
    cin>>n>>s;
    
    ll r=0,g=0,b=0;
    rep(i,n){
        if(s[i]=='R') r++;
        else if(s[i]=='G') g++;
        else b++;
    }

    ll ans=r*g*b;
    ll sub=0;
    rep(i,n){
        for(int j=i+1;j<n;j++){
            if(s[i]==s[j]) continue;
            int k=j+j-i;
            if(k>=n || s[k]==s[j] || s[k]==s[i]) continue;
            sub++;
        }
    }
    cout<<ans-sub<<endl;
}

Measured memory_bytes: 3568
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18;
const int INT_INF = 1e9;
const ll MOD = 1e9 + 7;
const int INT_MOD=1e9+7;
#define rep(i, n) for(int i = 0; i < n; i++)
#define REP(i, n) for(int i = 0; i <= n; i++)
#define rrep(i,n) for(int i=n;i>0;i--)
#define RREP(i,n) for(int i=n;i>=0;i--)
typedef pair<int, int> Pi;
typedef pair<double, double> P;

signed main(){
    int n,a[3003];cin>>n;
    ll dp[3003][3003]={};
    rep(i,n) cin>>a[i];
    RREP(i,n-1){
        for(int j=i;j<n;j++){
            if((n-i-j-1)%2==0){
                dp[i][j]=max(dp[i+1][j]+a[i],dp[i][j-1]+a[j]);
            }else{
                dp[i][j]=min(dp[i+1][j]-a[i],dp[i][j-1]-a[j]);
            }
        }
    }
    cout<<dp[0][n-1]<<endl;
    return 0;
}

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

using namespace std;

#define FOR(i,s,e) for((i)=(s);(i)<(int)(e);(i)++)

typedef long long ll;

const int INF = 1000000000;
const int N = 15;
const int M = 15;
int n, m;
int b[N], c[N], x[2][N];
int p[M];
bool check[2];
int xi[N], yi[N];

int main() {
	int i, j, k, l, num;
	scanf("%d%d ", &n, &m);
	num = 0;
	for (i=0; i<n; i++) {
		scanf("%d ", b+i);
		c[i] = b[i];
		if (b[i]) num++;
	}
	for (i=0; i<m; i++) scanf("%d ", p+i); 
	for (i=1; i<m; i++) p[i] += p[i-1];

	for (i=0; i<2; i++) {
		int bt = i % 2;
		k = 0;
		int numx = 0;
		for (j=0; j<n; j++) {
			if (j == p[k]) {
				bt = (bt+1) % 2;
				k++;
			}
			x[i][j] = bt;
			if (bt) numx++;
		}

		check[i] = (num == numx) ? true : false;
	}

/*
	printf("b:");
	for (j=0; j<n; j++)
		printf("%d ", b[j]);
	puts("");
	printf("p:");
	for (j=0; j<m; j++)
		printf("%d ", p[j]);
	puts("");

	for (i=0; i<2; i++) {
		printf("x[%d]:", i);
		for (j=0; j<n; j++) printf("%d ", x[i][j]);
		puts("");
	}
*/

	int res = INF;
	for (i=0; i<2; i++) {
		if (check[i]) {
			int cnt = 0;
			k = l = 0;
			for (j=0; j<n; j++) {
				if (x[i][j]) {
					xi[k] = j;
					k++;
				}
				if (b[j]) {
					yi[l] = j;
					l++;
				}
			}

/*
			printf("num = %d\n", num);

			printf("xi:");
			for (j=0; j<num; j++)
				printf("%d ", xi[j]);
			puts("");
			printf("yi:");
			for (j=0; j<num; j++)
				printf("%d ", yi[j]);
			puts("");
*/

			for (j=0; j<num; j++)
				cnt += abs(xi[j] - yi[j]);

			res = min(res, cnt);
		}
	}

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

	return 0;
}

Measured memory_bytes: 1196
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < n; i++)
#define rep2(i, x, n) for(int i = x; i <= n; i++)
#define rep3(i, x, n) for(int i = x; i >= n; i--)
#define elif else if
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ld, ld> pdd;
const ll MOD = 1e9+7;
const ll MOD2 = 998244353;
const int inf = INT_MAX;
const ll INF = LLONG_MAX;
const string alpha = "abcdefghijklmnopqrstuvwxyz";

int main(){
    int N, A[3];
    cin >> N >> A[2] >> A[1] >> A[0];
    int l[N], e[N];
    rep(i, N) cin >> l[i];
    e[0] = 1;
    rep2(i, 1, N-1) e[i] = 4*e[i-1];
    int ans = inf;
    rep(i, N-2) rep2(j, i+1, N-2) rep2(k, j+1, N-1){
        rep(p, e[N-3]){
            int tmp = 0, now = p, a[3];
            a[0] = l[i];
            a[1] = l[j];
            a[2] = l[k];
            rep(q, N){
                if(q == i||q == j||q == k) continue;
                elif(now%4 <= 2){
                    a[now%4] += l[q];
                    tmp += 10;
                }
                now /= 4;
            }
            sort(a, a+3);
            rep(i, 3){
                tmp += abs(A[i] - a[i]);
            }
            ans = min(ans, tmp);
        }
    }
    cout << ans << endl;
}

Measured memory_bytes: 256
#include <algorithm>
#include <cstdint>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <cfloat>

using namespace std;

using lint=int64_t;
using uint=uint32_t;
using ulint=uint64_t;

template<class T>
using vector2d=vector<vector<T>>;

template<class T>
bool UpdateMax(T &a, const T &b){
  if(a<b){
    a=b;
    return true;
  }else{
    return false;
  }
}

template<class T>
bool UpdateMin(T &a, const T &b){
  if(a>b){
    a=b;
    return true;
  }else{
    return false;
  }
}

template <class T>
void OutVec(const vector<T>& vec){
  for(int i = 0; i < vec.size() - 1; ++i){
    cout<<vec[i]<<" ";
  }
  cout<<vec.back()<<endl;
}

template <class T>
void OutVec2d(const vector2d<T>& vec){
  for(auto v:vec){
    OutVec(v);
  }
}

int main(){
  cout << std::fixed << std::setprecision(16);
  cin.tie(nullptr);
  std::ios::sync_with_stdio(false);

  lint n;
  cin>>n;

  lint result=0;
  unordered_map<lint,lint> fact_count;

  lint v=2;
  while(n>=v*v){
    if(n%v==0){
      n/=v;
      fact_count[v]++;
    }else{
      v++;
    }
  }
  if(n!=1){
    fact_count[n]++;
  }

  for(auto c:fact_count){
    int tmp_res=0;
    for(int i=1;i*(i+1)/2<=c.second;i++){
      tmp_res=i;
    }
    result+=tmp_res;
  }
  cout<<result<<endl;

  return 0;
}




Measured memory_bytes: 3656
#include <bits/stdc++.h>
#define _GLIBCXX_DEBUG
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep2(i, s, n) for (int i = s; i < (int)(n); i++)
#define Clear(a) a = decltype(a)();
typedef long long ll;
typedef vector<vector<ll>> vvl;
typedef vector<ll> vl;
typedef vector<vector<char>> vvc;
typedef vector<char> vc;
typedef pair<ll,ll> pll;
typedef priority_queue<string> priquestring;
typedef priority_queue<int> priqueint;
typedef priority_queue<ll> priquell;
typedef priority_queue<char> priquechar;
typedef priority_queue<string,vector<string>,greater<string>> rpriquestring;
typedef priority_queue<int,vector<int>,greater<int>> rpriqueint;
typedef priority_queue<ll,vector<ll>,greater<ll>> rpriquell;
typedef priority_queue<char,vector<char>,greater<char>> rpriquechar;
ll max(ll x,ll y){
if(x>y)return x;
else return y;
}
ll min(ll x,ll y){
  return x+y-max(x,y);
}

const ll big=1000000007;
int exp(int x,int y){
    if(y==0)return 1;//0^0=1
    if(x==1||x==0)return x;
    if(y%2==1)return (exp(x,y-1)*x)%big;
    int t=exp(x,y/2);
    return (t*t)%big;
}
void chmin(ll a,ll b){
    if(a>b)a=b;
    return;
}

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

void next(vector<int> &use){
    bool ans=true;
    int cnt=0;
    while(ans){
        use[cnt]++;
        if(use[cnt]<=2)ans=false;
        else use[cnt]=0;
        cnt++;
    }
}

int main(){
    ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    cout << fixed << setprecision(10);
    /*--------------------------------*/
    
    int n;cin >> n;
    vector<int> a(n),b(n);
    rep(i,n)cin >> a[i] >> b[i];
    sort(a.begin(),a.end());
    sort(b.begin(),b.end());
    if(n%2==1)cout << b[n/2]-a[n/2]+1 << endl;
    else{
        cout << (b[n/2]+b[n/2-1])-(a[n/2]+a[n/2-1])+1 << endl;
    }
    
}

Measured memory_bytes: 4784
#include <iostream>

using namespace std;

int main()
{
	int a[5], k, flag = 0;;
	
	for (int i = 0; i < 5; i++) {
		cin >> a[i];
	}
	
	cin >> k;
	
	for (int i = 0; i < 4; i++) {
		for (int j = i + 1; j < 5; j++) {
			if (a[j] - a[i] > k) {
				flag = 1;
				i = 4;
				break;
			}
		}
	}
	
	if (flag) {
		cout << ":(" << endl;
	}
	else {
		cout << "Yay!" << endl;
	}
	
	return 0;
}


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

int main(){
  ll N, M;
  cin >> N >> M;
  ll K = 1<<N;

  ll dp[K][M+1];
  for(ll k=0; k<K; ++k) for(ll m=0; m<M+1; ++m) dp[k][m] = (k>0) ? LLONG_MAX : 0;

  for(ll m=0; m<M; ++m){
    ll a, b;
    cin >> a >> b;

    ll x=0, c;
    for(ll i=0; i<b; ++i){
      cin >> c;
      x += 1<<(c-1);
    }

    for(ll k=0; k<K; ++k){
      dp[k][m+1] = dp[k][m];
    }

    for(ll k=0; k<K; ++k){
      if(dp[k][m]!=LLONG_MAX){
        dp[k|x][m+1] = min(dp[k|x][m+1], dp[k][m]+a);
      }
    }
  }

  if(dp[K-1][M]!=LLONG_MAX){
    cout << dp[K-1][M] << endl;
  }else{
    cout << -1 << endl;
  }


  return 0;
}

Measured memory_bytes: 32256
N, K = map(int, input().split())
alist = list(map(int, input().split()))
import math
K += N
sum_ = sum(alist)
ideal_denom = [(K / sum_) * a for a in alist]
min_denom = [math.floor(i_d) if math.floor(i_d) != 0 else 1 for i_d in ideal_denom]
max_denomed_alist = [a/m_d for a, m_d in zip(alist, min_denom) ]
min_denomed_alist = [a/(m_d+1) for a, m_d in zip(alist, min_denom)]

num_replace = K - sum(min_denom)

max_denomed_alist.sort(reverse=True)
ans = math.ceil(max_denomed_alist[num_replace])
 

print(ans)

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

using namespace std ;

#define int long long

int gcd(int x , int y){
    if( y == 0 ) return x ;
    else return gcd( y , x % y ) ;
}

signed main()
{
    int a , b ;
    cin >> a >> b  ;
    cout << a * b / gcd( a , b ) ;
}


Measured memory_bytes: 256
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<vector>
#include<set>
#include<sstream>
#include<cstring>
#include<cmath>
#include<map>
using namespace std;
typedef long long ll;
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin>>t;
	for(int a = 0;a<3;a++){
		if(t%10==7){
			cout<<"Yes";
			return 0;
		}
		t /= 10;
	}
	cout<<"No";
	return 0;
}


Measured memory_bytes: 3648
# ABC144E - Gluttony
def binary_search(upper_lim: int) -> int:
    ok, ng = upper_lim, -1
    while abs(ok - ng) > 1:
        mid = (ok + ng) // 2
        if check(mid):
            ok = mid
        else:
            ng = mid
    return ok


def check(x: int) -> bool:
    cost = sum(a - x // f for a, f in zip(A, F) if a * f > x)
    return cost <= K


def main():
    global K, A, F
    N, K, *AF = map(int, open(0).read().split())
    A, F = AF[:N], AF[N:]
    A.sort(), F.sort(reverse=1)
    ans = binary_search(A[-1] * F[0] + 1)
    print(ans)


if __name__ == "__main__":
    main()

Measured memory_bytes: 127800
# 公式解説を見てからやった
# 複数サイクルでき、1-K回移動可能
# N < 5000?多分、O(N * 2N)くらいで行けそうに見えるが。。。

if __name__ == "__main__":

	N,K = map(int,input().split())
	P = [ int(p)-1 for p in input().split() ]
	C = list(map(int,input().split()))

	# 一度計算したサイクル情報を一応キャッシュしておく。。。
	# あんまり意味なさそう
	cycleIDs = [ -1 for _ in range(N) ]
	cycleInfs = []


	# print(P)

	ans = -1e10
	cycleID = 0

	for n in range(N):

		v = n
		currentCycleItemCnt = 0
		currentCycleTotal = 0

		if cycleIDs[v] != -1:
			currentCycleItemCnt, currentCycleTotal = cycleInfs[ cycleIDs[v] ]
			# print(currentCycleItemCnt, currentCycleTotal)
		else:
			while True:
				# 全頂点について、属するサイクルを計算する
				currentCycleItemCnt += 1
				currentCycleTotal += C[v]

				v = P[v]
				if v == n:
					# サイクル発見
					cycleInfs.append( (currentCycleItemCnt, currentCycleTotal) )
					cycleID += 1
					break

				# 一応、一度サイクルを計算した頂点については、
				# その頂点の属するサイクルの情報をメモっておく。。。
				cycleIDs[v] = cycleID

		procCnt = 0
		currentCycleSumTmp = 0

		while True:

			# 頂点vにコマが置かれた時の最高スコアを計算し、
			# これまでの最高スコアを上回ったら、これまでの最高スコアを更新する
			procCnt += 1
			currentCycleSumTmp += C[v]
			if K < procCnt:
				break

			cycleLoopCnt = 0
			if procCnt < K and 0 < currentCycleTotal:
				cycleLoopCnt = ( K - procCnt ) // currentCycleItemCnt

			# print("v=", v, "currentCycleSumTmp=", currentCycleSumTmp, procCnt)
			tmp = currentCycleSumTmp + cycleLoopCnt * currentCycleTotal
			ans = max( ans, tmp )

			v = P[v]
			if v == n:
				# サイクル終了
				break

	print(ans)


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

bool is_prime(int n){
    for(int i=2;i<=static_cast<int>(sqrt(n));i++){
        if (n%i == 0) return false;
    }
    return true;
}

int main(){

    vector<int> cnt_num(100000+1);
    for(int i=3;i<=100000;i++){
        cnt_num[i] = cnt_num[i-1];
        if (i%2 && is_prime(i) && is_prime((i+1)/2)) cnt_num[i] += 1;
    }

    int q;
    cin >> q;
    for (int i=0;i<q;i++){
        int l, r;
        cin >> l >> r;
        cout << cnt_num[r] - cnt_num[l-1] << endl;

    }
}

Measured memory_bytes: 1024
#include <stdio.h>
 
int main(void){
    int num[100]={0};
    int num2[100]={0};
    int i=0,j;
    int a=0;
    while(scanf("%d",&num[i])!=EOF){
        i++;
    }
    for(i=0;i<100;i++){
        for(j=0;j<100;j++){
            if(num[j]==i){
                num2[i]++;
            }
        }
        if(num2[i]>a){
            a=num2[i];
        }
    }
    for(i=0;i<100;i++){
        if(num2[i]==a){
            printf("%d\n",i);
        }
    }
    return 0;
}

Measured memory_bytes: 596
#include <iostream>
using namespace std;
int main(){
    int x, a, b;
    cin >> x >> a >> b;
    if (b <= a){
        cout << "delicious" << endl;
    }
    else if (a < b && b <= a+x){
        cout << "safe" << endl;
    }
    else{
        cout << "dangerous" << endl;
    }

    return 0;
}

Measured memory_bytes: 256
use std::cmp;

// 入力関数
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

// 以下main
fn main() {
    let init: Vec<u32> = read_vec();
    let a = init[0];
    let b = init[1];
    let k = init[2] as usize;

    let mut divisor: Vec<u32> = Vec::new();

    for i in 0..cmp::min(a, b) {
        let devider = i + 1 as u32;
        if a % devider == 0 && b % devider == 0 {
            divisor.push(devider);
        }
    }

    let n = divisor.len();

    if n != 0 {
        println!("{}", divisor[n - k]);
    } else {
        println!("{}", 1);
    }
}


Measured memory_bytes: 4352
num = (10 ** 9) + 7

n, m = map(int, input().split())

if m == 1:
    print(1)
    exit()

prime_upper = int(m ** (1/2) + 50)
prime_dict = {}

check = [False] * prime_upper
prime = [2]

while m % 2 == 0:
    m //= 2
    if not 2 in prime_dict.keys():
        prime_dict[2] = 0
    prime_dict[2] += 1

for j in range(2, prime_upper, 2):
    check[j] = True

for i in range(3, prime_upper, 2):
    if not check[i]:
        prime.append(i)
        while m % i == 0:
            m //= i
            if not i in prime_dict.keys():
                prime_dict[i] = 0
            prime_dict[i] += 1

        for j in range(i, prime_upper, i):
            check[j] = True

if len(prime_dict.values()) != 0:
    value_max = max(prime_dict.values())
    com2 = [[0] * (value_max + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        for j in range(1, value_max + 1):
            if i == 1:
                com2[i][j] = 1
            elif j == 1:
                com2[i][j] = i
            else:
                com2[i][j] = (com2[i][j - 1] + com2[i - 1][j]) % num
    if m != 1:
        ans = n
    else:
        ans = 1
    for key, value in prime_dict.items():
        ans = (ans * com2[n][value]) % num
    print(ans)
else:
    print(n)



Measured memory_bytes: 127412
#include <bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
ll mod=1e9+7;
bool prime(ll n)
{
    if(n==1)
        return false;
    if(n==2)
        return true;
    for(ll i=2; i*i<=n; i++)
    {
        if(n%i==0)
            return false;
    }
    return true;
}
ll gcd(ll x,ll y)
{
    if(y==0)
        return x;
    return gcd(y,x%y);
}
ll fp(ll b,ll p)
{
    if(p==0)
        return 1;
    ll  z=fp(b,p/2);
    if(p%2==0)
        return (z*z)%mod;
    else
        return (((z*z)%mod)*(b%mod))%mod;
}
long long  Factorial(long long n)
{
    if(n > 1)
        return n * Factorial(n - 1);
    else
        return 1;
}
const int m=1e6+1;
ll fact[m],inv[m];
void fn()
{
    fact[0]=1,inv[0]=1;
    for(int i=1; i<=1e6; i++)
    {
        fact[i]=(i*fact[i-1])%mod;
        inv[i]=fp(fact[i],mod-2);
    }
}

long long  nCr(ll N, ll R)
{
    return (((fact[N]*inv[N-R])%mod)*inv[R])%mod;
}
vector<int>v;
void primeFactors(int n)
{
    while (n%2 == 0)
    {
        v.push_back(2);
        n = n/2;

    }

    for (int i = 3; i <= sqrt(n); i = i+2)
    {
        while (n%i == 0)
        {
            v.push_back(i);
            n = n/i;
        }
    }
    if (n > 2)
        v.push_back(n);
}
long long  NCR(long long N, long long R)
{
return (Factorial(N)) / ((Factorial(N-R)) * Factorial(R));
}
int main()
{
 int n;
 cin>>n;
 int ans[n],h[n];
 for(int i=0;i<n;i++){
    cin>>h[i];
 }
 ans[0]=0;
 ans[1]=ans[0]+abs(h[0]-h[1]);
 for(int i=2;i<n;i++){
        ans[i]=min(ans[i-1]+abs(h[i]-h[i-1]),ans[i-2]+abs(h[i]-h[i-2]));
 }
cout<<ans[n-1]<<endl;
    return 0;
}


Measured memory_bytes: 1024
#include<bits/stdc++.h>
using namespace std;
#define inf 1e9
#define ll long long
#define ull unsigned long long
#define M 1000000007
#define P pair<int,int>
#define PLL pair<ll,ll>
#define FOR(i,m,n) for(int i=m;i<n;i++)
#define RFOR(i,m,n) for(int i=m;i>=n;i--)
#define rep(i,n) FOR(i,0,n)
#define rrep(i,n) RFOR(i,n,0)
#define all(a) a.begin(),a.end()
const int vx[4] = {0,1,0,-1};
const int vy[4] = {1,0,-1,0};
#define PI 3.14159265

int d[1000][1000];
int t[3][10000];

int n,c;

int main(){
  cin>>n>>c;
  rep(i,c){
    rep(j,c){
      cin>>d[i+1][j+1];
    }
  }

  rep(i,n){
    rep(j,n){
      int x;
      cin>>x;
      t[(i+j+2)%3][x]++;
    }
  }

  int ans = inf;
  FOR(i,1,c+1){
    FOR(j,1,c+1){
      FOR(k,1,c+1){
        if(i==j||j==k||i==k) continue;
        int res=0;
        FOR(l,1,c+1){ 
          res+=d[l][i]*t[0][l];
          res+=d[l][j]*t[1][l];
          res+=d[l][k]*t[2][l];
        }
        ans = min(ans,res);
      }
    }
  }
  
  cout<<ans<<endl;

  return 0;
}

Measured memory_bytes: 384
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

import static java.lang.Integer.parseInt;

/**
 * JAG Practice Contest
 */
public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line;
		String[] words;

		while ((line = br.readLine()) != null && !line.isEmpty()) {
			int N, M;
			N = parseInt(line.substring(0, line.indexOf(' ')));
			M = parseInt(line.substring(line.indexOf(' ') + 1));
			if ((N | M) == 0) break;

			int[] vs = new int[M + 1];

			for (int i = 0; i < N; i++) {
				line = br.readLine();
				int d, v;
				d = parseInt(line.substring(0, line.indexOf(' ')));
				v = parseInt(line.substring(line.indexOf(' ') + 1));
				vs[d] = Math.max(vs[d], v);
			}

			System.out.println(Arrays.stream(vs).sum());
		}
	}
}

Measured memory_bytes: 30948
### constant

MAX_P = 100000

### subroutines

def gen_primes(max_p)
  primes = Array.new(max_p + 1){true}
  primes[0] = primes[1] = false

  pnums = []

  s_max_p = Math.sqrt(max_p + 0.5).to_i

  for p in (2..s_max_p)
    if primes[p]
      pnums << p
      for q in (p * p).step(max_p, p)
        primes[q] = false
      end
    end
  end

  for p in ((s_max_p + 1)..MAX_P)
    if primes[p]
      pnums << p
    end
  end

  return pnums
end

def pal_rec(k)
  if k >= $n
    pln = $c * (10 ** $n)
    for i in (0...$n)
      pln += $pals[i] * (10 ** (2 * $n - i) + 10 ** i)
    end

    for pi in $pnums
      break if pi * pi > pln
      return 0 if pln % pi == 0
    end

    return pln
  end

  9.downto(0) do |pl|
    $pals[k] = pl
    mpl = pal_rec(k + 1)
    return mpl if mpl > 0
  end

  0
end

### main

$pnums = gen_primes(MAX_P)
#p $pnums.length

$n, $c = gets.strip.split(' ').map{|s| s.to_i}

if $c < 0
  puts ($n == 1 ? 11 : 10 ** (2 * $n) - 1)
  exit 0
end

$pals = []

puts pal_rec(0)

Measured memory_bytes: 7024
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        if( n != 1 ) {
            // since needs n integers
            int div = m/n;
            int max = 1;
            for( int i = 2; i <= div; i++ ) {
                // ??
                if(m%i == 0) max = Math.max(max, i);
            }
            System.out.println(max);
        } else {
            System.out.println(m);
        }
    }
}

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

int main() {
	int n;
	string s;
	cin >> n >> s;
	int ans = 0;
	rep(i, 1000) {
		int t = i;
		int cnt = 0;
		for (int j = n - 1; j >= 0; j--) {
			if (s[j] - '0' == t % 10) {
				cnt++;
				t /= 10;
				if (cnt == 3) {
					ans++;
					break;
				}
			}
		}
	}
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 3672
#include "bits/stdc++.h"
#define rep(i,n) for(int i = 0; i < (n); ++i)
using namespace std;
typedef long long int ll;
typedef pair<ll, ll> P;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	int n, k;
	cin >> n >> k;
	ll r, s, p;
	cin >> r >> s >> p;
	string t;
	cin >> t;
	ll ans = 0;
	rep(i,n){
		if(t[i] == 'r'){
			if(i-k < 0 || t[i-k] != 'r') ans += p;
			else t[i] = '!';
		}
		else if(t[i] == 's'){
			if(i-k < 0 || t[i-k] != 's') ans += r;
			else t[i] = '!';
		}
		else{
			if(i-k < 0 || t[i-k] != 'p') ans += s;
			else t[i] = '!';
		}
	}
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 512
#include<bits/stdc++.h>
using namespace std;
string s;
bool ok1,ok2;
int main()
{
	cin>>s;
	if(s[0]=='A')
	{
		ok1=true;
	}
	else
	{
		ok2=true;
	}
	if(s[1]=='A')
	{
		ok1=true;
	}
	else
	{
		ok2=true;
	}
	if(s[2]=='A')
	{
		ok1=true;
	}
	else
	{
		ok2=true;
	}
	if(ok1 && ok2)
	{
		cout<<"Yes"<<endl;
	}
	else
	{
		cout<<"No"<<endl;
	}
	return 0;
}

Measured memory_bytes: 256
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <iomanip>
#include <numeric>
 
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<ll,ll>;
string S,T;
ll N,K;
ll A[100005];
ll M = 1000000007;
ll ans;
int main() {
    cin >> ans;
    if(ans>=30){
        cout << "Yes" << endl;
    }else{
        cout << "No" << endl;
    }
    
}


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

typedef long long ll;
typedef pair<ll, ll> P;

#define pb push_back
#define rep(i, n) for(int i = 0; i < (n); i++)
#define dep(i, a, n) for(int i = a; i >= (n); i--)
#define FOR(i, a, n) for(int i = a; i < (n); i++)
#define mod (ll)(1e9+7)
#define int ll
#define INF 100000000

__attribute__((constructor))
void initial() {
  cin.tie(0);
  ios::sync_with_stdio(false);
}

signed main() {
	int old;
  cin >> old;
  if (old == 7 || old == 5 || old == 3) {
    cout << "YES" << endl;
  } else {
    cout << "NO" << endl;
  }
	return 0;
}


Measured memory_bytes: 256
#include <cstdio>
int main(){
	int n, a, b, h, w, c = 0;
	scanf("%d %d %d",&n,&h,&w);
	for (int i = 0; i < n; i++){
		scanf("%d %d",&a,&b);
		if (a >= h && b >= w){
			c++;
		}
	}
	printf("%d\n",c++);
}

Measured memory_bytes: 256
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

x = LI()

print(x.index(0) + 1)

Measured memory_bytes: 10816
#include <iostream>
#include <numeric>

#define N 5
#define min_score 40

using namespace std;

int main()
{
  int scores[N];

  for(int i = 0; i < N; i += 1){
    cin >> scores[i];
    scores[i] = max(scores[i], min_score);
  }

  cout << (accumulate(scores, scores+N, 0)/N) << endl;

  return 0;
}

Measured memory_bytes: 1160
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main() {
	int N;
	cin >> N;
	string S[110];

	for (int i = 1; i <= N; i++) {
		cin >> S[i];
		if (S[i] == "Y") {
			cout << "Four";
			return 0;
		}

	}
	cout << "Three";
}

Measured memory_bytes: 256
N=int(input())
AB = [list(map(int, input().split())) for _ in range(N-1)] #N-1
C = list(map(int, input().split())) #N
C.sort()

M = sum(C[:-1])

adjacent_dict={}
for a,b in AB:
  adjacent_dict.setdefault(a, set()).add(b)
  adjacent_dict.setdefault(b, set()).add(a)
  

leafs = []
adjacents = [0] * (N+1) # a[i]: 頂点i
for k, v in adjacent_dict.items():
  adjacents[k] = len(v)
  if len(v)==1:
    leafs.append(k)

nodes = leafs.copy() #小さい値を入れたい順のノード
visited = [0] * (N+1) # visited[i]: 頂点i
for n in nodes:
  visited[n] = 1
  
#while leafs:
#  next_leafs = set()
#  for l in leafs:
#    for u in adjacent_dict[l]:
#      acjacents[u] -= 1
#      next_leafs.add(u)
  
  
while leafs:
  new_stack = []
  for v in leafs:
    for u in adjacent_dict[v]:
      adjacents[u] -= 1
      if visited[u]==0:
        visited[u]=1
        new_stack.append(u)
  leafs = [v for v in new_stack if adjacents[v]==1]
  nodes.extend(leafs)
  if not leafs:
    nodes.extend(new_stack) #最後に隣接0のノードが残ったとき
    break
  for u in [v for v in new_stack if adjacents[v]!=1]:
    visited[u] = 0
    
  
ans = [0]*(N)
for i in range(N):
  ans[nodes[i]-1] = C[i]
  
print(M)
print(*ans)


Measured memory_bytes: 9476
import fractions
import copy

a,b=map(int,input().split())

def calc_divisore(n):
    divisors=[]
    for i in range(1,int(n**0.5)+1):
        if n%i==0:
            divisors.append(i)
            if i!=n//i:
                divisors.append(n//i)
    return divisors

la=calc_divisore(a)
lb=calc_divisore(b)
ll=sorted(list(set(la)&set(lb)))
#print(la,lb,ll)
#print(ll)

ansl=[1]

ll_c=copy.copy(ll)

for i in ll_c:
#    ansl.append(i)
    len_s=len(ll)
    ll=list(filter(lambda x: fractions.gcd(i,x)==1, ll))
    if len(ll)!=len_s:
        ansl.append(i)

#   print(i,lll)
#    print(ansl)
#    print('\n')
print(len(ansl))

Measured memory_bytes: 7240
#include<iostream>
#include<stack>
#include<map>
#include<set>
#include<queue>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
#define me(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
const int N=500005;
int main()
{
	int t,i,j,m,n,x,y,z,a[4],b,sum=0,c;
	cin>>a[1]>>a[2]>>a[3];
	sort(a+1,a+1+3);
	x=a[3]-a[1];
	y=a[3]-a[2];
	
	sum+=y;
	x-=y;
	if(x%2)
	{x+=1;
		sum+=x/2;
		sum+=1;
	}
	else 
	{
		sum+=x/2;
	}
	cout<<sum;
	return 0; 
}

Measured memory_bytes: 512
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <string>
#include <queue>
#include <numeric>
#include <ctype.h>
#include <limits>
#include <iomanip>

#define rep(i,n) for (int i = 0; i < n; i++)
#define all(x) (x).begin(),(x).end()
using namespace std;

typedef long long ll;

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

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

int main(){
  int a,b;
  cin >> a >> b;
  int count_1=0, count_2=0, count_3=0;
  if(a==1 || b==1) count_1++;
  if(a==2 || b==2) count_2++;
  if(a==3 || b==3) count_3++;
  
  if(count_1==0){
      cout << "1" << endl;
  } else if(count_2==0){
      cout << "2" << endl;
  } else {
      cout << "3" << endl;
  }
  
  return 0;
}


Measured memory_bytes: 256
import random
from functools import lru_cache
import math

def solve():
    n = int(input())
    if n < 1000:
        print(1000 - n)
    else:
        paid = math.ceil(n / 1000) * 1000
        print(paid-n)

t = 1
for _ in range(t):
    solve()



Measured memory_bytes: 76860
#include <bits/stdc++.h>
using namespace std;
typedef bool boolean;

const int N = 2e5 + 5;

int n;
int A[N];
int B[N];
boolean inq[N];

boolean check(int p) {
	return B[p] >= B[(p + n - 1) % n] + B[(p + 1) % n];
}

int main() {
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d", A + i);
	}
	for (int i = 0; i < n; i++) {
		scanf("%d", B + i);
	}
	queue<int> Q;
	for (int i = 0; i < n; i++) {
		if (check(i)) {
			inq[i] = true;
			Q.push(i);
		}
	}
	long long ans = 0;
	while (!Q.empty()) {
		int p = Q.front();
		Q.pop();
		inq[p] = false;
		int pre = (p + n - 1) % n, suf = (p + 1) % n;
		int sum = B[pre] + B[suf];
		int t = max(0, (B[p] - A[p]) / sum);
		if (!t && B[p] != A[p]) {
			puts("-1");
			return 0;
		}
		ans += t;
		B[p] -= sum * t;
		if (!inq[pre] && check(pre)) {
			inq[pre] = true;
			Q.push(pre);
		}
		if (!inq[suf] && check(suf)) {
			inq[suf] = true;
			Q.push(suf);
		}
	}
	for (int i = 0; i < n; i++) {
		if (A[i] ^ B[i]) {
			puts("-1");
			return 0;
		}
	}
	printf("%lld\n", ans);
	return 0;
}


Measured memory_bytes: 2432
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,n) for(int i=0;i<n;i++)
#define inf 100000000000000000
#define mod 1000000007
typedef pair<int, int> P;

bool prime(int n) {
	for (int i = 2; i <= sqrt(n); i++) {
		if (n % i == 0)return false;
	}
	return n != 1;
}
int gcd(int x, int y) {
	if (y == 0)return x;
	return gcd(y, x % y);
}
int lcm(int x, int y) {
	return x / gcd(x, y) * y;
}
int mod_pow(int n, int p, int m) {
	if (p == 0) return 1;
	if (p % 2 == 0) {
		int t = mod_pow(n, p / 2, m);
		return (t * t) % m;
	}
	return n * mod_pow(n, p - 1, m) % m;
}

signed main() {
	int n, m, q;
	cin >> n >> m >> q;
	int d[505][505], ans[505][505];
	for (int i = 0; i <= n; i++) {
		for (int j = 0; j <= n; j++) {
			d[i][j] = 0, ans[i][j] = 0;
		}
	}
	rep(i, m) {
		int l, r;
		cin >> l >> r;
		d[l][r]++;
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			ans[i][j] = d[i][j] + ans[i - 1][j] + ans[i][j - 1] - ans[i - 1][j - 1];
		}
	}
	rep(i, q) {
		int p, q;
		cin >> p >> q;
		cout << ans[q][q] - ans[p - 1][q] - ans[q][p - 1] + ans[p - 1][p - 1] << endl;
	}

	return 0;
}


Measured memory_bytes: 4864
//https://atcoder.jp/contests/abc156/tasks/abc156_b
#include <bits/stdc++.h>
#if LOCAL
#include "dump.hpp"
#else
#define dump(...)
#endif
using namespace std;
using ll=long long;
#define FOR(i,a,b) for(ll i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
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;}
int main() {
    ll N, K; cin>>N>>K;
    ll ans=0;
    while(N>0){
        N/=K;
        ++ans;
    }
    cout<<ans<<endl;
    return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define f first
#define s second
#define pb push_back
#define reset(a,b) memset(a,b,sizeof a);
#define ALL(x) x.begin(),x.end()
#define debug(x) cout<<#x<<" = "<<(x)<<endl
#define sz(x) (int)(x.size())
#define lt(x) (int)(x.length())
#define MOD 1000000007 
#define mx 100003

int main(){
	set<int> digit;
	int n, k;
	for(int i = 0; i < 10; i++)
		digit.insert(i);
	cin >> n >> k;
	for(int i = 0; i < k; i++){
		int x;
		cin >> x;
		digit.erase(x);
	}
	for(int i : digit){
		if(n <= i){
			cout << i << endl;
			return 0;
		}
	}
	for(int i : digit){
		if(i == 0)
			continue;
		for(int j : digit){
			int x = i * 10 + j;
			if(n <= x){
				cout << x << endl;
				return 0;
			}
		}
	}
	for(int i : digit){
		if(i == 0)
			continue;
		for(int j : digit){
			for(int k : digit){
				int x = i * 100 + j * 10 + k;
				if(n <= x){
					cout << x << endl;
					return 0;
				}
			}
		}
	}
	for(int i : digit){
		if(i == 0)
			continue;
		for(int j : digit){
			for(int k : digit){
				for(int l : digit){
					int x = i * 1000 + j * 100 + k * 10 + l;
					if(n <= x){
						cout << x << endl;
						return 0;
					}
				}
			}
		}
	}
	for(int i : digit){
		if(i == 0)
			continue;
		for(int j : digit){
			for(int k : digit){
				for(int l : digit){
					for(int m : digit){
						int x = i * 10000 + j * 1000 + k * 100 + l * 10 + m;
						if(n <= x){
							cout << x << endl;
							return 0;
						}
					}
				}
			}
		}
	}
}

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

#define MAX 100000
#define LEN 15

struct node{
  int right;
  int left;
  int dep;
  int par;
  char type[LEN];
};

struct node T[MAX];

void deps(int a, int b){
  T[a].dep = b;
  if(T[a].right != -1){
    deps(T[a].right,b);
  }
  if(T[a].left != -1){
    deps(T[a].left,b+1);
  }
}


void printC(int a){
  int c;
  c=T[a].left;
  printf("[");
  while(c!= -1){
    printf("%d", c);
    if(T[c].right != -1){
      printf(", ");
    }
      c= T[c].right;
  }
  printf("]\n");
  
}


int main(){

  int i,j,k,c[MAX],id,root,n;
  
  scanf("%d",&n);

  for(i=0;i<n;i++){
    T[i].par = T[i].left = T[i].right = -1;
  }
  
  for(i=0;i<n;i++){
    scanf("%d%d",&id,&k);
    if(k==0){
      c[0] = -1;
    }
    
    for(j=0;j<k;j++){
      scanf("%d", &c[j]);
    }
    
    for(j=0;j<k;j++){
      T[c[j]].par = id;
      if(j != k-1){
	T[c[j]].right = c[j+1];
      }
    }  
    T[id].left = c[0];
  }
  
  for(i=0;i<n;i++){
    if(T[i].par == -1) root = i;
  }

  deps(root, 0);
      
  for(i=0;i<n;i++){
    if(T[i].par == -1){
      strcpy(T[i].type, "root");
    }
    else if(T[i].left == -1){
      strcpy(T[i].type, "leaf");
    }
    else{
      strcpy(T[i].type, "internal node");
    }
    printf("node %d: parent = %d, depth = %d, %s, ", i, T[i].par, T[i].dep, T[i].type);
    printC(i);
  }
  return 0;
}



Measured memory_bytes: 9208
#include<stdio.h>

int main()
{
    long n,a,b;
    scanf("%ld %ld %ld",&n,&a,&b);
    long min=a * ( n - 1 ) + b ;
    long max = a + ( n - 1 ) * b;
    if(n == 1 ){
        if( a == b)
            printf("1");
        else
            printf("0");
    }
    else{
        if(a > b )
            printf("0");
        else
            printf("%lld",(long long)(max - min + 1));
        
    }
    return 0;
}


Measured memory_bytes: 128
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<queue>
#include<bitset>
#include<map>
using namespace std;
template<typename __T>
inline void read(__T &x)
{
    x=0;
    int f=1;char c=getchar();
    while(!isdigit(c)){if(c=='-')	f=-1;c=getchar();}
    while(isdigit(c))	{x=x*10+c-'0';c=getchar();}
    x*=f;
}
bool vis[305][305];
int dis[305][305];
int n;
int main()
{
	read(n);
	memset(vis,1,sizeof(vis));
	for(int i=1;i<=n;i++)
		vis[i][i]=0;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
			read(dis[i][j]);
	for(int k=1;k<=n;k++)
		for(int i=1;i<=n;i++)
			for(int j=1;j<=n;j++)
			{
				if(i==k || j==k)	continue;
				if(dis[i][j]>dis[i][k]+dis[k][j])
				{
					printf("-1\n");
					return 0;
				}
				if(dis[i][j]==dis[i][k]+dis[k][j])
					vis[i][j]=0;
			}
	long long ans=0;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
			if(vis[i][j])	ans+=dis[i][j];
	cout<<ans/2<<endl;
	return 0;
}


Measured memory_bytes: 640
#include<iostream>
#include<vector>
#include<algorithm>
#include<tuple>
#include<string>
#define rep(i,n) for (int i=0; i<n; i++)
using namespace std;
int main() {
  int N,X;
  cin >> N >> X;
  vector<int> L(N);
  rep(i,N) cin >> L[i];
  vector<int> D(N+1);
  D[0] = 0;
  int cnt = 0;
  for (int i=1; i<N+1; i++) {
    D[i] = D[i-1] + L[i-1];
    if (D[i] <= X) cnt++;
  }
  cout << cnt+1 << endl;
}
  

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

int getCollatz(int x_num) {
    return (x_num % 2)? 3 * x_num + 1 : x_num / 2;
}

int main(void) {
    int s, cnt = 0;
    set<int> se_num;

    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> s;
    se_num.insert(s);
    while (true) {
        ++cnt;
        s = getCollatz(s);
        if (se_num.count(s)) {
            break;
        }
        se_num.insert(s);
    }

    cout << cnt + 1 << "\n";
    return 0;
}

Measured memory_bytes: 256
// {{{
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <complex>
#include <vector>
#include <list>
#include <set>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <algorithm>
#include <numeric>
using namespace std;

#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define FOR(i, a, b) for(ll i = static_cast<ll>(a); i < static_cast<ll>(b); i++)
#define FORR(i, a, b) for(ll i = static_cast<ll>(a); i >= static_cast<ll>(b); i--)
#define REP(i, n) for(ll i = 0ll; i < static_cast<ll>(n); i++)
#define REPR(i, n) for(ll i = static_cast<ll>(n); i >= 0ll; i--)
#define ALL(x) (x).begin(), (x).end()

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
typedef pair<ll, ll> LP;
typedef pair<int, P> IP;
typedef pair<ll, LP> LLP;

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

constexpr int INF = 100000000;
constexpr ll LINF = 10000000000000000ll;
constexpr int MOD = static_cast<int>(1e9 + 7);
constexpr double EPS = 1e-9;
// }}}

int a, b, k;
priority_queue<int> q;

void init()
{
}

void solve()
{
    FOR(i, 1, max(a, b)+1){
        if(a % i == 0 && b % i == 0) q.push(i);
    }
    REP(i, k-1) q.pop();
    cout << q.top() << endl;
}

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

// vim:set foldmethod=marker:


Measured memory_bytes: 256
S = input()
N = len(S) + 1

a_left = [0] * N
a_tmp = 0
for i in range(N - 1):
    if S[i] == '<':
        a_tmp += 1
    else:
        a_tmp = 0
    #
    a_left[i + 1] = a_tmp

a_right = [0] * N
a_tmp = 0
for i in range(N - 1):
    if S[-1 - i] == '>':
        a_tmp += 1
    else:
        a_tmp = 0
    #
    a_right[-2 - i] = a_tmp
        
a_ans = [max(li, ri) for li, ri in zip(a_left, a_right)]

print(sum(a_ans))

Measured memory_bytes: 31908
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

"""
・大きい数から挿入していく
・連結成分の両端を管理する
"""

N,*A = map(int,read().split())

A = [0] + A + [0]
ind = [0] * (N+1)
for i,x in enumerate(A):
    ind[x] = i

left = list(range(1,len(A)+1))
right = list(range(-1,len(A)-1))
answer = 0
for i in ind[:0:-1]:
    # i番目に数を挿入
    l = left[i-1]; r = right[i+1]
    left[r] = l; right[l] = r
    x = i - l + 1; y = r - i + 1
    answer += A[i] * (x * y)

print(answer)

Measured memory_bytes: 36380