akhauriyash/Code-Regression huggingface dataset:
'''
研究室PCでの解答
'''
import math
#import numpy as np
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 #998244353
dir = [(-1,0),(1,0),(0,-1),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"


def main():
    l = int(ipt())
    if l <= 60:
        print(2,l)
        for i in range(l):
            print(1,2,i)
        exit()
    else:
        l2 = format(l,'b')
        n = len(l2)
        ans = [(1,2,0),(1,2,1),(1,2,2),(1,2,3)]
        for i in range(2,n-1):
            ans.append((i,i+1,0))
            ans.append((i,i+1,2**i))
        nii = 2**(n-1)
        for i in range(1,n-2):
            if (l>>(n-1-i))&1:
                ans.append((n-i-1,n-1,nii))
                nii += 2**(n-i-1)
        if (l>>1)&1:
            ans.append((1,n-1,nii))
            ans.append((1,n-1,nii+1))
            nii += 2
        if l&1:
            ans.append((1,n-1,nii))
        print(n-1,len(ans))
        for a,b,c in ans:
            print(a,b,c)
    return None

if __name__ == '__main__':
    main()


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

long long a, b;

long long lowbit(long long c)
{ return c&(-c); }

long long highbit(long long a)
{
	while (a != lowbit(a)) a -= lowbit(a);
	return a;
}

long long solve(long long a, long long b)
{
	if (a > b) return 0;
	if (a == b) return 1;
	if (highbit(a) == highbit(b)) return solve(a-highbit(a), b-highbit(b));
	long long k = highbit(b);
	long long ans = k-a;
	long long R = b-k==0?0:(highbit(b-k)<<1)-1;
	if (R+1 >= a) return ans+k;
	else return ans+R+1+k-a;
}

int main()
{
	cin >> a >> b;
	cout << solve(a, b) << endl;
	return 0;
}


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

int main(){
ll N;
cin>>N;
if(N%2==0){
  cout<<N/2-1<<endl;
}else{
  cout<<N/2<<endl;
}
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
using vi=vector<int>;
using vvi=vector<vi>;
using vd=vector<double>;
using vvd=vector<vd>;
using vl=vector<ll>;
using vvl=vector<vl>;
using pii=pair<int,int>;
using vs=vector<string>;
#define rep(i,n) range(i,0,n)
#define range(i,a,n) for(int i=a;i<n;i++)
#define all(a) a.begin(),a.end()
#define LINF    	((ll)1ll<60)
#define INF     	((int)1<<30)
#define EPS     	(1e-9)
#define MOD     	(1000000007)
#define fcout(a)	cout<<setprecision(a)<<fixed
#define fs 			first
#define sc			second
#define PI			3.141592653589793

template<class S,class T>ostream& operator<<(ostream&os,pair<S,T>p){os<<"["<<p.first<<", "<<p.second<<"]";return os;};
template<class S>auto&operator<<(ostream&os,vector<S>t){bool a=1; for(auto s:t){os<<(a?"":" ")<<s; a=0;} return os;}

int main(){
	cin.tie(0);
   	ios::sync_with_stdio(false);
	
	int d,g;
	cin>>d>>g;
	vi p(d),c(d);
	rep(i,d){
	    cin>>p[i]>>c[i];
	}
	
	int ans=INF;
	rep(s,1<<d){
	    int cmp=0,t=s,a=0;
	    while(t){
	        int index=__builtin_ctz(t);
	        cmp+=c[index]+(index+1)*100*p[index];
	        a+=p[index];
	        t&=t-1;
	    }
	    if(cmp<g){
    	    for(int i=d-1;i>=0;i--){
    	        if(!(s&(1<<i))){
    	            int q=p[i];
    	            while(cmp<g&&q>0){
    	                q--;
    	                a++;
    	                cmp+=(i+1)*100;
    	            }
    	            break;
    	        }
    	    }
	    }
	    if(cmp<g)a=INF;
	    ans=min(ans,a);
	}
	cout<<ans<<endl;
	return 0;
}


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

using namespace std;

#define int long long
#define ll long long
typedef pair<int, int> P;
#define mod 1000000007
#define INF (1LL<<60)

#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define YES cout << "YES" << endl;
#define Yes cout << "Yes" << endl;
#define NO cout << "NO" << endl;
#define No cout << "No" << endl;



int c[26];

signed main(){

	string s;
	cin >> s;
	int N = s.length();
	rep(i, N) c[s[i]-'a']++;
	
	int ans = N*(N - 1) / 2 + 1;

	rep(i, 26){
		ans -= c[i] * (c[i] - 1) / 2;
	}
	cout << ans << endl;

	return 0;
}

Measured memory_bytes: 640
#include<bits/stdc++.h>
using namespace std;
using lld = long long int;
using ld = long int;
int main()
{
    int n;
    cin >> n;
    if(n>=400 && n<600)
        cout << 8;
    else if(n>=600 && n<800)
        cout << 7;
    else if(n>=800 && n<1000)
        cout << 6;
    else if(n>=1000 && n<1200)
        cout << 5;
    else if(n>=1200 && n<1400)
        cout << 4;
    else if(n>=1400 && n<1600)
        cout << 3;
    else if(n>=1600 && n<1800)
        cout << 2;
    else if(n>=1800 && n<2000)
        cout << 1;
}


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

int main(){
  int N;
  int a[N];
  cin >> N;
  for(int i = 0; i<N; i++){
    cin >> a[i];
  }
  sort(a,a+N);
  reverse(a,a+N);
  int A = 0, B = 0;
  for(int i = 0; i<N; i++){
    if(i % 2 == 0){
      A += a[i];
    }else{
      B += a[i];
    }
  }
  cout << abs(A-B) << endl;
}

Measured memory_bytes: 3620
#define _CRT_SECURE_NO_DEPRECATE
#pragma GCC optimize("O3")
#pragma GCC target("sse4")
#include<bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//using namespace __gnu_pbds; 
using namespace std;
#define int long long int
#define SYNC std::ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
#define FRE freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
typedef long double ld;
typedef pair<int,int> ii;
typedef pair<int,ii> iii;
typedef vector<int> vi;
typedef vector<ii>   vii;
//typedef tree<int, null_type, less<int>, rb_tree_tag, 
//             tree_order_statistics_node_update> 
//    data_set;
#define rep(i,l,r)   for(int i=(l);i<(r);i++)
#define deb(x)     cout << (#x) << " is " << (x) << endl
#define dbg(x)     cout << x << ' '
#define here cout << " Hey baitch!!\n";
#define  pb push_back
#define  F  first
#define  S  second
#define all(v) (v).begin(),(v).end()
#define sz(a) (int)((a).size())
#define sq(x) ((x)*(x))
const int MOD = 1e9+7;
const int MOD1 = 998244353;
const int N = 2e5+5;
const int INF = 1000111000111000111LL;
const ld PI = 3.1415926535898;

int32_t main()
{
	SYNC
	int a,b,c,k;
	cin >> a >> b >> c >> k;
	int sum = 0;
	if(k > 0) {
		int buf = min(k,a);
		sum += buf;
		a -= buf;
		k -= buf;
	}
	if(k > 0) {
		int buf = min(k,b);
		b -= buf;
		k -= buf;
	}
	if(k > 0) {
		int buf = min(k,c);
		sum -= buf;
		k -= buf;
	}
	cout << sum;
    return 0;
}

Measured memory_bytes: 3664
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef double db; 
typedef string str; 
typedef pair<ll,ll> pl; 
typedef vector<ll> vl; 
typedef vector<vl> vvl; 
#define mp make_pair
#define se second
#define pb push_back
#define pf push_front
#define nn <<"\n"
#define F0R(i,a) for(ll i=0;i<a;i++)
#define FOR(i,a,b) for(ll i=a;i<b;i++)
int INF=0x3f3f3f3f;
ll MOD=1000000007;

ll binpow(ll a,ll b, ll c=1e18){
	ll res=1;
	while(b>0){
		if(b & 1){
			res*=a;
			res%=c;
		}
		a*=a;
		a%=c;
		b>>=1;
	}
	return res;
}
int main(){
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	//ifstream cin("name.in");
	//ofstream cout("name.out");
	char a;
	cin>>a;
	
	if(toupper (a)==a){
		cout<<"A" nn;
	}else{
		cout<<'a' nn;
	}
}


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

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

typedef long long ll;

using namespace std;

const int INF = 1e9,MOD = 1e9 + 7,ohara = 1e6;
const ll LINF = 1e18;

//-------------------------↓↓↓↓↓↓------------------------

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

      ll n, k, a, sum[ohara], sei[ohara], cnt, ans = 0;
      
      cin >> n >> k;
      
      rep(i,n){
        cin >> a;
        sum[i] = a;
        if(a > 0)sei[i] = a;
      }
      
      rep(i,n - 1){
        sum[i + 1] += sum[i];
        sei[i + 1] += sei[i];
      }

      rep(i,n - k + 1){
        if(i == 0)cnt = sum[i + k - 1];
        else cnt = sum[i + k - 1] - sum[i - 1];
        if(i != 0)cnt += sei[i - 1];
        cnt += sei[n - 1] - sei[i + k - 1];
        ans = max(ans,cnt);
      }

      rep(i,n - k + 1){
        cnt = 0;
        if(i != 0)cnt += sei[i - 1];
        cnt += sei[n - 1] - sei[i + k - 1];
        ans = max(ans,cnt);
      }
      cout << ans << "\n";

       
return 0;
}


Measured memory_bytes: 6656
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
struct state{int x,y;};

bool f[50][50][2];
int H,W,N;
int six,siy,tix,tiy;

int d[50][50];
state prev[50][50];

int dfs(){
  for(int i=0;i<50;i++)
    for(int j=0;j<50;j++)
      d[i][j]=-1;

  d[six][siy]=0;
  queue<state> Q;
  Q.push((state){six,siy});

  while(!Q.empty()){
    state s=Q.front();Q.pop();
    int y=s.y,x=s.x;
    int cost=d[x][y];
    // cout<<x<<' '<<y<<' '<<cost<<endl;

    if(y+1<H && d[x][y+1]==-1 && !f[x][y][0]){
      d[x][y+1]=cost+1;
      prev[x][y+1]=s;
      Q.push((state){x,y+1});
    }
    
    if(x+1<W && d[x+1][y]==-1 && !f[x][y][1]){
      d[x+1][y]=cost+1;
      prev[x+1][y]=s;
      Q.push((state){x+1,y});
    }

    if(y>0 && d[x][y-1]==-1 && !f[x][y-1][0]){
      d[x][y-1]=cost+1;
      prev[x][y-1]=s;
      Q.push((state){x,y-1});
    }

    if(x>0 && d[x-1][y]==-1 && !f[x-1][y][1]){
      d[x-1][y]=cost+1;
      prev[x-1][y]=s;
      Q.push((state){x-1,y});
    }
  }

  return d[tix][tiy];
}

void init(){
  for(int i=0;i<50;i++)
    for(int j=0;j<50;j++)
      f[i][j][0]=f[i][j][1]=false;
}


int main(){
  while(cin>>W>>H>>N){
    init();
    for(int i=0;i<N;i++){
      int ax,ay,bx,by;
      cin>>ax>>ay>>bx>>by;
      if(ax==bx){// |
	if(ay>by)swap(ay,by);
	for(int y=ay;y<by;y++){
	  if(ax)f[ax-1][y][1]=true;
	}
      }else if(ay==by){// -
	if(ax>bx)swap(ax,bx);
	for(int x=ax;x<bx;x++){
	  if(ay)f[x][ay-1][0]=true;
	}
      }
    }
    cin>>six>>siy>>tix>>tiy;
    int A=dfs();
    if(A==-1){
      cout<<0<<endl;
      continue;
    }
    vector<state> vec;
    state s=(state){tix,tiy};
    while(1){
      vec.push_back(s);
      if(s.x==six&&s.y==siy)break;
      s=prev[s.x][s.y];
    }
    reverse(vec.begin(),vec.end());
    int B=A;
    for(int i=0;i+1<(int)vec.size();i++){
      int ax=vec[i].x;
      int ay=vec[i].y;
      int bx=vec[i+1].x;
      int by=vec[i+1].y;

      if(ax==bx){
	if(ay>by)swap(ay,by);
	f[ax][ay][0]=true;
      }else if(ay==by){
	if(ax>bx)swap(ax,bx);
	f[ax][ay][1]=true;
      }

      B=max(B,dfs());
      if(ax==bx){
	if(ay>by)swap(ay,by);
	f[ax][ay][0]=false;
      }else if(ay==by){
	if(ax>bx)swap(ax,bx);
	f[ax][ay][1]=false;
      }
    }
    cout<<B-A<<endl;
  }
  return 0;
}

Measured memory_bytes: 1304
import java.util.Scanner;

public class Main{
	public Main(){
		Scanner sc = new Scanner(System.in);
		
		while(sc.hasNext()){
			String[] str = (sc.nextLine()).split(" ");
			String m = "", w = "";
			
			int i = 0, max = 0, a;
			for(String s: str){
				a = 0;
				for(String st: str){
					if(s.equals(st)){
						a++;
					}
				}
				if(max < a){
					max = a;
					w = s;
				}
				if(s.length() > m.length()){
					m = s;
				}
				i++;
			}
			System.out.println(w+" "+m);
		}
	}

	public static void main(String[] args){
		new Main();
	}
}

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

const int N = 100005;

int n;
pair<int, int> L[N], R[N];

bool used[N];

long long solve1() {
  long long ans = 0;
  int cur = 0;
  
  for (int i=0; i<n; i++) used[i] = false;
  
  for (int i=0; i<n; i++) {
    if (!used[L[i].second]) {
      ans += max(L[i].first - cur, 0);
      used[L[i].second] = true;
      
      if (L[i].first - cur > 0) cur = L[i].first;
    }
    
    if (!used[R[i].second]) {
      ans += max(cur - R[i].first, 0);
      used[R[i].second] = true;
      
      if (cur - R[i].first > 0) cur = R[i].first;
    }
  }
  
  return ans + abs(cur);
}

long long solve2() {
  long long ans = 0;
  int cur = 0;
  for (int i=0; i<n; i++) used[i] = false;
  for (int i=0; i<n; i++) {
    if (!used[R[i].second]) {
      ans += max(cur - R[i].first, 0);
      used[R[i].second] = true;
      
      if (cur - R[i].first > 0) cur = R[i].first;
    }
    
    if (!used[L[i].second]) {
      ans += max(L[i].first - cur, 0);
      used[L[i].second] = true;
      
      if (L[i].first - cur > 0) cur = L[i].first;
    }
  }
  
  return ans + abs(cur);
}

int main() {
  scanf("%d", &n);
  for (int i=0; i<n; i++) {
    int l, r;
    scanf("%d %d", &l, &r);
    
    L[i] = {l, i};
    R[i] = {r, i};
  }
  
  sort(L, L + n, greater<pair<int, int>>());
  sort(R, R + n);
  
  
  printf("%lld\n", max(solve1(), solve2()));
  return 0;
}

Measured memory_bytes: 1920
import math, sys
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from copy import deepcopy
from functools import lru_cache
from heapq import heapify, heappop, heappush
from itertools import accumulate, combinations, permutations
input = sys.stdin.readline
mod = 10**9 + 7
ns = lambda: input().strip()
ni = lambda: int(input().strip())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))

n = ni()
A = nl()

abstotal = sum([abs(i) for i in A])
absmin = min([abs(i) for i in A])
if len([i for i in A if i < 0]) % 2 == 0:
    ans = abstotal
else:
    ans = abstotal - 2 * absmin
print(ans)



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

typedef long long ll;

#define pb push_back
#define mkp make_pair
#define ff first
#define ss second
#define all(a) a.begin(), a.end()
#define clr(a, b) memset(a, b, sizeof(a))
#define forn(i, n) for(int i=0; i<(int)(n); ++i)
#define forab(i, a, b) for(int i=(int)(a); i<=(int)(b); ++i)
#define FOR(it,c) for ( __typeof((c).begin()) it=(c).begin(); it!=(c).end(); it++ )
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
#ifdef LOCAL
    clock_t tStart = clock();
#endif
    string s;
    cin >> s;
    int i = 0, c = 0;
    while(i+1 < s.length()) {
        if(s[i] == 'h' && s[i+1] == 'i') {
            c += 2;
        }
        ++i;
    }
    if(c == (int)s.length())
        cout << "Yes\n";
    else
        cout << "No\n";
#ifdef LOCAL
    cerr << "Time elapsed: " << 1.0 * (clock() - tStart)/ CLOCKS_PER_SEC << " s.\n";
#endif
    return 0;
}


Measured memory_bytes: 256
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <stack>
#include <string>

typedef int type;
using namespace std;
const bool isDebug = false;


stack<int> numstack;
void solve(){
    string s;
    while(cin>>s){
        try{
            //int n = std::stoi(s);
            int n = stoi(s);
            numstack.push(n);
        }
        catch (...){
            int b = numstack.top();
            numstack.pop();
            int a = numstack.top();
            numstack.pop();
            int ans = 0;
            switch(s.c_str()[0]){
                case '+':
                    ans = a + b;
                    if(isDebug) printf("%d = %d + %d\n", ans, a, b);
                    numstack.push(ans);
                    break;
                case '-':
                    ans = a - b;
                    if(isDebug) printf("%d = %d - %d\n", ans, a, b);
                    numstack.push(ans);
                    break;
                case '*':
                    ans = a * b;
                    if(isDebug) printf("%d = %d * %d\n", ans, a, b);
                    numstack.push(ans);
                    break;
                default:
                    printf("ERRRRRR\n");
                    break;
            }
            continue;
        }
    }

    int ans = numstack.top();
    numstack.pop();
    printf("%d\n", ans);
}

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

}

Measured memory_bytes: 3372
#include <bits/stdc++.h>
#define ll long long int

using namespace std;

int main ()
{
	int n;
	cin >> n;
	int a[n+1], b[n+1];
	for (int i=1; i<=n; i++){
		cin >> a[i];
		b[a[i]] = i;
	}
	for (int i=1; i<=n; i++){
		cout << b[i] <<" ";
	}
	cout << endl;
}

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

bool func(int n, int a, int b){
  int now = 0;
  while(n){
    now += n%10;
    n /= 10;
  }
  if(a <= now && now <= b) return true;
  return false;
}

int main(){
  int n; cin >> n;
  map<char,int> mp;
  for(int i = 0; i < n; i++){
    char c; cin >> c;
    mp[c]++;
  }
  int ans = mp.size();
  if(ans == 3) cout << "Three" << endl;
  else cout << "Four" << endl;
  return 0;
}


Measured memory_bytes: 256
using System;
using System.Collections.Generic;
using System.Linq;

namespace ABC079D
{
    class Program
    {
        static void Main(string[] args)
        {
            var HW = ReadInt();
            int H = HW[0];
            int W = HW[1];

            int[,] edge = new int[10, 10];
            for (int i = 0; i < 10; i++)
            {
                var input = ReadInt();
                for (int j = 0; j < 10; j++)
                {
                    edge[i, j] = input[j];
                }
            }

            WarshallFloyd.Init(10, 0, edge);
            bool negativeCycle = false;
            var dp = WarshallFloyd.Start(out negativeCycle);

            int ans = 0;
            for (int h = 0; h < H; h++)
            {
                var input = ReadInt();
                for (int w = 0; w < W; w++)
                {
                    if (input[w] == -1) continue;
                    ans += dp[input[w], 1];
                }
            }

            Console.WriteLine(ans);
            Console.ReadKey();
        }



        static int[] ReadInt()
        {
            int[] ret = Console.ReadLine().Split().Select(int.Parse).ToArray();
            return ret;
        }
        static long[] ReadLong()
        {
            long[] ret = Console.ReadLine().Split().Select(long.Parse).ToArray();
            return ret;
        }
    }
    /// <summary>
    /// ワーシャルフロイド、負の辺に対応、O(V^3)、全頂点間距離
    /// </summary>
    static class WarshallFloyd
    {
        static int INF = int.MaxValue;

        static int _v;
        static int _e;
        static int[,] dp;

        static public void Init(int V, int E, int[,] Edge)
        {
            _v = V; _e = E;

            dp = new int[V, V];
            for (int i = 0; i < V; i++)
            {
                for (int j = 0; j < V; j++)
                {
                    if (i != j) dp[i, j] = INF;
                    if (Edge[i, j] != 0) dp[i, j] = Edge[i, j];
                }
            }
        }

        static public int[,] Start(out bool negativeCycle)
        {
            negativeCycle = false;
            for (int k = 0; k < _v; k++)
            {
                for (int i = 0; i < _v; i++)
                {
                    for (int j = 0; j < _v; j++)
                    {
                        if (dp[i, k] == int.MaxValue || dp[k, j] == int.MaxValue) continue;
                        dp[i, j] = Math.Min(dp[i, j], dp[i, k] + dp[k, j]);
                    }

                    if (dp[i, i] < 0) negativeCycle = true;
                }
            }

            return dp;
        }
    }
}


Measured memory_bytes: 15444
import sys
H, W = map(int, input().split())
S = [list(s.rstrip()) for s in sys.stdin.readlines()]
dp = [[10**9] * W for _ in range(H)]
if S[0][0] == '#':
  dp[0][0] = 1
else:
  dp[0][0] = 0
for h in range(H):
  for w in range(W):
    for a, b in ((h+1, w), (h, w+1)):
      if a >= H or b >= W:
        continue
      else:
        if S[h][w] == '.' and S[a][b] == '#':
          dp[a][b] = min(dp[a][b], dp[h][w]+1)
        else:
          dp[a][b] = min(dp[a][b], dp[h][w])
print(dp[H-1][W-1])

Measured memory_bytes: 9304
for$x(<>=~/ .* /..$`){$==0;$p[$_]=[$x,++$=]for glob<>}$s[$t=$_+$']=$s[$_],map$s[$t]+=abs$p[$t][$_]-$p[$t-$'][$_],0,1for 1..9e4;/ /&&print$s[$']-$s[$`],$/for<>

Measured memory_bytes: 50688
#include <bits/stdc++.h>
using namespace std;
#define REP(i, n) for(int i = 0; i < n; i++)
int main(){ 
    long long int n,t,b=0;
    cin>>n>>t;
    vector<long long int> a(n);
    REP(i,n) cin>>a[i];
    if(n==1){
        cout<<t;
        return 0;
    }
    REP(i,n-1){
        if(a[i+1]-a[i]<=t){
            b+=a[i+1]-a[i];
        }else{
            b+=t;
        }
    }
    b+=t;
    cout<<b;
    return 0;
}


Measured memory_bytes: 1920
#include<stdio.h>
int main(){
  int h,w,a,y[10010],x[10010],ny,nx,i,j,k,r,t;
  int Y[]={1,0,-1,0};
  int X[]={0,1,0,-1};
  char s[110][110],c;
  while(scanf("%d %d",&h,&w),h){
    for(i=a=0;i<h;i++)scanf("%s",s[i+1]+1);
    for(i=1;i<=h;i++){
      for(j=1;j<=w;j++){
	if(s[i][j]==0)continue;
	a++;
	c=s[i][j];
	s[y[0]=i][x[0]=j]=t=0;
	for(r=1;r-t;t++){
	  for(k=0;k<4;k++){
	    ny=y[t]+Y[k];
	    nx=x[t]+X[k];//printf("%c %c\n",c,s[ny][nx]);
	    if(s[ny][nx]-c)continue;
	    s[y[r]=ny][x[r]=nx]=0;
	    r++;
	  }
	}
      }
    }
    printf("%d\n",a);
  }
  return 0;
}

Measured memory_bytes: 2652
#include <stdio.h>

int main(){
  long long int n, i, j, sum, max, in[5000];
  while(scanf("%lld", &n) && n){
    max = -100000;
    for(i = 0;i < n;i++) scanf("%lld", in + i);
    for(i = 0;i < n;i++){
      sum = 0;
      for(j = i;j < n;j++){
        sum += in[j];
        max = sum > max ? sum : max;
      }
    }

    printf("%lld\n", max);
  }

  return 0;
}

Measured memory_bytes: 632
N, M = map(int, input().split())
X = list(map(int, input().split()))
sortX = sorted(X)
diffX = [sortX[i] - sortX[i-1] for i in range(1, M)]
sdiffX = sorted(diffX)
if N == 1:
    print(sum(sdiffX))
    exit()
ans = sum(sdiffX[:-(N-1)])
print(ans)


Measured memory_bytes: 20460
#include<bits/stdc++.h>
#define itn int
#define lli long long int
#define REP(a,n) for(int i=a;i < n;i++)
#define REP2(a,n) for(int j = a;j<n;j++)
using namespace std;
void Swap(int*a, int*b) {
	int temp = *a;
	*a = *b;
	*b = temp;
}
int main(void) {
	int a, b;
	scanf("%d %d", &a, &b);
	if (a > b) {
		Swap(&a, &b);
	}
	for (int i = 0; i < b; i++) {
		printf("%d", a);
	}
	printf("\n");
	return 0;
}

Measured memory_bytes: 256
/* by Natsu Kinmoe */
#include <bits/stdc++.h>
using namespace std;
#define SZ(x)               ((int)(x).size())
#define all(x)              (x).begin(), (x).end()
#define loop(i, n)          for(int i = 0; i < (n); i++)
#define cont(i, n)          for(int i = 1; i <= (n); i++)
#define circ(i, a, b)       for(int i = (a); i <= (b); i++)
#define range(i, a, b, c)   for(int i = (a); ((c) > 0 ? i <= (b) : i >= (b)); i += (c))
#define foreach(it, v)      for(__typeof((v).begin()) it = (v).begin(); it != (v).end(); it++)
#define y0          y0O0OO00OO0OO0OO0OOO00OO0OO0O0O000OO0
#define y1          y1II11II11III11I1III11II111IIII1II1I1
#define pub         push_back
#define pob         pop_back
#define mak         make_pair
typedef long long   ll;
typedef long double lf;
const int   Inf = 0x3f3f3f3f;
const ll    INF = 0x3f3f3f3f3f3f3f3fll;
/* Source code starts here */

struct Netflow {
	struct Edge {
		int to, cap, rev, cost;
		Edge(int to, int cap, int rev, int cost) : to(to), cap(cap), rev(rev), cost(cost) {}
	};
	vector<Edge> egs[5005];
	void inline addedge(int u, int v, int cap, int cost) {
		egs[u].pub(Edge(v, cap, SZ(egs[v]), cost));
		egs[v].pub(Edge(u, 0, SZ(egs[u]) - 1, 0));
	}
	int d[5005], h[5005];
	int prv[5005], pre[5005];
	int inline mcmf(int bg, int en) {
		int res = 0;
		while(1) {
			priority_queue<pair<int, int> > pq;
			pq.push(mak(0, bg));
			memset(d, Inf, sizeof(d)); d[bg] = 0;
			while(pq.size()) {
				pair<int, int> P = pq.top(); pq.pop();
				int now = P.second, dis = -P.first;
				if(d[now] != dis) continue;
				loop(i, SZ(egs[now])) {
					Edge &e = egs[now][i];
					if(e.cap && d[e.to] > dis + e.cost + h[now] - h[e.to]) {
						d[e.to] = dis + e.cost + h[now] - h[e.to];
						pq.push(mak(-d[e.to], e.to));
						prv[e.to] = now; pre[e.to] = i;
					}
				}
			}
			if(d[en] == Inf) return res;
			circ(i, bg, en) h[i] += d[i];
			int fl = Inf;
			for(int i = en; i != bg; i = prv[i]) {
				fl = min(fl, egs[prv[i]][pre[i]].cap);
			}
			res += fl * h[en];
			for(int i = en; i != bg; i = prv[i]) {
				Edge &e = egs[prv[i]][pre[i]];
				e.cap -= fl;
				egs[i][e.rev].cap += fl;
			}
		}
	}
} nf;

int n, m;
char s[55][55];

int inline id(int x, int y) {
	return x * (m + 1) + y;
}

int main() {
	scanf("%d%d", &n, &m);
	cont(i, n) scanf("%s", s[i] + 1);
	int bg = 0, en = id(n, m) + 1;
	int cnt = 0;
	cont(i, n) cont(j, m) {
		if(s[i][j] == '#') continue;
		int ni = i + 1, nj = j;
		if(ni <= n && s[ni][nj] != '#') {
			nf.addedge(id(i, j), id(ni, nj), Inf, 0);
		}
		ni = i, nj = j + 1;
		if(nj <= m && s[ni][nj] != '#') {
			nf.addedge(id(i, j), id(ni, nj), Inf, 0);
		}
	}
	cont(i, n) cont(j, m) {
		if(s[i][j] == 'o') nf.addedge(bg, id(i, j), 1, 0), cnt += i + j - 233;
		if(s[i][j] != '#') nf.addedge(id(i, j), en, 1, 233 - (i + j));
	}
	printf("%d\n", -nf.mcmf(bg, en) - cnt);
	return 0;
}


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

int main() {
    int N, K;
    cin >> N >> K;
    int ans = 0;
    rep(i, N) {
        int x; cin >> x;
        ans += 2 * min(x, K - x);
    }
    cout << ans << '\n';
    return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <set>
#include <iomanip>
#include <vector>
#include <queue>
#include <map>
#include <numeric>
//#include <bits/stdc++.h>

using namespace std;
const int INF = 1 << 30;
struct P
{
    int x;
    int y;
};

bool cmp(P a ,P b)
{
    return a.x<b.x;
}

int main()
{
    ios::sync_with_stdio(false);
    long long n,m;
    cin>>n>>m;
    P p[n];
    for(int i = 0 ; i < n ;++i)
    {
        int a,b;
        cin>>a>>b;
        p[i].x=a;
        p[i].y=b;
    }
    sort(p,p+n,cmp);
    for(int i = 0 ; i < n ;++i)
    {
        if(p[i].y>=m)
        {    
            cout<<p[i].x<<endl;
            return 0;
        }
        else
            m-=p[i].y;
    }
    return 0;
}

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

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

    string ans;
    if (s[0] == s[s.size() - 1])
    {
        if (s.size() % 2 == 0)
            ans += "First";
        else
            ans += "Second";
    }
    else
    {
        if (s.size() % 2 == 0)
            ans += "Second";
        else
            ans += "First";
    }
    cout << ans << endl;
}


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

const char wall = '#';
vector<vector<char>> fields;
vector<vector<bool>> used;
vector<vector<ll>> dist;
const int dx[4] = {0, -1, 0, 1};
const int dy[4] = {1, 0, -1, 0};

ll N;

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

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  // Globalなvectorのリサイズ
  //A.resize(N);

  ll n, A, B;
  cin >> n >> A >> B;

  ll ans = n/(A+B)*A;
  ll rem = n % (A+B);
  ans += min(rem, A);
  cout << ans << endl;
  return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#define INF 1e18
#define int long long
#define Rep(i, a, n) for (int i = (a); i < (n); i++)
#define Repr(i, n, a) for (int i = (n); i >= (a); i--)
#define rep(i, n) Rep(i, 0, n)
#define repr(i, n) Repr(i, n, 0)
#define all(a) a.begin(), a.end()
using namespace std;
typedef pair<int, int> P;
typedef pair<int, P> PP;
const int mod = 1000000007;

int dp[1010][1010];

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

    int h, w;
    cin >> h >> w;
    vector<string> v(h);
    rep(i, h) cin >> v[i];
    v[0][0] = '#';
    dp[1][1] = 1;
    rep(i, h)
    {
        rep(j, w)
        {
            if (v[i][j] == '#')
                continue;
            dp[i + 1][j + 1] = (dp[i + 1][j] + dp[i][j + 1]) % mod;
        }
    }
    cout << dp[h][w] << endl;
}

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

int main(){
  int N, X;
  cin >> N >> X;
  vector<int> m(N);
  int sum = 0;
  for(int i = 0; i < N; i++){
    cin >> m[i];
    sum += m[i];
  }

  int ans = N;
  int s = X;
  s -= sum;
  sort(m.begin() , m.end());

  int t = 0;
  int j = 0;
  while(1){
    t += m[j];
    if( s >= t ) ans++;
    else{ break; }
  } 

  cout << ans;
  return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define F first
#define S second
#define pii pair<int, int>
#define eb emplace_back
#define all(v) v.begin(), v.end()
#define rep(i, n) for (int i = 0; i < n; ++i)
#define rep3(i, l, n) for (int i = l; i < n; ++i)
#define max(a, b) (a > b ? a : b)
#define min(a, b) (a < b ? a : b)
#define chmax(a, b) a = (a >= b ? a : b)
#define chmin(a, b) a = (a <= b ? a : b)
#define out(a) cout << a << endl
#define outa(a, n) { rep(_, n) cout << a[_] << " "; cout << endl; }
#define outp(a, n) { cout << endl; rep(_, n) cout << a[_].F << " " << a[_].S << endl; }
#define SZ(v) (int)v.size()
#define inf (int)(1e9+7)
#define abs(x) (x >= 0 ? x : -(x))
#define ceil(a, b) a / b + !!(a % b)
#define FIX(a) fixed << setprecision(a)
#define LB(v, n) (int)(lower_bound(all(v), n) - v.begin())
#define UB(v, n) (int)(upper_bound(all(v), n) - v.begin())

int main_wa(int a, int b, int c) {
    if (a % 2 != 0 || b % 2 != 0 || c % 2 != 0) return 0;
    if (a == b && b == c) return -1;
    
    rep(i, 1000000) {
        int aa = b / 2 + c / 2, bb = a / 2 + c / 2, cc = a / 2 + b / 2;
        a = aa; b = bb; c = cc;
        // out(a << " " << b << " " << c);
        if (a % 2 != 0 || b % 2 != 0 || c % 2 != 0) {
            return i + 1;
        }
    }
    return -1;
}

int main_ac(int a, int b, int c) {
    if (a % 2 != 0 || b % 2 != 0 || c % 2 != 0) return 0;
    int cnt = 0;
    while (1) {
        int tmp = a / 2 + b / 2;
        int tmp2 = a / 2 + c / 2;
        int tmp3 = b / 2 + c / 2;
        a = tmp3; b = tmp2; c = tmp;
        //cout << a << " " << b << " " << c << endl;
        cnt++;
        if (a % 2 != 0 || b % 2 != 0 || c % 2 != 0) break;
        if (cnt > inf / 100) return -1;
    }
    return cnt;
}

random_device rnd;
mt19937 mt(rnd());
uniform_int_distribution<> rand100(1, 100);

int main() {
    // while (1) {
        // int a = rand100(mt), b = rand100(mt), c = rand100(mt);
        int a, b, c;
        cin >> a >> b >> c;
        out(main_wa(a, b, c));
        /*
        int aa = main_wa(a, b, c);
        int bb = main_ac(a, b, c);
        if (aa != bb) {
            out(aa << " " << bb);
            out(a << " " << b << " " << c);
            break;
        }
         */
    // }
}


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

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

typedef int _loop_int;
#define REP(i,n) for(_loop_int i=0;i<(_loop_int)(n);++i)
#define FOR(i,a,b) for(_loop_int i=(_loop_int)(a);i<(_loop_int)(b);++i)
#define FORR(i,a,b) for(_loop_int i=(_loop_int)(b)-1;i>=(_loop_int)(a);--i)

#define DEBUG(x) cout<<#x<<": "<<x<<endl
#define DEBUG_VEC(v) cout<<#v<<":";REP(i,v.size())cout<<" "<<v[i];cout<<endl
#define ALL(a) (a).begin(),(a).end()

#define CHMIN(a,b) a=min((a),(b))
#define CHMAX(a,b) a=max((a),(b))

// mod
const ll MOD = 1000000007ll;
#define FIX(a) ((a)%MOD+MOD)%MOD

// floating
typedef double Real;
const Real EPS = 1e-11;
#define EQ0(x) (abs(x)<EPS)
#define EQ(a,b) (abs(a-b)<EPS)
typedef complex<Real> P;

int n;
int a[125252];
int l[125252], r[125252];

int main(){
  scanf("%d",&n);
  REP(i,n)scanf("%d",a+i);
  l[0] = a[0];
  FOR(i,1,n)l[i] = __gcd(l[i-1],a[i]);
  r[n-1] = a[n-1];
  FORR(i,0,n-1)r[i] = __gcd(r[i+1],a[i]);
  int ans = max(r[1], l[n-2]);
  FOR(i,1,n-1){
    CHMAX(ans,__gcd(l[i-1],r[i+1]));
  }
  printf("%d\n",ans);
  return 0;
}


Measured memory_bytes: 1408
/*         
               JAI SHREE RAM    */
 
 
 
#include<bits/stdc++.h>
using namespace std;
 
#define ff              first
#define ss              second
#define pb              push_back
#define int             long long
#define mp              make_pair
#define pr              pair<long long,long long>
#define vr              vector<long long>
#define mod            1000000007
#define mod2            998244353
#define inf             1e18
#define ps(x,y)         fixed<<setprecision(y)<<x
#define mk(arr,n,type)  type *arr=new type[n];
#define ll              long long
#define ld	            long double
#define w(x)            int x; cin>>x; while(x--)
#define fill(a,b)       memset(a, b, sizeof(a))
#define ios ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);


class Graph { 
    // No. of vertices 
    int V; 
  
    // Pointer to an array containing adjacency lists 
    list<int>* adj; 
  
    // A function used by DFS 
    void DFSUtil(int v, bool visited[]); 
  
public: 
    // Constructor 
    Graph(int V); 
  
    void addEdge(int v, int w); 
    int NumberOfconnectedComponents(); 
}; 
  
// Function to return the number of 
// connected components in an undirected graph 
int Graph::NumberOfconnectedComponents() 
{ 
  
    // Mark all the vertices as not visited 
    bool* visited = new bool[V]; 
  
    // To store the number of connected components 
    int count = 0; 
    for (int v = 0; v < V; v++) 
        visited[v] = false; 
  
    for (int v = 0; v < V; v++) { 
        if (visited[v] == false) { 
            DFSUtil(v, visited); 
            count += 1; 
        } 
    } 
  
    return count; 
} 
  
void Graph::DFSUtil(int v, bool visited[]) 
{ 
  
    // Mark the current node as visited 
    visited[v] = true; 
  
    // Recur for all the vertices 
    // adjacent to this vertex 
    list<int>::iterator i; 
  
    for (i = adj[v].begin(); i != adj[v].end(); ++i) 
        if (!visited[*i]) 
            DFSUtil(*i, visited); 
} 
  
Graph::Graph(int V) 
{ 
    this->V = V; 
    adj = new list<int>[V]; 
} 
  
// Add an undirected edge 
void Graph::addEdge(int v, int w) 
{ 
    adj[v].push_back(w); 
    adj[w].push_back(v); 
} 
void solve()
{
   int n,m;
   cin>>n>>m;
   
   Graph g(n);
   for(int i=0;i<m;i++)
   {
       int a,b;
       cin>>a>>b;
       
       g.addEdge(a-1,b-1); 
   }
   int ans=g.NumberOfconnectedComponents();
   
   cout<<ans-1<<"\n";
}
 
int32_t main()
{ 
      
      ios;
      int test;
     
      
      test=1;
      //cin>>test;
    
      while(test--)
      {
          solve();
      }
       
    
    return 0;
	}

Measured memory_bytes: 13576
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
#define pb push_back
#define mp make_pair
#define fi first 
#define se second
#define mst(x,y) memset(x,y,sizeof(x))

typedef pair<int,int> pii;
typedef long long ll;
typedef double db;
const ll INF = 0x7fffffff;
const db eps = 1e-5;
const ll mod = 1e9+7;
const int MAXN = 100010;
int MIN(int a, int b) {return a>b?b:a;}
int main() {
	ios_base::sync_with_stdio(0);
	int n,m,x=0;
	char a[MAXN];
	cin>>n>>m>>a;
	x += (a[0] == 'R' && a[1] == 'R')+(a[n-1] == 'L' && a[n-2] == 'L');
	for (int i=1;i<n-1;i++) {
		x += (a[i]=='L' && a[i-1] != 'R') + (a[i] == 'R' && a[i+1] != 'L');
	}
	cout<<MIN(n-1,x+2*m)<<endl;
	return 0;
}

Measured memory_bytes: 3228
#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>
#include <functional>
#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<ll, ll, ll, ll> tlglglglg;
typedef tuple<double, double, double> tddd;
typedef complex<double> xy_t;
typedef vector<ll> vll;
typedef vector< vector<ll> > matrix;
typedef unsigned int uint;
typedef unsigned long long ull;
template <class T> using V = vector<T>;
template <class T> using VV = V<V<T>>;
template <class T> using VVV = V<VV<T>>;
#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;
void yesno(bool ok, string yes = "Yes", string no = "No") {
    if (ok) {
        cout << yes << endl;
    } else {
        cout << no << endl;
    }
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    ll N;
    cin >> N;
    ll L[N];
    REP(i, 0, N) {
        cin >> L[i];
    }
    ll ans = 0;
    REP(i, 0, N) {
        REP(j, i + 1, N) {
            REP(k, j + 1, N) {
                if (L[i] == L[j] || L[j] == L[k] || L[k] == L[i]) {
                    continue;
                }
                if (L[k] < L[i] + L[j] && L[k] > abs(L[i] - L[j])) {
                    ans++;
                }
            }
        }
    }
    cout << ans << endl;
}


Measured memory_bytes: 3652
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;

int main() {
    int n, m, ans = 0;
    vector<int> v[100001];
    priority_queue<int> q;
    cin >> n >> m;
    for(int i=0;i<n;i++){
        int a, b;
        cin >> a >> b;
        v[a].push_back(b);
    }
    for(int i=1;i<=m;i++){
        for(int j=0;j<v[i].size();j++){
            q.push(v[i][j]);
        }
        if(q.empty())continue;
        int w = q.top();
        q.pop();
        ans += w;
    }
    cout << ans << endl;
	return 0;
}

Measured memory_bytes: 5632
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()

# 勝てる手の組み合わせを持つ辞書型を生成する
win_hand = {"r": "p", "s": "r", "p": "s"}
ANS = []

# 勝てる手の配列を作成する
for i in range(N):
    ANS.append(win_hand[T[i]])

# 配列を１つの文字列にする
ans = "".join(ANS)

# 制約のある手以降を探索
for i in range(K, N):
    # K回前の手と同じなら出した手をxに置換する
    if ans[i] == ans[i-K]:
        ans = ans[:i] + "x" + ans[i+1:]

# 各手の数と得られる点数を求める
point = ans.count("r")*R + ans.count("s")*S + ans.count("p")*P

print(point)


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

#define int long long
const int INF = 1e15;
typedef pair<int, int> P;

struct Edge {
	int to, cost;
};

int n;
vector<Edge> G[801];
int ss;

int dfs(int v, int p) {
	//if ( ss == 3 ) cout << v << " " << p << endl;
	bool flg = false;
	for ( Edge e : G[v] ) {
		int to = e.to, cost = e.cost;		
		if ( to == p ) continue;
		if ( G[to].size() >= 2 ) flg = true;
	}

	if ( !flg ) return 0;
	
	int ret = 0;	
	for ( Edge e : G[v] ) {
		int to = e.to, cost = e.cost;
		if ( to == p ) continue;
		if ( G[to].size() == 1 ) continue;
		ret += dfs(to, v)+cost;		
	}

	return ret;
}

int calc(int s) {
	ss = s;
	int ret = 0;
	int ma = 0;
	for ( Edge e : G[s] ) {
		int to = e.to, cost = e.cost;
		if ( G[to].size() == 1 ) continue;
		int tmp = dfs(to, s)+cost;
		//if ( s == 7 ) cout << tmp << endl;
		ma = max(ma, tmp);
		ret += tmp*2;
	}

	queue<P> q;
	vector<int> d(n, -1);
	q.push(P(s, 0));
	while ( !q.empty() ) {
		P p = q.front(); q.pop();
		int v = p.first, c = p.second;

		if ( d[v] >= 0 ) continue;
		if ( G[v].size() == 1 ) continue;

		d[v] = c;

		for ( Edge e : G[v] ) {
			int to = e.to, cost = e.cost;
			if ( G[to].size() == 1 ) continue;
			q.push(P(to, c+cost));
		}
	}

	ma = 0;
	for ( int i = 0; i < n; i++ ) ma = max(ma, d[i]);

	//if ( s == 3 ) cout << ma << endl;

	return ret-ma;
}

signed main() {
	
	while ( cin >> n, n ) {
		for ( int i = 0; i < 801; i++ ) G[i].clear();
		int sum = 0;

		{		
			vector<int> p(n);
			for ( int i = 0; i < n-1; i++ ) cin >> p[i], p[i]--;
			for ( int i = 1; i < n; i++ ) {
				int d;
				cin >> d;
				sum += d;
				G[i].push_back(Edge{p[i-1], d});
				G[p[i-1]].push_back(Edge{i, d});
			}
		}

		//for ( int i = 0; i < n; i++ ) cout << G[i].size() << endl;

		int ans = INF;
		int id = 0;
		for ( int i = 0; i < n; i++ ) {
			//if ( ans > calc(i) ) id = i;
			ans = min(ans, calc(i));
		}

		//cout << id << endl;
		cout << ans+sum << endl;
	}	
	return 0;
}



Measured memory_bytes: 3164
K, N = map(int, input().split())
A = list(map(int, input().split()))
A.append(A[0]+K)

max_dist = 0
for i in range(N):
    cur_dist = A[i+1] - A[i]
    if max_dist < cur_dist:
        max_dist = cur_dist

print(str(K - max_dist))


Measured memory_bytes: 25796
/*
 * atcoder/abc138_2nd/d.cpp
 */

// C++ 14
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstring> // memset
#include <cassert>
using namespace std;
#define ll long long
#define loop(__x, __start, __end) for(int __x = __start; __x < __end; __x++)
template <class T> ostream & operator << (ostream & out, vector<T> const & v) {
  for (auto &&a: v) out << a << " "; out << endl; return out;
}
template <class T> void dump(T &a) { cout << a << endl; }
template <class T> bool chmin(T &a, T b) { if (a > b) {a = b; return true; } return false; }
template <class T> bool chmax(T &a, T b) { if (a < b) {a = b; return true; } return false; }

const int MAX = 200001;
int N, Q;
vector<int> G[MAX];
vector<int> A(MAX, 0);
vector<int> B(MAX, 0);
void dfs(int n = 0, int prev = -1, ll acc = 0) {
  acc += A[n];
  B[n] = acc;

  for (auto&&u: G[n]) {
    if (u == prev) continue;
    dfs(u, n, acc);
  }
}
void solve() {
  cin >> N >> Q;
  int a, b, p, x;
  loop(n,0,N-1) {
    cin >> a >> b;
    a--;b--;
    G[a].push_back(b);
    G[b].push_back(a);
  }
  loop(n,0,Q) {
    cin >> p >> x;
    p--;
    A[p] += x;
  }
  dfs();
  loop(n,0,N) cout << B[n] << " ";
  cout << endl;
}
int main() {
  // cout.precision(15); cout << fixed;

  solve();

  return 0;
}


Measured memory_bytes: 24320
#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

int main(void){
	int n;
	char henzi[100][3];
	int x = 0;
	int y = 0;
	int s = 0;
	int i = 0;

	scanf("%d", &n);
	while(i < n)
	{
		cin >> henzi[i];
		i++;
	}

	for(i = 0;i < n; i++)
	{
		if((int)strlen(henzi[i]) == 1)
			x++;
		else
			y++;

		if (x < y)
		{
			s++;
			break;
		}
	}

	if((x == y) && !s)
		cout << "YES" << endl;
	else
		cout << "NO" << endl;

	
	return 0;
}



Measured memory_bytes: 3236
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int x = in.nextInt();
            int a = in.nextInt();
            int b = in.nextInt();
            if (Math.abs(a - x) < Math.abs(b - x))
                out.println("A");
            else
                out.println("B");
        }

    }

    static class InputReader {
        StringTokenizer st;
        BufferedReader br;

        public InputReader(InputStream is) {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            this.br = br;
        }

        public String next() {
            if (st == null || !st.hasMoreTokens()) {
                String nextLine = null;
                try {
                    nextLine = br.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (nextLine == null)
                    return null;
                st = new StringTokenizer(nextLine);
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}
 

Measured memory_bytes: 21332
#include <iostream>

int main()
{
	int N, K;
	std::cin >> N >> K;
	char S[N];
	std::cin >> S;
	--K;

	if (S[K] == 'A')
		S[K] = 'a';
	else if (S[K] == 'B')
		S[K] = 'b';
	else if (S[K] = 'C')
		S[K] = 'c';

	std::cout << S << std::endl;

	return 0;
}

Measured memory_bytes: 256
#include<iostream>
#include<vector>
using namespace std;
bool ip(int x)
{
if((x%5)!=1)return false;
for(int i=2;i<x;i++)
if((x%i)==0)
return false;
return true;
}
int main()
{
vector<int> p;
int n,i=2;
while(p.size()<55)
{
if(ip(i))p.push_back(i);
i++;
}
cin>>n;
for(i=0;i<n;i++)
cout<<p[i]<<" ";
return 0;
}

Measured memory_bytes: 256
N = int(input())
MOD = 10 ** 9 + 7
dp = [[[[0] * 4 for k in range(4)] for j in range(4)] for i in range(N + 4)]

dp[0][0][0][0] = 1

for i in range(1, N + 1):
    for j in range(4):
        for k in range(4):
            for q in range(4):
                for p in range(4):
                    if i >= 3 and (k, q, p) in [(0, 1, 2), (1, 0, 2), (0, 2, 1)]:
                        continue
                    if i >= 4 and (j, q, p) == (0, 1, 2):
                        continue
                    if i >= 4 and (j, k, p) == (0, 1, 2):
                        continue
                    else:
                        dp[i][k][q][p] += dp[i - 1][j][k][q]
                        dp[i][k][q][p] %= MOD

num = 0
for j in range(4):
    for k in range(4):
        for q in range(4):
            num += dp[N][j][k][q]
            num %= MOD
print(num)

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

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

    int n;
    cin >> n;
    vector<int> a(n), b(n);
    for (int i = 0; i < n; i++)
    {
        a[i] = 30000 * (i + 1);
        b[i] = 30000 * (n - i);
    }
    for (int i = 0; i < n; i++)
    {
        int a;
        cin >> a;
        b[a - 1] += i;
    }
    for (int i = 0; i < n; i++)
    {
        cout << a[i];
        if (i < n - 1)
            cout << " ";
        else
            cout << endl;
    }
    for (int i = 0; i < n; i++)
    {
        cout << b[i];
        if (i < n - 1)
            cout << " ";
        else
            cout << endl;
    }
}

Measured memory_bytes: 768
/*****************
B - Popular Vote
****************/

#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1000 + 5;

int main()
{
	int n,m;
	cin >> n >> m;
	int a[N],sum = 0;
	for(int i = 0;i < n;i++){
		cin >> a[i];
		sum += a[i];
	}
	int ans = 0;
	for(int i = 0;i < n;i++){
		if(a[i] * 4 * m < sum)
			continue;
		ans++;
	}
	cout << (ans < m ? "No" : "Yes"); 
	
	return 0;
}

Measured memory_bytes: 256
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
total = 0
for i in range(n):
	total += b[a[i]-1]
	if i > 0:
		if a[i] == a[i-1]+1:
			total += c[a[i-1]-1]
print(total)

Measured memory_bytes: 3064
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> p2;
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll n,r;
    cin>>n>>r;
    if(n>10)
    cout<<r;
    else
    cout<<r+100*(10-n);
}


Measured memory_bytes: 256
#include <iostream>
using namespace std;
int main(){
    int N,M;
    cin >>N >>M;
    int city[50]={};
    for(int i=0; i < M; i++){
        int a,b;
        cin>>a>>b;
        city[a-1]++;
        city[b-1]++;
    }
    for(int i=0; i <N; i++){
        cout<<city[i]<<endl;
    }
    
}

Measured memory_bytes: 256