akhauriyash/Code-Regression huggingface dataset:
import sys
from collections import deque
import copy

def get_read_func(fileobject):
    if fileobject == None :
        return raw_input
    else:
        return fileobject.readline


def main():
    if len(sys.argv) > 1:
        f = open(sys.argv[1])
    else:
        f = None
    read_func = get_read_func(f);
    input_raw = read_func().strip().split()
    N = int(input_raw[0])
    input_raw = read_func().strip().split()
    A_dic = {}
    B_dic = {}
    for i in range(0, N):
        if i % 2 == 0:
            if input_raw[i] in A_dic:
                A_dic[input_raw[i]] += 1
            else:
                A_dic[input_raw[i]] = 1
        else:
            if input_raw[i] in B_dic:
                B_dic[input_raw[i]] += 1
            else:
                B_dic[input_raw[i]] = 1

    max_A_num = 0
    max_B_num = 0
    max_A = 0
    max_B = 0
    for A in A_dic:
        if max_A_num < A_dic[A]:
            max_A_num = A_dic[A]
            max_A = A
    for B in B_dic:
        if max_B_num < B_dic[B]:
            max_B_num = B_dic[B]
            max_B = B

    max_A_num2 = 0
    max_B_num2 = 0
    if max_A == max_B:

            for A in A_dic:
                if A != max_A:
                    max_A_num2 = max(max_A_num2, A_dic[A])

            for B in B_dic:
                if B != max_B:
                    max_B_num2 = max(max_B_num2, B_dic[B])

            if max_A_num2 > max_B_num2:
                max_A_num = max_A_num2
            else:
                max_B_num = max_B_num2

    print N - max_A_num - max_B_num




if __name__ == '__main__':
    main()


Measured memory_bytes: 19020
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <queue>
#include <stack>
#include <algorithm>
#include <limits>
#include <numeric>
#include <cassert>

#define seq(i, n) for (int i = 0; i < (n); i++)
#define seq2(i, f, t) for (int i = (f); i < (t); i++)
#define rev(i, n) for (int i = (n); i >= 0; i--)
#define rev2(i, f, t) for (int i = (f); i >= (t); i--)
#define all(x) (x).begin(),(x).end()
#define max(x, y) ((x) > (y) ? (x) : (y))
#define min(x, y) ((x) < (y) ? (x) : (y))

using namespace std;

using ll = long long;

int solve(int n, vector<int> i) {
  int res = 100000000;
  seq2(k,1,n-1){
    int a,b;
    a=accumulate(i.begin(),i.begin()+k+1, 0);
    b=accumulate(i.begin()+k+1,i.end(), 0);
    int c=abs(a-b);
    if(res>c){
      res=c;
    }
  }
  return res;
}

int main() {
#ifdef TEST
  assert(solve(3, {1, 2, 3}) == 0); 
  assert(solve(4, {1, 3, 1, 1}) == 2); 
  assert(solve(8, {27, 23, 76, 2, 3, 5, 62, 52}) == 2); 
#else
  int n;
  vector<int> v;
  cin >> n;
  seq(i, n) {
    int d;
    scanf("%d",&d);
    v.push_back(d);
  }
  cout << solve(n, v) << endl;
#endif

  return 0;
}


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

#define MAX_N 100000

using namespace std;

int n, k, s;
int nr;

int a[MAX_N + 1];

int main()
{
    cin >> n >> k >> s;

    nr = (s == (int)(1e9) ? 2 : s + 1);

    if(k == n)
    {
        for(int i = 1; i <= n; i ++)
            a[i] = s;
    }

    else
        if(k == 0)
        {
            for(int i = 1; i <= n; i ++)
                a[i] = nr;
        }
    else
        if(k > 0)
        {
            for(int i = 1; i <= k; i ++)
                a[i] = s;

            for(int i = k + 1; i <= n; i ++)
                a[i] = nr;
        }

    for(int i = 1; i <= n; i ++)
        cout << a[i] << " " ;
    cout << "\n";

    return 0;
}


Measured memory_bytes: 1664
import sys
input = sys.stdin.readline


n = int(input())
dg = 10**6
edge = [[] for _ in [0]*n]
hen = []


for _ in [0]*(n-1):
    a,b = map(int,input().split())
    edge[a-1].append(b-1)
    edge[b-1].append(a-1)
    hen.append((a-1)*dg+b-1)

p = -1
q = -1
for i in range(n):
    if p < len(edge[i]):
        p = max(p,len(edge[i]))
        q = i

par = [-2]*n
chi = [[] for _ in [0]*n]
tank = []
new = [q]
par[q] = -1

while len(new) != 0:
    tank = []
    for e in new:
        for ch in edge[e]:
            if par[ch] < -1:
                par[ch] = e
                chi[e].append(ch)
                tank.append(ch)
    new = tank


co = [0]*n
new = [q]
while len(new) != 0:
    tank = []
    for e in new:
        color = 1
        for ch in chi[e]:
            if color == co[e]:
                color += 1
            co[ch] = color
            color += 1
            tank.append(ch)
    new = tank

print(p)
for e in hen:
    a,b = e//dg,e%dg
    if par[a] == b:
        print(co[a])
    else:
        print(co[b])


Measured memory_bytes: 80672
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
const int INF = (1<<30);
const ll INFLL = (1ll<<60);
const ll MOD = (ll)(1e9+7);

#define l_ength size

void mul_mod(ll& a, ll b){
	a *= b;
	a %= MOD;
}

void add_mod(ll& a, ll b){
	a = (a<MOD)?a:(a-MOD);
	b = (b<MOD)?b:(b-MOD);
	a += b;
	a = (a<MOD)?a:(a-MOD);
}

vector<int> v;

int main(void){
	int n,i,m=0;
	cin >> n;
	for(i=0; i<20; ++i){
		if(n==(1<<i)){
			cout << "No" << endl;
			return 0;
		}else if(n<(1<<i)){
			break;
		}
		m = max(m,(1<<i));
	}
	cout << "Yes" << endl;
	cout << 1+n << " " << 2+n << endl;
	for(i=2; i<n; i+=2){
		cout << 1 << " " << i << endl;
		cout << 1 << " " << i+1 << endl;
		cout << i << " " << i+1+n << endl;
		cout << i+1 << " " << i+n << endl;
	}
	if(n%2==0){
		cout << m << " " << n << endl;
		cout << (n^m^1) << " " << n+n << endl;
	}
	return 0;
}


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

int main ()
{
    int p;
    int a,b;
    int n,m;
    while(1){
        n=m=0;
        cin>>p;
        if(p==0){
            break;
        }
        for(int i=0;i<p;i++){
            cin>>a>>b;
            if(a>b){
                n+=a;
                n+=b;
            }else if(a<b){
                m+=a;
                m+=b;
            }else{
                n+=a;
                m+=b;
            }
        }
        cout<<n<<" "<<m<<endl;
    }
    return 0;
}

Measured memory_bytes: 1160
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <cmath>
#include <deque>
#include <iterator>
#include <map>
#include <queue>
#include <stack>
#include <string>
#include <tuple>
#include <utility>
#include <limits>
#include <iomanip>
using namespace std;

using ll=long long;
template<class T> using V = vector<T>;
template<class T, class U> using P = pair<T, U>;
using vll = V<ll>;
using vvll = V<vll>;
#define rep(i, k, n) for (ll i=k; i<(ll)n; ++i)
#define REP(i, n) rep(i, 0, n)
template<class T> inline bool chmax(T& a, T b) {if (a<b) {a=b; return true;} return false;}
template<class T> inline bool chmin(T& a, T b) {if (a>b) {a=b; return true;} return false;}

const ll MOD = 1000000007;
const ll HIGHINF = (ll)1e18;

int main() {
  string s; cin >> s;
  stack<char> ss;
  REP(i, s.size()) {
    if (s[i] == 'S') ss.push(s[i]);
    else {
      if (ss.empty()) ss.push(s[i]);
      else if (ss.top() == 'S') ss.pop();
      else ss.push(s[i]);
    }
  }
  cout << ss.size() << endl;
  return 0;
}


Measured memory_bytes: 644
n,m = map(int,input().split())
a = [[0,10],[10,100],[100,1000]]
sc = [list(map(int,input().split())) for i in range(m)]
for i in range(a[n-1][0],a[n-1][1]):
  cnt = 0
  for j in range(m):
    s,c = sc[j][0],sc[j][1]
    l = str(i)
    if l[s-1] == str(c):
      cnt += 1
  if cnt == m:
    print(i)
    quit()
print(-1)

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

int main() {
  bool can = true;
  int n, t, x, y;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> t >> x >> y;
    if (t>=x+y && (t-x-y)%2==0) continue;
    else can = false;
  }
  if (can) cout << "Yes" << endl;
  else cout << "No" << endl;
}



Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
#define lli long long int   //used int to avoid mle
#define ulli unsigned long long int 
#define ld long double
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define loop(i,a,b) for(lli i=a;i<b;i++)
#define initialize(array,size,value) for(lli i=0;i<size;i++) array[i]=value
#define couta(array,size) for(lli i=0;i<size;i++) cout<<array[i]<<" "
#define vl vector<lli>
#define vp vector< pair <lli,lli> >
#define sl set<lli>
#define spl set<pll>
#define msl multiset <lli>
#define msp multiset <pll>
#define pll pair<lli, lli>
#define mll map<lli, lli>              //for( map<lli, lli>::iterator i=temp.begin();i!=temp.end();i++)cout<<i->fi<<" "<<i->se<<endl;
#define mvl map<lli, vl>
#define umll unordered_map<lli, lli>
#define vt vector<pair<lli, pll >  >
#define vf vector<pair<pll,pll > >
#define qu queue<lli>
#define pq priority_queue<lli>
#define dq deque <lli>
#define ptr vector<lli>::iterator
#define bs(array,x) binary_search(array.begin(),array.end(),x)
#define lb(array,x) lower_bound(array.begin(),array.end(),x)
#define ub(array,x) upper_bound(array.begin(),array.end(),x)
#define nobw(array,i,j) upper_bound(array.begin(), array.end(), j)-lower_bound(array.begin(), array.end(), i) //number of numbers between i & j
#define vc clear()
#define endl '\n'
#define sp system("pause");
#define INF 9223372036854775807
#define MINF -9223372036854775808
#define start_routine() int begtime = clock();
#define end_routine() int endtime = clock(); cerr << endl << "Time elapsed: " << (endtime - begtime)*1000/CLOCKS_PER_SEC << " ms"; return 0
lli mod=1000000007;
//string s=bitset<32>(n).to_string();
int main()
{
 	ios::sync_with_stdio(0);
    cin.tie(0);
   
    lli a,b;
    cin>>a>>b;
    lli t[4]={0};
    t[a]=1,t[b]=1;

    for(lli i=1;i<=3;i++){
    	if(t[i]==0)cout<<i;
    }
  
}

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

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; }

#define FOR(i,a,b) for(ll i=(a);i<(b);++i)
#define ALL(v) (v).begin(), (v).end()
#define p(s) cout<<(s)<<endl
#define p2(s, t) cout << (s) << " " << (t) << endl
#define br() p("")
#define pn(s) cout << (#s) << " " << (s) << endl

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

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

ll A, B, C, D;

// n以下で、CでもDでも割り切れない個数
ll f(ll n){
    ll ans = n;
    ans -= n/C;
    ans -= n/D;
    ans += n/lcm(C, D);
    return ans;
}

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

    // input
    cin >> A >> B >> C >> D;

    ll ans = f(B) - f(A-1);
    p(ans);
    
    return 0;
}

Measured memory_bytes: 256
#include<stdio.h>
int main(){
int a,b,c,k;
scanf("%d%d%d%d", &a, &b, &c, &k);
  
  if(a>=k){
    printf("%d\n",k);
    return 0;
  }
  else{
    if(a+b>=k){
      printf("%d\n",a);
      return 0;
    }
    else{
      printf("%d\n",a-(k-a-b));
    return 0;
    }
  }

}


Measured memory_bytes: 1724
#include <iostream>
#include <algorithm>
#include<bits/stdc++.h>
#include<iomanip>
using namespace std;
typedef long long ll;
int main()
{
	int n;
	cin>>n;
	ll pow[58];
	pow[0]=1;
	for(int i=1;i<58;i++)
	pow[i]=2*pow[i-1];
	ll ans=0,z;
	ll x,y;
	cin>>x>>y;
	for(int i=2;i<n;i++)
	{
		cin>>z;
		ans=ans^z;
	}
	ll sum1=x+y;
	sum1=(sum1-ans);
    //cout<<sum1<<"\n";
	if(sum1<0||sum1%2!=0)
	{
      //cout<<"hi1\n";
		cout<<-1;
		return 0;
	}
	sum1=sum1/2;
	int i=0;
	ll temp1=sum1;
	ll temp2=ans;
	ll final =0;
	while(temp1)
	{
		if(temp1%2==1&&temp2%2==0)
		final+=pow[i];
		if(temp1%2==1&&temp2%2==1)
		{
			cout<<-1;
			return 0;
		}
		i++;
		temp1/=2;
		temp2/=2;
	}	
	if(final>x)
	{
    //   cout<<"hi2\n";
		cout<<-1;
		return 0;
	}
	int g[58]={0};
    for(int i=0;i<58;i++)
    {
    	g[i]=ans%2;
    	ans=ans/2;
	}
	for(int i=57;i>=0;i--)
	{
		if(g[i]&&final+pow[i]<=x)
		final=final+pow[i];
	}
    if(final==0)
    cout<<-1;
    else
	cout<<x-final;
	return 0;
}

Measured memory_bytes: 3592
def kochfunc(n1, x1, y1, x2, y2):   #関数作成
    if n1 > n-1:                      #breakの条件
        return 
    
    root3 = 1.732050807
    sx = (x1*2 + x2)/3 ; sy  = (y1*2 + y2)/3 
    tx = (x1 + x2*2)/3 ; ty  = (y1 + y2*2)/3
    
    vx = tx-sx; vy = ty-sy
    ux = sx + (vx - vy*root3)/2
    uy = sy + (vx*root3 + vy)/2
    
    kochfunc(n1+1, x1, y1, sx, sy)      #再帰関数
    print('{:.8f}'.format(sx), '{:.8f}'.format(sy))
    kochfunc(n1+1, sx, sy, ux, uy)
    print('{:.8f}'.format(ux), '{:.8f}'.format(uy))
    kochfunc(n1+1, ux, uy, tx, ty)
    print('{:.8f}'.format(tx), '{:.8f}'.format(ty))
    kochfunc(n1+1, tx, ty, x2, y2)
    
n = int(input())    
print('{:.8f}'.format(0), '{:.8f}'.format(0))    
kochfunc(0, 0, 0, 100, 0)
print('{:.8f}'.format(100), '{:.8f}'.format(0))


Measured memory_bytes: 5740
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define L long
const int INF = 1e5;

int n;
vector<int> h(INF);
int ans = 0;

int dp[INF];

int findAns(int i){

    if(dp[i] != -1){
        return dp[i];
    }

    if(i == 0){
        dp[0] = 0;
        return 0;
    }

    if(i == 1){
        dp[1] = abs(h[1] - h[0]);
        return abs(h[1] - h[0]);
    }

    return dp[i] = min( findAns(i - 1) + abs(h[i] - h[i - 1]), findAns(i - 2) + abs(h[i] - h[i - 2]));

}

void solve(){
    int n;
    cin >> n;

    for(int i =0 ;i <n;i ++){
        cin >> h[i];
    }

    memset(dp, -1, sizeof(dp));

    int ans = findAns(n - 1);
    cout << ans << "\n";
}

int main(){
    solve();
}


Measured memory_bytes: 6412
n = int(input())
A = list(map(int, input().split()))
A.sort()

ndiv_sum = 0
max_num = A[-1]
no_div = [True] * (max_num+1)
for i in range(len(A)-1):
    if no_div[A[i]]:
        for j in range(A[i], max_num+1, A[i]):
            no_div[j] = False
        if A[i]!=A[i+1]:
            ndiv_sum += 1
if no_div[A[-1]]:
    ndiv_sum += 1
print(ndiv_sum)


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

using namespace std;

const int HUGEI = 2147483647;  // (1 << 31) - 1
const long long HUGEL = 9223372036854775807;  // (1 << 63) - 1
const string ABC = "abcdefghijklmnopqrstuvwxyz";

int main(void) {
    int n;
    vector <string> sn;
    cin >> n;
    for (int i = 0; i < n; i++) {
        string s;
        cin >> s;
        sn.push_back(s);
    }
    string res = "";
    for (char c = 'a'; c <= 'z'; c++) {
        int mincnt = HUGEI;
        for (int i = 0; i < n; i++) {
            int cnt = 0;
            for (unsigned int j = 0; j < sn[i].size(); j++) {
                char cs = sn[i][j];
                if (cs == c) {
                    cnt++;
                }
            }
            mincnt = min(mincnt, cnt);
        }
        for (int l = 0; l < mincnt; l++) {
            res += string(&c)[0];
        }
    }
    cout << res << endl;
    return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); i++)
#define irep(i, n) for (int i = (n); i >= 0; i--)
using namespace std;
using ll = long long;
using P = pair<int, int>;
const int INF = 1 << 25;
const int MOD = 1e9+7;
 
int main() {
	int n, a;
	cin >> n;
	vector<int> c(n);
	rep(i,n) {
		cin >> a;
		c[i] = a-i-1;
	}
	sort(c.begin(), c.end());
	ll ans = 0;
	if (n%2) {
		rep(i,n) {
			ans += abs(c[i] - c[n/2]);
		}
	} else {
		ll l = 0, r = 0;
		rep(i,n) {
			l += abs(c[i]-c[n/2-1]);
			r += abs(c[i]-c[n/2]);
		}
		ans = min(l,r);
	}
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 3996
#include <bits/stdc++.h>
#define rep(i,a) for(int i=0;i<int(a);++i)
#define REP(i,a,b) for(int i=int(a);i<int(b);++i)
#define pb push_back
#define mp make_pair
#define F first
#define S second
using ll = long long;
using itn = int;
using namespace std;
static const long double GRATIO=(long double)(1+sqrt(5))/2;
ll GCD(ll a, ll b){
    return b ? GCD(b, a%b) : a;
}
ll LCM(ll a, ll b){
    return a/GCD(a,b)*b;
}
int main(){
    ll H,W;
    cin>>H>>W;
    if(H%3==0 || W%3==0){
        cout<<0<<endl;
        return 0;
    }

    //残っているものについてはT字に切ればいい.うまく見つける
    ll split=W/2;
    ll min_subt=1e9;
    rep(i,H+1){
        ll Sc=W*i;
        ll Sa=(H-i)*split;
        if(W%2){
            ll Sb=(H-i)*(split+1);
            min_subt = min(min_subt, abs(max(Sa,max(Sb,Sc))-min(Sa,min(Sb,Sc))));    
        }else{
            min_subt = min(min_subt, abs(max(Sa,Sc)-min(Sa,Sc)));
        }

    }
    split=H/2;
    rep(i,W+1){
        ll Sc=H*i;
        ll Sa=(W-i)*split;
        if(H%2){
            ll Sb=(H-i)*(split+1);
            min_subt = min(min_subt, abs(max(Sa,max(Sb,Sc))-min(Sa,min(Sb,Sc))));    
        }else{
            min_subt = min(min_subt, abs(max(Sa,Sc)-min(Sa,Sc)));
        }

    }
    rep(i,H+1){
        ll Sc=W*i;
        ll Sa=W*((H-i)/2);
        if((H-i)%2){
            ll Sb=W*(((H-i)/2)+1);
            min_subt = min(min_subt, abs(max(Sa,max(Sb,Sc))-min(Sa,min(Sb,Sc))));    
        }else{
            min_subt = min(min_subt, abs(max(Sa,Sc)-min(Sa,Sc)));
        }
    }
    rep(i,W+1){
        ll Sc=H*i;
        ll Sa=H*((W-i)/2);
        if((W-i)%2){
            ll Sb=H*(((H-i)/2)+1);
            min_subt = min(min_subt, abs(max(Sa,max(Sb,Sc))-min(Sa,min(Sb,Sc))));    
        }else{
            min_subt = min(min_subt, abs(max(Sa,Sc)-min(Sa,Sc)));
        }
    }
    cout<<min_subt<<endl;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
//#include<boost\lexical_cast.hpp> 
#define ll long long
#define pi pair<int,int>
#define pl pair<ll,ll>
#define vi vector<int> 
#define vl vector<ll>
#define vpi vector<pi> 
#define vpl vector<pl>
#define pb push_back
#define mp make_pair
#define sz(x) (int)x.size()
#define INF 0x7fffffff
#define LINF 2000000000000000007
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl
#define ss second
#define ff first
#define endl "\n"
#define mod 1000000007
#define MAX 100010
#define fill(a,x) memset(x,a,sizeof x)
#define all(x) x.begin(),x.end()
#define clr(x) memset(x,0,sizeof x)
#define rep(i,a,n) for(ll i=a;i<n;++i)
#define repr(i,n,b) for(ll i=n;i>=b;i--)
#define repit(itr,x) for(auto itr=x.begin();itr!=x.end();itr++)
using namespace std;
//using boost::lexical_cast;
//using boost::bad_lexical_cast;
int main(){
	ios_base::sync_with_stdio(false); cin.tie(NULL);
	int test=1;
	// cin>>test;
	while(test--){
		int n; cin>>n;
		vi dp(3);

		rep(days,0,n){
			vi new_dp(3,-INF);
			vi c(3,0);
			rep(i,0,3){
				cin>>c[i];
			}
			rep(i,0,3){
				rep(j,0,3){
					if(i!=j){
						new_dp[j]=max(new_dp[j],dp[i]+c[j]);
					}
				}
			}
			dp=new_dp;
		}
//			dp=new_dp;
			cout<<max({dp[0],dp[1],dp[2]})<<endl;
	}
}


Measured memory_bytes: 256
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <iomanip>
#include <array>
#include <numeric>
#include <regex>
#include <bitset>
#include <deque>
#include <cassert>

using namespace std;
typedef long long ll;
typedef pair<int, int> p_ii;

const int INF = 1e9;
const double PI = acos(-1.0);
const ll MOD = 1e9 + 7;

#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define debug(x) cout << #x << ": " << x << endl;
#define popcnt __builtin_popcount


int main() {
    int n, h, w;
    cin>>n>>h>>w;
    cout<<(n-h+1)*(n-w+1)<<endl;

    return 0;
}

Measured memory_bytes: 256
import os
import sys
from atexit import register
from io import BytesIO
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))
input = lambda: sys.stdin.readline().rstrip('\r\n')
raw_input = lambda: sys.stdin.readline().rstrip('\r\n')

n,k = [int(x) for x in input().split()]
perm  =  [int(x)-1 for x in input().split()]
cost = [int(x) for x in input().split()]


ans = -10**10
for node in xrange(n):
    visited = [False for _ in xrange(n)]
    curnode = perm[node]
    cost_lst = [0]
    while not visited[curnode]:
        visited[curnode] = True
        cost_lst.append(cost_lst[-1] + cost[curnode])
        curnode = perm[curnode]

    cycles_n = k // (len(cost_lst)-1)
    rem = k % (len(cost_lst)-1)

    # print(cost_lst)
    if cycles_n > 0:
        ans = max(ans, max(cost_lst[1:]))
    if cycles_n == 0:
        ans = max(ans, max(cost_lst[1:rem+1]))
    if cycles_n > 0 and cost_lst[-1] > 0:
        if rem != 0:
            opt1 = cycles_n * cost_lst[-1] + max(cost_lst[1:rem+1])
        else:
            opt1 = (cycles_n-1) * cost_lst[-1] + max(cost_lst[1:])
        ans = max(ans, opt1)

print(ans)
    


Measured memory_bytes: 111792
//! ----------------------------------------------
//! Framework <https://github.com/vain0x/procon>
//!
//! See the bottom of file for solution.
//! ----------------------------------------------

#![allow(unused_imports)]
#![allow(non_snake_case)]

use std::cell::RefCell;
use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::fmt::{Debug, Display, Formatter, Write as FmtWrite};
use std::io::{stderr, stdin, BufRead, Write};
use std::mem::{replace, swap};
use std::ops::*;
use std::rc::Rc;

/// Print values to standard error if debug mode.
#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), stderr());
            writeln!(err, "\x1B[33m{}\x1B[0m = {:?}", e, $e).unwrap()
        })*
    };
}

/// Read from standard input and parse each word.
/// - `read!(T, U, ..)` parses a line as a tuple of words.
/// - `read![[T]]` parses a line as an array of words.
/// - `read![..; N]` parses `N` lines, using `read!(..)` repeatedly.
#[allow(unused_macros)]
macro_rules! read {
    ([$t:ty] ; $n:expr) =>
        ((0..$n).map(|_| read!([$t])).collect::<Vec<_>>());
    ($($t:ty),+ ; $n:expr) =>
        ((0..$n).map(|_| read!($($t),+)).collect::<Vec<_>>());
    ([$t:ty]) =>
        (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::<Vec<$t>>());
    ($($t:ty),*) => {{
        let buf = rl();
        let mut w = buf.split_whitespace();
        ($(w.next().unwrap().parse::<$t>().unwrap()),*)
    }};
}

/// Read a line from standard input.
#[allow(dead_code)]
fn rl() -> String {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();

    #[allow(deprecated)]
    buf.trim_right().to_owned()
}

// -----------------------------------------------
// Solution
// -----------------------------------------------

fn main() {
    let N = read!(usize);
    let odd = (N + 1) / 2;

    println!("{}", odd as f64 / N as f64)
}


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

public class Prog
{
    public void run()
    {
        var input = Console.ReadLine().Split();
        int A = int.Parse(input[0]);
        int P = int.Parse(input[1]);
        int piece = A * 3 + P;
        if(piece%2 == 0)
        {
            Console.WriteLine(piece / 2);
        }
        else
        {
            Console.WriteLine((piece - 1) / 2);
        }
    }
    public static void Main()
    {
        //var input = Console.ReadLine().Split();
        //int[] X = Array.ConvertAll(input, int.Parse);
        var prog = new Prog();
        prog.run();
    }
}

//Array.ConvertAll(int.Parse)

Measured memory_bytes: 11092
#include <iostream>
int main(){
    int N, W;
    std::cin >> N >> W;
    int dp[N + 1][W + 1];//N番目までの品物を選んだ時の時のWの価値の最大
    for(int i = 0; i < N + 1; i++){
        for(int j = 0; j < W + 1; j++) dp[i][j] = 0;
    }
    int v[N], w[N];
    for(int i = 0; i < N; i++) std::cin >> v[i] >> w[i];
    for(int i = 0; i < N; i++){
        for(int j = 0; j <= W; j++){
            if(j - w[i] < 0) dp[i + 1][j] = dp[i][j];
            else if(j - w[i] >= 0){
                dp[i + 1][j] = std::max(dp[i][j], dp[i][j - w[i]] + v[i]);
            }
        }
    }
    std::cout << dp[N][W] << std::endl;
}


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


#define int  long long
#define rep(i,begin,end) for(__typeof(end)i=(begin)-((begin)>(end));i!=(end)-((begin)>(end));i+=1-2*((begin)>(end)))
#define F first
#define S second
#define sz(x) ((int)x.size())
#define pii pair<int,int>
#define vi vector<int>
#define vii vector<pii>
#define pb push_back
#define pf push_front
#define eb emplace_back 
#define all(v) (v).begin(), (v).end()
#define mod 100000
#define mi multiset<int>
#define mii multiset<pii>
#define what_is(x) cerr << #x << " is " << x <<"\n";
#define sortA(v) sort(v.begin(), v.end())
#define sortD(v) sort(v.rbegin(), v.rend())
#define PI 3.14159265358979323846
#define vout(a) for(auto x:a) cout<<x<<" ";
#define INF 10000000000000000

// #define ordered_set tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update>


// using namespace __gnu_pbds;
using namespace std;

int lcm(int a,int b) {return (a*(b/__gcd(a,b)));}

int modp(int a,int m,int n)
{
    // n=n%(m-1);
    // a=a%m;
    int res=1;
    while(n>0)
    {
        if(n&1) res=(res*a);//%m;
        a=(a*a);//%m;
        n>>=1;
    }
    return res;
}

 
void solve()
{
    int t,n,m,i,k,l,r,u,v,w,j,s,pos,sum=0,flag=0,count=0;
    string S,T,U;
    // int h1,m1,h2,m2;
    // long double a,b;
    cin>>n;
    vi a(n),b(n),c(n);
    vii range(n);
    rep(i,0,n)
    {
        cin>>a[i]>>b[i];
        c[i]=b[i]-a[i];
        // range[i].F=a[i];
        // range[i].S=b[i];
    }
    // sort(all(range));
    sortA(a);
    sortA(b);
    sortA(c);
    if(n%2)
    {
        cout<<b[n/2]-a[n/2]+1;
        return;
    }
    else
    {
        cout<<b[n/2]-a[n/2]+b[n/2-1]-a[n/2-1]+1;
        return;
    }
    // int mx=1000000000000000;
    // rep(i,n/2+1,n)
    // {
    //     mx=min(mx,range[i].S);
    // // }
    // if(n%2)
    // {
    //     cout<<range[n/2].S-range[n/2].F+1;
    // }
    // else
    // {
    //     cout<<range[n/2].S-range[n/2].F+1+range[n/2-1].S-range[n/2-1].F;
    // }
}



signed main()
{
    #ifndef ONLINE_JUDGE 
       freopen("input.txt","r",stdin);
       freopen("output.txt","w",stdout);
    #endif
    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t=1;
    // cin>>t;
    while(t--)
    {
        solve();
        if(t)cout<<"\n";
    }
    return 0;
}


Measured memory_bytes: 11120
#coding: utf-8
import math
import heapq
import bisect
import numpy as np
#from scipy.misc import comb

N,M = map(int, input().split())
X = list(map(int, input().split()))
X.sort()

Y = []
for i in range(M-1):
    Y.append(X[i+1]-X[i])
Y.sort()

ans = 0
if N < M:
    ans = sum(Y[:M-N])

print(ans)

Measured memory_bytes: 23028
#include <algorithm>
#include <cmath>
#include <iostream>
#include <limits>
#include <numeric>
#include <string>
#include <type_traits>
#include <vector>
using namespace std;
int main() {
  int x;
  cin >> x;
  //低を５
  // cout << pow(2, 3) << endl;
  for (int iti = 0; iti < pow(10, 9); iti++) {
    // cout << "ITTI" << iti << endl;
    for (int ni = iti; ni > -iti; ni--) {
      // cout << "NI" << ni << endl;
      if (pow(iti, 5) - pow(ni, 5) == x) {
        cout << iti << " " << ni << endl;
        return 0;
      }
    }
  }
}

Measured memory_bytes: 3980
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(), (x).end()
#define allR(x) (x).rbegin(), (x).rend()
using ll = long long;
using P = pair<int, int>;
const int INF (1<<30);

int main() {
  int M, N;
  ll K;
  cin >> N >> M >> K;
  vector<ll> A(N), B(M);
  rep(i, N) cin >> A[i];
  rep(i, M) cin >> B[i];

  if (A[0] > K) {
    ll sB = 0LL;
    rep(i, M) {
      sB += B[i];
      if (sB > K) {
        cout << i << endl;
        return 0;
      }
    }
    
    cout << M << endl;
    return 0;
  }


  int iA = 0;
  ll sA = 0LL;
  rep(i, N) {
    if (sA+A[i] > K) {
      iA = i-1;
      break;
    }

    sA += A[i];

    if (i == N-1) {
      iA = i;
    }
  }


  int ans = iA+1;
  int iB = 0;
  for (int i = iA; i >= 0; i--) {

    for (int j = iB; j < M; j++) {
      if (sA+B[j] > K) {
        break;
      } 
      else {
        sA += B[j];
        iB++;
        ans = max(ans, i+1+iB);
      }
    }

    sA -= A[i];

    for (int j = iB; j < M; j++) {
      if (sA+B[j] > K) {
        break;
      } 
      else {
        sA += B[j];
        iB++;
        ans = max(ans, i+iB);
      }
    }

  }

  cout << ans << endl;



  return 0;
}


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

using namespace std;

#define REP(i,n) for(ll (i) = (0);(i) < (n);++i)
#define REV(i,n) for(ll (i) = (n) - 1;(i) >= 0;--i)
#define PB push_back
#define EB emplace_back
#define MP make_pair
#define FI first
#define SE second
#define SHOW1d(v,n) {REP(WW,n)cerr << v[WW] << ' ';cerr << endl << endl;}
#define SHOW2d(v,WW,HH) {REP(W_,WW){REP(H_,HH)cerr << v[W_][H_] << ' ';cerr << endl;}cerr << endl;}
#define ALL(v) v.begin(),v.end()
#define Decimal fixed<<setprecision(20)
#define INF 1000000000
#define LLINF 1000000000000000000LL
#define MOD 998244353

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

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

	ll n;cin >> n;
	vector<int> v(n);
	REP(i, n)cin >> v[i];
	sort(ALL(v));

	ll ans = 0;
	REP(i, n){
		REP(j, i){
			REP(k, j){
				if(v[j] + v[k] > v[i])ans++;
			}
		}
	}

	cout << ans << endl;

	return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <algorithm>

using namespace std;

int n, l;
string s[101];

int main() {
	cin >> n >> l;
	for(int i = 0; i < n; i++) 
		cin >> s[i];
	sort(s, s + n);
	for(int i = 0; i < n; i++) 
		cout << s[i];
	return 0;
}

Measured memory_bytes: 256
var
  n,m,d,ans:longint;
function check(x:longint):boolean;
begin
  if (m div x)>=n then
  begin
    check:=true;
  end
  else
  begin
    check:=false;
  end;
end;
begin
  ans:=1;
  readln(n,m);
  for d:=1 to trunc(sqrt(m)) do
  begin
    if (m mod d)<>0 then
    begin
      continue;
    end;
    if check(d) then
    begin
      if d>ans then
      begin
        ans:=d;
      end;
    end;
    if check(m div d) then
    begin
      if (m div d)>ans then
      begin
        ans:=m div d;
      end;
    end;
  end;
  writeln(ans);
end.

Measured memory_bytes: 128
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;


string isLessThan(string s, string t)	{
	if (s.length() < t.length())	{
		for (int i = 0; i < s.length(); i++)	{
			if (s[i] < t[i])	{
				return "Yes";
			}
			else if (s[i] > t[i])	{
				return "No";
			}
		}
		return "Yes";
	}
	else if (s.length() >= t.length())	{
		bool valid = false;
		for (int i = 0; i < min(s.length(), t.length()); i--)	{
			if (s[i] > t[i]) return "No";
			else if (s[i] < t[i]) valid = true;
		}
		if (valid) return "Yes";
		return "No";
	}
	return "Noice";
}


int main()	{
	string s, t;
	cin >> s >> t;
	sort(s.begin(), s.end());
	sort(t.begin(), t.end(), greater<char>());
	cout << isLessThan(s, t) << endl;
	return 0;
}


Measured memory_bytes: 3604
N, M = map(int, input().split())
if N == 1:
    ans = M
else:
    ans = 1
    for x in range(2, int(M**0.5)+1):
        if M % x == 0:
            if (M // x) >= N:
                ans = max(ans, x)
            if x >= N:
                ans = max(ans, M // x)
print(ans)


Measured memory_bytes: 3060
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=1e6+5,maxm=1e5+5;
int fac[maxn],pri[maxm],siz;
int a[maxn];
void euler(){
	int i,j;
	siz=0;
	for (i=0;i<maxn;i++) fac[i]=i;
	for (i=2;i<maxn;i++){
		if (fac[i]==i) pri[siz++]=i;
		for (j=0;j<siz&&pri[j]<=fac[i]&&i*pri[j]<maxn;j++)
			fac[i*pri[j]]=pri[j];
	}
}
int main(){
	int i,n;
	euler();
	a[0]=a[1]=0;
	for (i=2;i<maxn;i++)
		a[i]=a[i-1]+(fac[i]==i);
	while (scanf("%d",&n)!=EOF)
		printf("%d\n",a[n]);
	return 0;
}



Measured memory_bytes: 11352
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<map>

using namespace std;

int main() {
	int n;
	cin >> n ;
	string s;
	cin >> s;
	int a[n];
	for (int i = 0; i < n; i++) {
		if (s[i] == 'E')a[i] = 1;
		else a[i] = -1;
	}
	int sum[n] = {};
	sum[0] = a[0];
	for (int i = 1; i < n; i++)sum[i] = sum[i - 1] + a[i];

	int max = -100;
	int k = 0;
	for (int i = 0; i < n; i++) {
		if (sum[i] > max) {
			max = sum[i];
			k = i;
		}
	}
	int count = 0;
	for (int i = 0; i < n; i++) {
		if (i < k&&s[i] == 'W')count++;
		else if (i >k && s[i] == 'E')count++;
	}
	cout << count << endl;

	return 0;
}

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

int main() {
  int64_t X, m;
   m = 100;
  cin >> X;
  int y = 0;
  for (int i = 0; i<X; ++i){
    ++y;
    m *= 1.01;
    if(m>=X) break;
  }
  cout << y << endl;

}


Measured memory_bytes: 3632
p=list(map(int,input().split()))
q=list(map(int,input().split()))
r=list(map(int,input().split()))
n=int(input())
b=[]
for i in range(n):
  b.append(int(input()))

for i in range(0,n):
  for j in range(0,3):
    if b[i]==p[j]:
      p[j]=0
    if b[i]==q[j]:
      q[j]=0
    if b[i]==r[j]:
      r[j]=0

if (p[0]==p[1]==p[2] or
    q[0]==q[1]==q[2] or
    r[0]==r[1]==r[2] or
    p[0]==q[0]==r[0] or
    p[1]==q[1]==r[1] or
    p[2]==q[2]==r[2] or
    p[0]==q[1]==r[2] or
    p[2]==q[1]==r[0]):
  print("Yes")
else:
  print("No")

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

int main(){
    int n,a,b;
    cin>>n>>a>>b;
    string s;
    cin>>s;
    vector<string>  result(n);
    int q_all=0,q_alien=0;

    for(int i=0; i<n; i++){
        if(s.at(i)=='a'){
            if(q_all<a+b){
                result.at(i)="Yes";
                q_all++;
            }else{
                result.at(i)="No";
            }
        }else if(s.at(i)=='b'){
            if(q_all<a+b && q_alien<b){
                result.at(i)="Yes";
                q_all++;
                q_alien++;
            }else{
                result.at(i)="No";
            }
        }else if(s.at(i)=='c'){
            result.at(i)="No";
        }
    }

    for(int i=0; i<n; i++){
        cout<<result.at(i)<<endl;
    }
}

Measured memory_bytes: 6272
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
const ll mod = 1e9+7;



int main(){
    int n;
    cin >> n;
    vector<int> a(n);
    map<int,int> mp;
    for(int i = 0; i < n; i++){
        cin >> a[i];
        mp[a[i]]++;
    }
    int ans = 0;
    for(int i = 0; i < n; i++){
        bool end = false;
        if(mp[a[i]] > 1) continue;
        if(mp[1] > 0 && a[i] == 1) ans++;
        for(int j = 1; j*j <= a[i]; j++){
            if(a[i]%j == 0){
                if(mp[j] > 0  || (j != 1 && mp[a[i]/j] > 0)){
                    end = true;
                    break;
                }
            } 
        }
        if(!end) ans++;
    }
    cout << ans << endl;
    return 0;
}

Measured memory_bytes: 32672
/*
    Author: Nguyen Tan Bao
    Status:
    Idea:
*/
 
#include <bits/stdc++.h>
#define FI first
#define SE second
#define EPS 1e-9
#define ALL(a) a.begin(),a.end()
#define SZ(a) int((a).size())
#define MS(s, n) memset(s, n, sizeof(s))
#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define FORE(i,a,b) for (int i = (a); i >= (b); i--)
#define FORALL(it, a) for (__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)
//__builtin_ffs(x) return 1 + index of least significant 1-bit of x
//__builtin_clz(x) return number of leading zeros of x
//__builtin_ctz(x) return number of trailing zeros of x
 
using namespace std;
using ll = long long;
using ld = double;
typedef pair<int, int> II;
typedef pair<II, int> III;
typedef complex<ld> cd;
typedef vector<cd> vcd;
 
const ll MODBASE = 1000000007LL;
const int MAXN = 200010;
const int MAXM = 1000;
const int MAXK = 16;
const int MAXQ = 200010;

int a[MAXN], n;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    cin >> n;
    FOR(i,1,n) cin >> a[i];
    int Min = 1000000000, res = 0;
    FOR(i,1,n) {
        if (a[i] < Min) res++;
        Min = min(Min, a[i]);
    }
    cout << res;
    return 0;
}


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

int main(){
	int N; cin >> N;
	vector<int> button(N);
	for( int &k : button) cin >> k;
	
	int x = 1;
	for( int i = 1; i <= N; i++ ){
		x = button[x-1];
		if(x == 2){
			cout << i << endl;
			return 0;
		}
	}
	cout << -1 << endl;
}


Measured memory_bytes: 640
#include<stdio.h>

int main(void){

    long int N,M,ans;

    scanf("%ld %ld",&N,&M);

    if(N > M || M < N*2){
        ans = M/2;
    }else{
        ans = N;
        M -= N*2;
        ans += M/4;
    }

    printf("%ld",ans);
    return 0;
}


Measured memory_bytes: 128
/* BISMILLAHIR RAHMANIR RAHIM */
#include<bits/stdc++.h>
using namespace std;
#define ll        long long
#define ull       unsigned long long
#define si(x)     scanf("%d", &x)
#define sll(x)    scanf("%lld", &x)
#define ssll(x,y)    scanf("%lld %lld", &x ,&y)
#define sd(x)     scanf("%lf", &x)
#define l0(i,n)   for(ll i=0; i<n; i++)
#define MAX       100000
#define maxn 	  200002
#define pb 		  push_back
#define mk 		  make_pair
#define endl	  "\n"
#define INF 	  1000000000
#define MOD		  1000000007
#define vll(a)	  vector<ll>a
#define imie(...) "[" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "


int main ()
{
		ios::sync_with_stdio(0);
		cin.tie(0);
		//CODE TONOY
		string s,t;
		cin >> s >> t;
		ll cnt = 0;
		for (int i=0 ; i<(int)s.length() ; i++)
		{
			if(s[i]!=t[i])
			cnt++;
		}
		cout << cnt << endl;
		return 0;
}







Measured memory_bytes: 3768
n=int(input())
t=[int(i) for i in input().split()]
v=[int(i) for i in input().split()]
l=[]

for i in range(n):
    l+=[v[i]]*t[i]*2

l=[min(i,j) for i,j in zip([0]+l,l+[0])]

for i in range(1,len(l)):
    l[i]=min(l[i],l[i-1]+0.5)
for i in range(len(l)-1)[::-1]:
    l[i]=min(l[i],l[i+1]+0.5)

ans=0

for i in range(1,len(l)):
    ans+=0.25*(l[i]+l[i-1])

print(ans)

Measured memory_bytes: 4396
#include <iostream>
#include <vector>
#include <string>

using namespace std;

bool contain(vector<char> c, char key)
{
    if (c.size() > 0)
    {
        for (auto i : c)
        {
            if (i == key)
            {
                return true;
            }
        }
        return false;
    }
    else
    {
        return false;
    }
}

int main()
{
    string w = "";
    cin >> w;
    bool test = true;
    vector<char> tested;
    if (w.size() > 1)
    {
        for (int i = 0; i < w.size() - 1; i++)
        {

            if (!contain(tested, w[i]))
            {
                tested.push_back(w[i]);
                int num = 1;
                for (int a = i + 1; a < w.size(); a++)
                {
                    if (w[i] == w[a])
                    {
                        num += 1;
                    }
                }
                if (num % 2 != 0)
                {
                    test = false;
                    break;
                }
            }
        }
        if (test != false)
        {
            cout << "Yes" << endl;
        }
        else
        {
            cout << "No" << endl;
        }
    }
    else
    {
        cout << "No" << endl;
    }
}


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


class Program
{
    static void Main()
    {
        List<int> a = new List<int>();
        
        while (true)
        {
            string s = Console.ReadLine();
            if (s == "0") break;
            a.Add(int.Parse(s));
        }
        for (int i = 0; i < a.Count; i ++)
        {
            Console.WriteLine("Case {0}: {1}", i + 1, a[i]);
        }
    }
}


Measured memory_bytes: 15912
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main (){
    int l,r;scanf("%d %d",&l,&r);
    int ans=0;
    for(int i=l;i<=r;i++){

        if(i/10000==(i%10)&&(i/1000%10)==(i/10%10)) ans++;
    }
    cout<<ans<<endl;
    return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
#define fast ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);
#define mod 1000000007
#define PI 3.1415926535897932384626433
#define se second
#define fi first
#define pb push_back
#define T true
#define F false
#define endl "\n"
typedef char ch;
typedef bool boll;
typedef string st;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef set < string > sst;
typedef set < long long > sl;
typedef queue < long long > que;
typedef vector < long long > vec;
typedef map < long long, long long > mll;
typedef pair < long long, long long > pll;
typedef vector < pair < long long, long long > > vpl;
typedef pair < long long, unsigned long long > pul;

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

int main()
{
    fast;

    int n;
    cin >> n;
    int sum;
    int x=sum;
    for(int i=1;i<=n;i++){
        for (int j=1;j<=n;j++){
            for(int k=1;k<=n;k++){
                sum += gcd(i,gcd(j,k));
            }
        }
    }
    cout << sum - x;

}



Measured memory_bytes: 3616
import sys
sys.setrecursionlimit(10**7)
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()
INF = 10 ** 18
MOD = 10 ** 9 + 7

debug = True
debug = False

def dprint(*objects):
    if debug == True:
        print(*objects)

def solve():
    N = II()
    b_list = LI()

    a_list = [0 for i in range(N)]
    for i in range(N):
        # i桁目はi-1とiのminで決めればいい
        if i == 0:
            a_list[i] = b_list[i]
        elif i == N-1:
            a_list[i] = b_list[i-1]
        else:
            a_list[i] = min(b_list[i], b_list[i-1])

    print(sum(a_list))

solve()

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

int main () {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n, m;
  cin >> n >> m;
  vector<int> arr (n);
  for (int i = 0; i < n; i++) {
    cin >> arr[i];
  }
  sort (arr.begin(), arr.end());
  vector< pair<int, int> > q;
  for (int i = 0; i < m; i++) {
    int foo, bar;
    cin >> foo >> bar;
    q.emplace_back(bar, foo);
  }
  sort (q.rbegin(), q.rend());
  int cur = 0;
  for (int i = 0; i < m; i++) {
    int tempo = q[i].second;
    while (tempo > 0 && cur < n) {
      arr[cur] = max (arr[cur], q[i].first);
      --tempo;
      ++cur;
    }
  }
  cout << accumulate (arr.begin(), arr.end(), 0LL) << '\n';
  return 0;
}


Measured memory_bytes: 1784
#include <iostream>
#include <map>
#include <queue>
#include <cmath>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
#pragma warning (disable: 4996)

long long N, sum;
long long cnt[100];

int main() {
	cin >> N;
	for (int i = 1; i <= N; i++) {
		string S = to_string(i);
		cnt[(S[0] - '0') * 10 + (S[S.size() - 1] - '0')]++;
	}
	for (int i = 10; i < 100; i++) {
		for (int j = 10; j < 100; j++) {
			if ((i / 10) == (j % 10) && (i % 10) == (j / 10)) sum += cnt[i] * cnt[j];
		}
	}
	cout << sum << endl;
	return 0;
}

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

int main(){
  int a,b;
  cin>>a;
  cin>>b;
  if(a==1) a=14;
  if(b==1) b=14;
  if(a>b) cout<<"Alice"<<endl;
  if(a==b) cout<<"Draw"<<endl;
  if(a<b) cout<<"Bob"<<endl;
  return 0;
}

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


public class B
{
	public static void Main()	
	{
		string[] args = Console.ReadLine().Split(' ');
		int N = Int32.Parse(args[0]);
		int A = Int32.Parse(args[1]);
		int B = Int32.Parse(args[2]);

		int ans = 0;
		for(int i = 1; i <= N; i++)
		{
			int sum = digitsSum(i);
			if((A <= sum) && (sum <= B))
				ans += i;
		}

		Console.WriteLine(ans);
	}

	private static int digitsSum(int x)
	{
		int tmp = x;
		int ans = 0;
		while(tmp > 0)
		{
			ans += tmp % 10;
			tmp /= 10;
		}
		return ans;
	}
}





Measured memory_bytes: 11092
#include <bit>
#include <bitset>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <set>
#include <map>
#include <vector>
#include <math.h>
#include <stdlib.h>
#include <queue>
#include <stack>
#include <iomanip>

typedef long double ld;
typedef long long ll;

using namespace std;


/* TEMPLATE ENDS HERE */

#define MAXN (1 << 10)

int n;
int a[2][MAXN];

int main() {
	cout << fixed << setprecision(12);	
	cin >> n;
	for (int i = 0; i < 2; i++) {
		for (int j = 0; j < n; j++) {
			cin >> a[i][j];
		}
	}
	int ret = 0;
	for (int i = 0; i < n; i++) {
		int cur = 0;
		for (int j = 0; j <= i; j++) {
			cur += a[0][j];
		}
		for (int j = i; j < n; j++) {
			cur += a[1][j];
		}
		ret = max(cur, ret);
	}
	cout << ret << endl;
	return 0;
}


ll MOD = ((ll)1e9 + 7);

struct mod {
	ll x;

	mod(ll tx = 0) {
		x = tx;
		x %= MOD;
	}
	
	mod& operator=(const ll & tx) {
		x = tx % MOD;
		return *this;
	}
	
	mod& operator=(const mod & m2) {
		x = m2.x;
		return *this;
	}

	mod operator+(const mod& m2) const {
		return mod((x + m2.x) % MOD);
	}

	mod& operator+=(const mod& m2) {
		x += m2.x;
		x %= MOD;
		return *this;
	}

	mod operator-(const mod & m2) const {
		return mod((x - m2.x + MOD) % MOD);
	}

	mod& operator-=(const mod & m2) {
		x -= m2.x;
		x = (x + MOD) % MOD;
		return *this;
	}

	mod operator*(const mod & m2) const {
		return mod((x * m2.x) % MOD);
	}

	mod& operator*=(const mod & m2) {
		x *= m2.x;
		x %= MOD;
		return *this;
	}

	mod mypow(ll k) const {
		mod ret = 1;
		mod cur = x;
		while (k) {
			if (k & 1) {
				ret *= cur;
			}
			cur *= cur;
			k >>= 1;
		}
		return ret;
	}

	mod inv() const {
		return mypow(MOD - 2);
	}

	mod operator/(const mod & m2) const {
		return (*this) * m2.inv();
	}

	mod& operator/=(const mod & m2) {
		x *= m2.inv().x;
		x %= MOD;
		return *this;
	}

	bool operator<(const mod & m2) const {
		return x < m2.x;
	}
};

ostream &operator<<(ostream & os, const mod & m) {
	return os << m.x;
}



Measured memory_bytes: 3652
n = int(input())
arr = list(map(int,input().split()))

from collections import Counter
c = Counter(arr)
c = list(c.values())
c.sort()
s = n

sol = []
removed = 0
for k in range(1,n+1):
    rest = k - removed
    while c and c[-1] > s//rest:
        s -= c[-1]
        c.pop()
        rest -= 1
        removed += 1
    sol.append(s//rest)

print("\n".join(map(str,sol)))

Measured memory_bytes: 40360
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import static java.lang.Integer.parseInt;

/**
 * Symmetric Ternary Number
 */
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 w = parseInt(line);
			String base3 = "";

			while (w != 0) {
				int r = w % 3;
				if (r == 0) {
					base3 = "0" + base3;
					w /= 3;
				} else if (r == 1) {
					base3 = "+" + base3;
					w /= 3;
				} else if (r == 2) {
					base3 = "-" + base3;
					w /= 3;
					w++;
				}
			}

			System.out.println(base3);

		} // end while
	} // end main
}

Measured memory_bytes: 24280