akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cmath>
#include <string>
using namespace std;

int main()
{
    int n;
    int m = 0;
    int m_2 = 0;
    int max = 0;
    int max_2 = 0;
    cin >> n;
    
    for(int i = 0; i < n; i++){
      int tmp;
      cin >> tmp;
      if(tmp > max){
        max_2 = max;
        m_2 = m;
        max = tmp;
        m = i;
      }else if(tmp > max_2){
        max_2 = tmp;
        m_2 = i;
      }
    }

    for(int i = 0; i < n; i++){
      if(i != m){
        cout << max << endl;
      }else{
        cout << max_2 << endl;
      }
    }

    

    return 0;
}


Measured memory_bytes: 1664
package main

import "fmt"

func main() {
	var h, w int
	fmt.Scan(&h, &w)

	a := make([]string, h)
	for i := range a {
		fmt.Scan(&a[i])
	}

	lm := make(map[int]bool)
	cm := make(map[int]bool)
	for i := 0; i < h; i++ {
		for j := 0; j < w; j++ {
			if a[i][j] == '#' {
				lm[i] = true
				cm[j] = true
			}
		}
	}

	for i := range a {
		if _, ok := lm[i]; ok {
			for j := range a[i] {
				if _, ok := cm[j]; ok {
					fmt.Print(string(a[i][j]))
				}
			}
			fmt.Println()
		}
	}
}


Measured memory_bytes: 768
#include <bits/stdc++.h>
#define N 1005
#define INF 0x3f3f3f3f 
#define mod 1000000007
using namespace std;
typedef long long ll;
ll ans;
 
int main(){
    int n;
    cin >> n;
    ll arr[n];
    for(int i=0; i<n; i++) cin >> arr[i];
    ll prefix[n];
    prefix[0] = arr[0];
    for(int i=1; i<n; i++) prefix[i] = prefix[i-1] + arr[i];
    ll res = 0, cntr = 0;
    for(int i=0; i<n; i++){
        if(i%2){
            if(prefix[i] + cntr <= 0){
                res+=1-prefix[i]-cntr;
                cntr+=1-prefix[i]-cntr;
            }
        }else{
            if(prefix[i] + cntr >= 0){
                res+=prefix[i]+cntr+1;
                cntr-=prefix[i]+cntr+1;
            }
        }
    }
    ans = res;
    res = 0;
    cntr = 0;
    for(int i=0; i<n; i++){
        if(i%2 == 0){
            if(prefix[i] + cntr <= 0){
                res+=1-prefix[i]-cntr;
                cntr+=1-prefix[i]-cntr;
            }
        }else{
            if(prefix[i] + cntr >= 0){
                res+=prefix[i]+cntr+1;
                cntr-=prefix[i]+cntr+1;
            }
        }
    }
    ans = min(ans, res);
    cout << ans;
    return 0;
}


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


template<typename T>
vector<T> make_v(size_t a){return vector<T>(a);}

template<typename T,typename... Ts>
auto make_v(size_t a,Ts... ts){
  return vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...));
}

template<typename T,typename V>
typename enable_if<is_class<T>::value==0>::type
fill_v(T &t,const V &v){t=v;}

template<typename T,typename V>
typename enable_if<is_class<T>::value!=0>::type
fill_v(T &t,const V &v){
  for(auto &e:t) fill_v(e,v);
}

//INSERT ABOVE HERE
signed main(){
  Int n;
  cin>>n;
  auto a=make_v<Int>(n,n);  
  for(Int i=0;i<n;i++)
    for(Int j=0;j<n;j++)
      cin>>a[i][j];

  Int s=1<<n;
  vector<Int> sm(s,0);
  for(Int b=0;b<s;b++)
    for(Int i=0;i<n;i++)
      for(Int j=0;j<i;j++)
        if((b>>i)&1) if((b>>j)&1) sm[b]+=a[i][j];

  vector<Int> dp(s),vi(s,0);
  function<Int(Int)> dfs=
    [&](Int b){
      Int &res=dp[b];
      if(vi[b]) return res;
      vi[b]=1;
      res=sm[b];
      for(Int i=b;i;i=(i-1)&b){
        if(i==b) continue;
        chmax(res,dfs(i)+dfs(b^i));
      }                 
      return res;
    };

  cout<<dfs(s-1)<<endl;
  return 0;
}


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

namespace Algorithm
{
    class Program
    {
        static void Main(string[] args)
        {
            var l = Console.ReadLine().Split().Select(int.Parse).ToArray();
            int N = l[0], K = l[1];

            if (K == 0)
            {
                Console.WriteLine((long)N * N);
                return;
            }

            var total = 0L;
            for (var b = K + 1; b <= N; b++)
            {
                total += (long)(N / b) * (b - K);
                total += Math.Max(0, (N % b) - (K - 1));
            }

            Console.WriteLine(total);
        }
    }
}


Measured memory_bytes: 13396
/** 
 * Dont raise your voice, improve your argument.
 * --Desmond Tutu
 */

#include <bits/stdc++.h>
using namespace std;
typedef unsigned int uint;
typedef long long ll;

#define fori(n) for(ll i=0; i<(n); i++)
#define forn(i, n) for(ll i=0; i<(n); i++)
#define forn3(i, x, n) for(ll i=(x); i<(n); i++)

int main() {
cin.tie(nullptr);
std::ios::sync_with_stdio(false);
    int n, m;
    cin>>n>>m;
    vector<ll> l(m), r(m);
    ll maxL=0;
    ll minR=1000000000;
    fori(m) {
        cin>>l[i]>>r[i];
        maxL=max(maxL, l[i]);
        minR=min(minR, r[i]);
    }

    ll ans=max(0LL, minR-maxL+1);
    cout<<ans<<endl;

}



Measured memory_bytes: 1792
package main

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

func solve() {
	n := getInt()
	caps := getIntSlice(5)
	bottleNeck := min(caps...)
	group := (n + bottleNeck - 1) / bottleNeck

	ans := group + 4
	fmt.Fprintln(wr, ans)
}

func min(ns ...int) int {
	min := ns[0]
	for i := 1; i < len(ns); i++ {
		if min > ns[i] {
			min = ns[i]
		}
	}
	return min
}

// -----------------------------------------

const (
	inf = 1 << 60
	// mod = 1000000007
)

var (
	sc = bufio.NewScanner(os.Stdin)
	wr = bufio.NewWriter(os.Stdout)
)

func main() {
	// buf := 200001
	// sc.Buffer(make([]byte, buf), buf)
	sc.Split(bufio.ScanWords)
	solve()
	wr.Flush()
}

func getInt() int {
	sc.Scan()
	i, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return i
}

func getIntSlice(n int) []int {
	is := make([]int, n)
	for i := range is {
		is[i] = getInt()
	}
	return is
}

func getString() string {
	sc.Scan()
	s := sc.Text()
	return s
}

func getRunes() []rune {
	return []rune(getString())
}


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

int main() {
    int X, Y, Z;
    cin >> X >> Y >> Z;
    cout << Z << " " << X << " " << Y << endl;
}


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

#define watch(x) cerr << (#x) << ": " << (x) << endl
#define int long long

void nope() {
    cout << -1 << '\n';
    exit(0);
}

void output(int a, int b) {
    cout << a << " " << b << '\n';
}

void dfs(vector<vector<int>>& graph, int cur, int par, vector<int>& f, vector<bool>& seen, vector<bool>& done) {
    seen[cur] = true;

    for(int child : graph[cur]) {
        if(child != par) {
            if(!seen[child])
                dfs(graph, child, cur, f, seen, done);
            else if(!done[child]){
                output(cur, child);
                f[cur]++;
            }
        }
    }

    done[cur] = true;

    if(cur == 1) return;
    
    if(f[cur]%2) {
        output(cur, par);
    } else {
        output(par, cur);
        f[par]++;
    }
}

int32_t main() {

    int n, m; cin >> n >> m;

    vector<vector<int>> graph(n+1);
    for(int i = 0; i < m; ++i) {
        int a, b; cin >> a >> b;
        graph[a].push_back(b);
        graph[b].push_back(a);
    }
    
    if(m%2) nope();

    vector<int> f(n+1, 0);
    vector<bool> seen(n+1, false), done(n+1, false);
    dfs(graph, 1, 0, f, seen, done);
    
    return 0;
}


Measured memory_bytes: 18560
use std::io::prelude::*;

fn input<T>() -> T
where
    T: std::str::FromStr,
{
    let stdin = std::io::stdin();
    let token: String = stdin
        .lock()
        .bytes()
        .map(|c| c.unwrap() as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().unwrap()
}

fn main() {
    let n: usize = input();
    let mut a: Vec<usize> = (0..n).map(|_| input()).collect();
    a.sort();

    let mut m = std::collections::HashMap::new();
    for i in a {
        let e = m.entry(i).or_insert(0);
        *e += 1;
    }

    let mut ans = 0;
    for (i, cnt) in m {
        if cnt < i {
            ans += cnt;
        } else if cnt > i {
            ans += cnt - i;
        }
    }

    println!("{}", ans);
}


Measured memory_bytes: 12540
#include <bits/stdc++.h>
#include <string>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <numeric>
using namespace std;

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

int main(){
  int N,A;
  cin >> N >> A;
  int count = 0;
  N = N - (N / 500)*500;
  if(N <= A){
    cout << "Yes" << endl;
  }
  else{
    cout << "No" << endl;
  }
  
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
	
int main() {
  	map<int,int> g; const string ans[] = {"No","Yes"};
	ios_base::sync_with_stdio(0), cin.tie(0);
	for (int a, i = 0; i < 3; ++i)
		cin >> a, ++g[a];
	cout << ans[g.size()==2]; }
		

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
int a[200005];
int main(){
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	long long ans=0;
	for(int i=1;i<=n;i++){
		if(a[i]<a[i-1]){
			ans+=a[i-1]-a[i];
			a[i]=a[i-1];
		}
	}
	printf("%lld",ans);
	return 0;
}

Measured memory_bytes: 4604
#include <bits/stdc++.h>
const int INF = 1e9;
const int MOD = 1e9+7;
using LL = long long;
const LL LINF = 1e18;
const double EPS = 1e-10;
using namespace std;
class Edge{
public:
    int from,to,value;
    Edge(LL a,LL b,LL c){
        from = a;
        to = b;
        value = c;
    }
    Edge(LL a,LL b){
        from = a;
        to = b;
    }
};

int main(){
    int N,L;cin >> N >> L;
    int ans = 0;
    for(int i = 0;i < N;i++){
        ans += L + i;
    }
    int mi = 1e9;
    int t = 0;
    for(int i = 0;i < N;i++){
        if(mi > abs(L+i)){
            mi = abs(L+i);
            t = L+i;
        }
    }
    cout<<ans-t<<endl;
}


Measured memory_bytes: 256
import sys, math
from collections import defaultdict
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 1000000007
sys.setrecursionlimit(1000000)

N, D = rl()

print(math.ceil(N / (2*D+1)))


Measured memory_bytes: 65300
#include <stdio.h>
#include <stdlib.h>

int binarySearch(int,int *,int);

int main(){
  int i,n,m,*A,*B,count = 0;
  
  scanf("%d",&n);
  A = (int *)malloc(n * sizeof(int));
  for(i = 0;i < n;i++){
    scanf("%d",&A[i]);
  }
  scanf("%d",&m);
  B = (int *)malloc(m * sizeof(int));
  for(i = 0;i < m;i++){
    scanf("%d",&B[i]);
  }
  
  for(i = 0;i < m;i++) count += binarySearch(B[i],A,n);

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

  return 0;
}


int binarySearch(int b,int *a,int n){
  int left = 0,right = n,mid;
  while(left < right){
    mid = (left + right) / 2;
    if(a[mid] == b) return 1;
    else if(b < a[mid]) right = mid;
    else left = mid + 1;
  }
  return 0;
  
}



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

int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    rep(i, n) cin >> a[i];

    int ans = 0;
    rep(i,n){
        if (!bool(i & 1) && bool(a[i] & 1)) ans++;
    }
    cout << ans << endl;
}


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

int main(){
   
  char a,b;

  cin >> a >> b;
  if(a=='H' ){
    if(b=='H'){
      cout << 'H' << endl;
    }else{
      cout << 'D' << endl;
    }
  }else{
    if(b=='H'){
      cout << 'D' << endl;
    }else{
      cout << 'H' <<endl;
    }
  }

  
 
  return 0;

}


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

namespace ARC070
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var X = int.Parse(Console.ReadLine());
            var ans = Enumerable.Range(0, X).TakeWhile(i => i * (i + 1) / 2 < X).Count();
            Console.WriteLine(ans);
        }
    }
}

Measured memory_bytes: 13268
#include <stdio.h>
#include <stdlib.h>
int main(){
  int a[100]={};
  int n;
  int i;
  int approved=1;
  while(n<1||n>100){
    scanf("%d",&n);
  }
  for(i=0;i<n;i++){
    while(a[i]<1||a[i]>1000){
      scanf("%d",&a[i]);
    }
    if(a[i]%2==0 && a[i]%3!=0 && a[i]%5!=0){
      approved=0;
    }
  }
  if(approved==0){
    printf("DENIED");
  }
  else printf("APPROVED");
  return 0;
}


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

using lint = long long;
using pint = pair<int, int>;
using plint = pair<lint, lint>;

constexpr lint INF = 1'010'000'000'000'000'017LL;
constexpr lint MOD = 1'000'000'007LL;
constexpr double EPS = 1e-12;
constexpr double PI = 3.14159265358979323846;

#define FOR(i, start, end) for(lint i = (start); i < end; i++)
#define REP(i, n) FOR(i, 0, n)
#define ALL(v) v.begin(), v.end()

template<class T> inline void YES(T condition){ if(condition) cout << "YES" << endl; else cout << "NO" << endl; }
template<class T> inline void Yes(T condition){ if(condition) cout << "Yes" << endl; else cout << "No" << endl; }

lint mod(lint val, lint m){ lint res = val % m; if(res < 0) res += m; return res;}
lint modinv(lint a, lint m) { lint b = m, u = 1, v = 0; while (b) { lint t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v); } u %= m; if (u < 0) u += m; return u;}
lint modpow(lint a, lint n, lint mod) { lint res = 1; while (n > 0) { if (n & 1) res = res * a % mod; a = a * a % mod; n >>= 1;} return res;}
lint gcd(lint a, lint b){ if(a < b) swap(a, b); if(b == 0) return a; return gcd(b, a%b);}
lint lcm(lint a, lint b){ return a * b / gcd(a, b);}


//---------------------------------------------------------------

void Main()
{
    int N, a, b, ans;
    cin >> N;
    vector<int> P(N), Q(N), nums(N);

    REP(i, N){
        nums[i] = i+1;
        cin >> P[i];
    }
    REP(i, N){
        cin >> Q[i];
    }

    a = -1;
    b = -1;
    int i = 0;
    do {
        i++;
        if(P == nums){
            a = i;
        }
        if(Q == nums){
            b = i;
        }
        if(a != -1 && b != -1){
            break;
        }
    } while(next_permutation(nums.begin(), nums.end()));

    ans = abs(a-b);
    cout << ans << endl;
}

//---------------------------------------------------------------
int main()
{
    cout << fixed << setprecision(15);
    Main();
    return 0;
}

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

template<typename T>
struct BIT {
    int n;
    vector<T> dat;

    BIT(int n=0){
        initialize(n);
    }

    void initialize(int nin){
        n = nin;
        dat.assign(n, 0);
    }

    T sum(int i){
        T s = 0;
        while(i >= 0){
            s += dat[i];
            i = (i & (i+1)) - 1;
        }
        return s;
    }

    T sum_between(int i, int j){
        return sum(j) - sum(i-1);
    }

    void plus(int i, T x){
        while(i < n){
            dat[i] += x;
            i |= i+1;
        }
    }

    // a[0]+...+a[ret] >= x
    int lower_bound(T x){
        if(x < 0) return -1;
        int ret = -1;
        int k = 1;
        while(2*k <= n) k <<= 1;
        for( ;k>0; k>>=1){
            if(ret+k < n && dat[ret+k] < x){
                x -= dat[ret+k];
                ret += k;
            }
        }
        return ret + 1;
    }
};

int main(){
    int N, Q;
    cin >> N >> Q;
    vector<int> C(N);
    for(int i=0; i<N; i++) cin >> C[i], C[i]--;
    vector<vector<pair<int, int>>> R2LQ(N);
    for(int i=0; i<Q; i++){
        int l, r;
        cin >> l >> r;
        R2LQ[r-1].emplace_back(l-1, i);
    }

    vector<int> last(N, -1);
    vector<int> ans(Q);

    BIT<int> bit(N);
    for(int r=0; r<N; r++){
        if(last[C[r]] >= 0) bit.plus(last[C[r]], -1);
        last[C[r]] = r;
        bit.plus(last[C[r]], 1);
        for(auto& [l, q] : R2LQ[r]) ans[q] = bit.sum_between(l, r);
    }
    for(int a : ans) cout << a << endl;
    return 0;
}


Measured memory_bytes: 33256
import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		Scanner stdIn = new Scanner(System.in);
		
		/*<考察>
		 * dream を a
		 * dreamer を b
		 * erase を c
		 * eraser を d とおく。
		 * 
		 * s と a,b,c,dを何度も比較する 4 *10^5で十分間に合う
		 * 比較するときに文字列がずれるためできないのでは。。。？
		 * 前から比較するとdream,dreamerのどっちで切っていいか分からなくなる、このような関係をprefixという。
		 * 
		 * dream,dreamer,erase,eraser以外の異物が入っているときに絶対不可能であるため、
		 * 変な文字が入ってないか確認するか？
		 * 		
		*/
		
		/*String s = stdIn.next();
		
		if(!(s.contains("dream") || s.contains("dreamer") || s.contains("erase") || s.contains("eraser")) ) {
			System.out.println("NO");
		}else {
			System.out.println("YES");
		}
		*/
		
//		String[] divide = new String[] {"dream","dreamer","erase","eraser"};
		StringBuilder[] sb = new StringBuilder[] {new StringBuilder("dream"),new StringBuilder("dreamer"),new StringBuilder("erase"),new StringBuilder("eraser")};
		
		for(int i = 0; i < sb.length; i++) {
			sb[i] = sb[i].reverse();
		}
		
		String s2 = stdIn.next();
		
		StringBuilder s1 = new StringBuilder(s2);
		String s = s1.reverse().toString();
		
		
		boolean flag = true;
		
		
	Outer:	for(int i = 0; i < s.length();) {
			boolean flag2 = false; //4個の文字列のうちあてはまるものはあるか
			
			
			
			if(s.length() - i == 5) {
				if(s.substring(i,s.length()).equals("maerd") || s.substring(i,s.length()).equals("esare")) {
					flag2 = true;
					break Outer;
				}
			}
			if(s.length() - i == 6) {
				if(s.substring(i,s.length()).equals("resare")){
					flag2 = true;
					break Outer;
				}
			}
		
			
			for(int j = 0; j < 4; j++) {
				String d = sb[j].toString();
				
	
				if(s.substring(i,i+d.length()).equals(d)) { //あてはまった
					flag2 = true;
					i += d.length();
					continue Outer;
				}
			}
			
			
			
			
			
			if(!flag2) {
				flag = false;
				break;
			}
		}
		
		if(flag) {
			System.out.println("YES");
		}else {
			System.out.println("NO");
		}
		
	}

}


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

int main()
{
  long n; cin>>n;
  
  int cnt = 0;
  bool ans = false;
  for(int i=0; i<n; i++)
  {
    int a, b; cin>>a>>b;
    if(a == b)
      cnt++;
    else
      cnt = 0;
    if(cnt == 3)
      ans = true;
  }
  cout<<(ans ? "Yes": "No");
}

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

#define SIZE 300005
#define MOD 1000000007LL
#define INF INT_MAX / 3
#define LLINF 1LL << 60
#define REP(i,n) for(int i=0;i<n;i++)
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define DOWN(i,b,a) for(int i=b;i>=a;i--)
#define SET(a,c) memset(a,c,sizeof a)
#define FORALL(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define FOREACH(i,c) for(auto (i) : (c))
#define BIT(i,j) ((i)>>(j))&1
#define ALL(o) (o).begin(), (o).end()
#define ERASE(o) (o).erase(unique((o).begin(),(o).end()), (o).end())
#define SQ(x) ((x)*(x))
using namespace std;
typedef long long ll;
typedef valarray<int> Array;
typedef pair<ll,ll> Pll;
typedef pair<int, int> Pii;
typedef pair<double, double> Pdd;
template<typename T> inline void priv(vector<T>a){REP(i,a.size()){cout<<a[i];if(i==a.size()-1)cout<<endl;else cout<<" ";}}
int gcd(int a,int b){int c=max(a,b);int d=min(a,b);return c==0||d==0?c:gcd(c%d,d);}
int lcm(int a,int b){return a==0||b==0?0:a*b/gcd(a,b);}

double area(double x1, double y1, double x2, double y2, double x3, double y3)
{
  double a = x2 - x1;
  double b = y2 - y1;
  double c = x3 - x1;
  double d = y3 - y1;
  return fabs(0.5*(a*d-b*c));
}

int main()
{
  cin.tie(0);
  ios::sync_with_stdio(false);
  double x1, y1, x2, y2, x3, y3, x4, y4;
  while(~scanf("%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf",&x1,&y1,&x2,&y2,&x3,&y3,&x4,&y4))
  {
    double a1 = area(x1,y1,x2,y2,x3,y3);
    double a2 = area(x1,y1,x3,y3,x4,y4);
    double a3 = area(x1,y1,x2,y2,x4,y4);
    double a4 = area(x2,y2,x3,y3,x4,y4);
    printf("%s\n",fabs((a1+a2)-(a3+a4))<10e-8?"YES":"NO");
  }
  return 0;
}

Measured memory_bytes: 3140
flag=[0 for i in range(64)]

def Test(flag,i):
    print(flag[i])

def Set(flag,m):
    for i in m:
        flag[i]=1
    return flag

def Clear(flag,m):
    for i in m:
        flag[i]=0
    return flag

def Flip(flag,m):
    for i in m:
        if flag[i]==0:
            flag[i]=1
        else:
            flag[i]=0
    return flag

def All(flag,m):
    judge=[flag[i] for i in m]
    if all(judge)==True:
        print(1)
    else:
        print(0)

def Any(flag,m):
    judge=[flag[i] for i in m]
    if any(judge)==True:
        print(1)
    else:
        print(0)

def none(flag,m):
    judge=[flag[i] for i in m]
    if not any(judge)==True:
        print(1)
    else:
        print(0)

def Count(flag,m):
    judge=[flag[i] for i in m]
    print(judge.count(1))

def Val(flag,m):
    a=0
    for i in m:
        a+=flag[i]*2**i
    print(a)

n=int(input())
mask=[]
for i in range(n):
    m=list(map(int,input().split()))
    mask.append(m[1:])

q=int(input())
for i in range(q):
    query=list(map(int,input().split()))
    if query[0]==0:
        Test(flag,query[1])
    elif query[0]==1:
        flag=Set(flag,mask[query[1]])
    elif query[0]==2:
        flag=Clear(flag,mask[query[1]])
    elif query[0]==3:
        flag=Flip(flag,mask[query[1]])
    elif query[0]==4:
        All(flag,mask[query[1]])
    elif query[0]==5:
        Any(flag,mask[query[1]])
    elif query[0]==6:
        none(flag,mask[query[1]])
    elif query[0]==7:
        Count(flag,mask[query[1]])
    else:
        Val(flag,mask[query[1]])
    



Measured memory_bytes: 5648
#include<iostream>
#include<string>
#include<cmath>
#include<cstdlib>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
#include<queue>

using namespace std;

string s;
int n;
string ans;

char notchar(char now){
  if(now == 'S') return 'W';
  else return 'S';
}

char next(char prepre,char pre,char now){
  if(pre == 'S'){
    if(now == 'o') return prepre;
    else return notchar(prepre);
  } else {
    if(now == 'o') return notchar(prepre);
    else return prepre;
  }
}

bool check(string ans){
  bool prev;
  if(ans[n-1] == 'S'){
    if(s[n-1] == 'o'){
      prev = (ans[0] == ans[n-2]);
    } else {
      prev = (ans[0] != ans[n-2]);
    }
  } else {
    if(s[n-1] == 'o'){
      prev = (ans[0] != ans[n-2]);
    } else {
      prev = (ans[0] == ans[n-2]);
    }
  }

  bool now;
  if(ans[0] == 'S'){
    if(s[0] == 'o'){
      now = (ans[1] == ans[n-1]);
    } else {
      now = (ans[1] != ans[n-1]);
    }
  } else {
    if(s[0] == 'o'){
      now = (ans[1] != ans[n-1]);
    } else {
      now = (ans[1] == ans[n-1]);
    }
  }

  return now & prev;

}

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

  ans = "SS";
  for(int i=1;i<n-1;i++){
    ans += next(ans[i-1],ans[i],s[i]);
  }
  if(check(ans)){
    cout<<ans<<endl;
    return 0;
  }

  ans = "SW";
  for(int i=1;i<n-1;i++){
    ans += next(ans[i-1],ans[i],s[i]);
  }
  if(check(ans)){
    cout<<ans<<endl;
    return 0;
  }

  ans = "WS";
  for(int i=1;i<n-1;i++){
    ans += next(ans[i-1],ans[i],s[i]);
  }
  if(check(ans)){
    cout<<ans<<endl;
    return 0;
  }

  ans = "WW";
  for(int i=1;i<n-1;i++){
    ans += next(ans[i-1],ans[i],s[i]);
  }
  if(check(ans)){
    cout<<ans<<endl;
    return 0;
  }

  cout<<"-1"<<endl;
  return 0;
}


Measured memory_bytes: 640
#include <iostream>
#include <list>
#include <vector>

#define rep(i, n) for(int i = 0; i < n; i++)
#define range(min, x, max) ((min <= x) && (x <= max))

using namespace std;

int main(void)
{
    int n = 0; cin >> n;

    list<double> ls;

    double tmp = 0;

    rep(i, n) {
        cin >> tmp;
        ls.push_front(tmp);
    }

    ls.sort();

    while(ls.size() != 1) {
        tmp = ls.front(); ls.pop_front();
        tmp+= ls.front(); ls.pop_front();
        ls.push_front(tmp / 2);
    }

    if(range(3.4, ls.front(), 3.6)) {
        cout << 3.5 << endl;
    } else if(range(374, ls.front(), 376)) {
        cout << 375 << endl;
    } else if(range(137, ls.front(), 139)) {
        cout << 138 << endl;
    } else {
        cout << ls.front() << endl;
    }

    return 0;
}


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

#define pb(n) push_back(n)
#define fi first
#define se second
#define all(r) begin(r),end(r)
#define vmax(ary) *max_element(all(ary))
#define vmin(ary) *min_element(all(ary))
#define debug(x) cout<<#x<<": "<<x<<endl
#define fcout(n) cout<<fixed<<setprecision((n))
#define scout(n) cout<<setw(n)
#define vary(type,name,size,init) vector< type> name(size,init)
#define vvl(v,w,h,init) vector<vector<ll>> v(w,vector<ll>(h,init))
#define mp(a,b) make_pair(a,b)

#define rep(i,n) for(int i = 0; i < (int)(n);++i)
#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)
#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)
#define repa(n,array) for(auto &n :(array))

using ll = long long;
using pii = pair<int,int> ;
using pll = pair<ll,ll> ;

const int mod = 1000000007;
constexpr ll inf = ((1<<30)-1)*2+1 ;
constexpr double PI = acos(-1.0) ;
double eps = 1e-10 ;
const int dy[] = {-1,0,1,0,1,-1,1,-1};
const int dx[] = {0,-1,0,1,1,-1,-1,1};

inline bool value(int x,int y,int w,int h){
  return (x >= 0 && x < w && y >= 0 && y < h);
}

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  ll n;
  while(cin >> n && n){
    vector<ll> v(n);
    ll sum = 0,ans = inf;
    rep(i,n){
      cin >> v[i];
      sum += v[i];
    }
    sort(all(v));
    rep(i,1 << n){
      ll a = 0;
      rep(j,n){
        if(i & (1 << j)){
          a += v[j];
        }
      }
      ll b = sum - a;
      ans = min(ans,abs(a - b));
    }
    cout << ans << endl;
  }
  return 0;
}

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

#define printl(s) cout << s << endl;
#define print(s) cout << s << endl; return 0;
#define printFix(n,i) cout << fixed << setprecision(i) << n << endl; return 0;
#define yes cout << "Yes" << endl; return 0;
#define no cout << "No" << endl; return 0;
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define rep2(i,n) for (int i = 1; i < (n)+1; ++i)
#define bitrep(i,n) for (int i = 0; i < (1<<(n));i++)
#define isOne(bit,i) (bit & (1 << i))
using ll = long long;
using pii = pair<int, int>;

const ll modseed = pow(10,9) + 7;
const int INF = 100'000'000;

template <typename T>
vector<T> getValues(ll num){
    vector<T> values(num);
    for(ll i=0;i<num;i++){
        cin >> values.at(i);
    }
    return values;
}

string S;
int N,cnt;

double calcDist(pii p1, pii p2){
  double x = (p1.first - p2.first) * (p1.first - p2.first);
  double y = (p1.second - p2.second) * (p1.second - p2.second);
  return sqrt(x+y);
}

int main(){
  cin >> N;
  vector<vector<double>> dists(N,vector<double>(N));
  vector<pii> poss(N);
  rep(i,N){
    int X, Y;
    cin >> X >> Y;
    poss.at(i) = pii(X,Y);
  }
  rep(i,N){
    rep(j,N){
      dists.at(i).at(j) = calcDist(poss.at(i),poss.at(j));
    }
  }
  vector<int> cases(N);
  rep(i,N) cases.at(i) = i;
  double total = 0;
  do{
    for(int i=0;i<N-1;i++){
      total += dists.at(cases.at(i)).at(cases.at(i+1));
    }
  }while(next_permutation(cases.begin(),cases.end()));
  double divT = 1;
  for(int i=2;i<=N;i++){
    divT *= i;
  }
  double res = total / divT;
  printFix(res,10);

}


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

using namespace std;

int main()
{
    long long int m,n,ans=0;
    cin >> m >> n;
    if(n>=2*m)
    {
        ans+=m;
        n-=2*m;
        m=0;
    }
    else
    {
        ans+=n/2;
        n=0;
    }
    if(n!=0)
    {
        ans+=n/4;
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 256
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

const (
	BUFSIZE   = 10000000
	MOD       = 1000000007
	INF_INT   = math.MaxInt32
	INF_INT64 = math.MaxInt64
)

var rdr *bufio.Reader

func main() {
	rdr = bufio.NewReaderSize(os.Stdin, BUFSIZE)
	solve()
}

func solve() {
	X := readint()
	if X >= 30 {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

func readline() string {
	buf := make([]byte, 0, 16)
	for {
		l, p, e := rdr.ReadLine()
		if e != nil {
			fmt.Println(e.Error())
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}

func readIntSlice(size int) []int {
	slice := make([]int, size)
	lines := strings.Split(readline(), " ")
	for i, v := range lines {
		slice[i] = s2i(v)
	}
	return slice
}

func readInt64Slice(size int) []int64 {
	slice := make([]int64, size)
	lines := strings.Split(readline(), " ")
	for i, v := range lines {
		slice[i] = s2i64(v)
	}
	return slice
}

func readint() int {
	return s2i(readline())
}

func readint64() int64 {
	return s2i64(readline())
}

// For int64
func b2i64(b bool) int64 {
	if b {
		return 1
	}
	return 0
}

func abs64(v int64) int64 {
	if v < 0 {
		return -v
	}
	return v
}

func min64(values ...int64) int64 {
	ret := int64(INF_INT64)
	for _, v := range values {
		if ret > v {
			ret = v
		}
	}
	return ret
}

func max64(values ...int64) int64 {
	ret := -int64(INF_INT64)
	for _, v := range values {
		if ret < v {
			ret = v
		}
	}
	return ret
}

func s2i64(s string) int64 {
	v, ok := strconv.ParseInt(s, 10, 64)
	if ok != nil {
		panic("Faild : " + s + " can't convert to int64")
	}
	return v
}

// For int
func b2i(b bool) int {
	if b {
		return 1
	}
	return 0
}

func abs(v int) int {
	if v < 0 {
		return -v
	}
	return v
}

func min(values ...int) int {
	ret := INF_INT
	for _, v := range values {
		if ret > v {
			ret = v
		}
	}
	return ret
}

func max(values ...int) int {
	ret := -INF_INT
	for _, v := range values {
		if ret < v {
			ret = v
		}
	}
	return ret
}

func s2i(s string) int {
	v, ok := strconv.Atoi(s)
	if ok != nil {
		panic("Faild : " + s + " can't convert to int")
	}
	return v
}

func lcm(v1, v2 int) int {
	if v1 > v2 {
		v1, v2 = v2, v1
	}
	for v1 != 0 {
		v1, v2 = v2%v1, v1
	}
	return v2
}

func gcd(v1, v2 int) int {
	return v1 * v2 / lcm(v1, v2)
}

func bit(size int) [][]bool {
	bSize := int(math.Pow(2, float64(size)))
	b := make([][]bool, bSize)
	for i := 0; i < bSize; i++ {
		b[i] = make([]bool, size)
		for j := 0; j < size; j++ {
			if i>>j&1 == 1 {
				b[i][j] = true
			} else {
				b[i][j] = false
			}
		}
	}
	return b
}

/* ------------------------------------------------ */
/* Data stracture                                   */
/* ------------------------------------------------ */
type IntHeap []int

func (h *IntHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }


Measured memory_bytes: 2216
#include <cstdio>
#include <algorithm>
using namespace std;

typedef long long LL;

const int N = 4010;
const LL mod = 1e9 + 7;

int n, m, k;
LL f[N][N], sum[N];

int main()
{
	scanf("%d %d %d", &n, &m, &k);
	LL ans = 0;
	f[0][0] = 1;
	for (int i = 1; i <= (n + m - 1) / (k - 1); ++ i)
	{
		for (int j = 1; j <= n + 1; ++ j)
			sum[j] = (sum[j - 1] + f[i - 1][j - 1]) % mod;
		for (int j = 0; j <= n; ++ j)
			f[i][j] = (sum[j + 1] - sum[max(j - k + 1, 0)] + mod) % mod;
		for (int j = 1; j <= n; ++ j)
			if (j % (k - 1) == n % (k - 1) && (k - 1 - j % (k - 1)) % (k - 1) == (m - 1) % (k - 1) && (k - 1) * i - j <= m - 1)
				(ans += f[i][j] - f[i - 1][j] + mod) %= mod;
	}
	printf("%lld\n", ans);
}

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

#define  int        long long int
 #define    sp(x)                 setprecision(x)
#define    bp(x)           __builtin_popcount(x)
 #define  ld         long double
 #define  f(i,j,n)            for(int i = j; i <= n; i++)
#define  r(i,n,j)       for(int i = n; i >= j; i--)
 #define  all(container)       container.begin() , container.end()
#define  sz(container)   (int)container.size()
 #define  ff             first
#define  ss             second
 #define  pii      pair <int , int>
#define  sp(x)       setprecision(x)
 #define  endl    "\n"
#define  mod  1000000007
 #define  pb    push_back
#define  mp    make_pair
 #define  T     int ttt; cin >> ttt; while(ttt--)
#define fast ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL);

int power(int x, int y, int p)  
{  
    int res = 1;    
    x = x % p; 
    if (x == 0) return 0; 
    while (y > 0)  
    {     
        if (y & 1)  
            res = (res*x) % p;  
        y = y>>1; 
        x = (x*x) % p;  
    }  
    return res; 
}
int fac[500005],inv[500005];
int32_t main()
{
    fast
    int n,m,ans=0;
    fac[0]=1;
    n=500002;
    f(i,1,n)
        fac[i]=(fac[i-1]*i)%mod;
    f(i,0,n)
        inv[i]=power(fac[i],mod-2,mod);
    cin>>n>>m;
    ans=(1LL*fac[m]*inv[m-n])%mod;
    ans=(ans*ans)%mod;
    f(i,1,n)
    {
        int temp=(1LL*fac[m]*inv[i])%mod;
        temp=(1LL*temp*inv[m-i])%mod;

        temp=(1LL*temp*fac[n])%mod;
        temp=(1LL*temp*inv[n-i])%mod;
        //temp=(1LL*temp*inv[i])%mod;

        int tt=(1LL*fac[m-i]*inv[m-n])%mod;
        //tt=(1LL*tt*inv[n-i])%mod;
        tt=(1LL*tt*tt)%mod;
        temp=(1LL*tt*temp)%mod;
        if(i%2)
            ans=(ans-temp+ mod+mod)%mod;
        else
            ans=(ans+temp)%mod;
    }
    cout<<ans;
}

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

#define REP(i,num) for(int i=0;i<(num);++i)
#define LOOP(i) while(i--)
#define ALL(c) c.begin(),c.end()
#define PRINTALL(c) for(auto pitr=c.begin();pitr!=c.end();++pitr){cout<<*pitr;if(next(pitr,1)!=c.end())cout<<' ';}cout<<endl;
#define PAIRCOMP(c,comp) [](const pair<ll,ll>& lhs,const pair<ll,ll>& rhs){return lhs.c comp rhs.c;}

using namespace std;
using ll = long long;

constexpr ll atcoder_mod = 1e9+7;

template<typename T=int>
T in(){T x; cin >> x; return (x);}
template<typename T=int,typename C=vector<T>>
C vecin(int N){C x(N);REP(i,N){x[i]=in<T>();}return move(x);}

void vout(){cout << endl;}
template<typename Head,typename... Tail>
void vout(Head&& h,Tail&&... t){cout << ' ' << h;vout(forward<Tail>(t)...);}
void out(){cout << endl;}
template<typename Head,typename... Tail>
void out(Head&& h,Tail&&... t){cout << h;vout(forward<Tail>(t)...);}

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout<<fixed<<setprecision(10);

	int N=in();
	map<int,int> C;
	REP(i,N){
		C[in()]++;
	}
	
	int sum=0;
	for(auto& x:C){
		if(x.second%2) sum++;
	}
	out(sum);
	return 0;
}


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

using namespace std;

/*-------------------------------*/
#define FOR(i, a, b) for(int i = (a); i < (b); i++)
#define RFOR(i, a, b) for(int i = (b) - 1; i >= (a); i--)
#define REP(i, n) for(int i = 0; i < (n); i++)
#define rep(i, n) for(int i = 0; i < (n); i++)
#define RREP(i, n) for(int i = (n) - 1; i >= 0; i--)
#define rrep(i, n) for(int i = (n) - 1; i >= 0; i--)
#define all(i) (i).begin(),(i).end()
#define rall(i) (i).begin(),(i).end(),greater<int>()
#define PB push_back
#define pb push_back
#define mp make_pair
#define FI first
#define SE second


typedef long long ll;
typedef pair<int, int> pint;
typedef vector<int> vi;
typedef vector<vector<int> > vii;
typedef vector<long long> llv;
typedef vector<pint> vpint;
/*-------------------------------*/

int main(void)
{
  int n;
  int a[108];

  while (true){
    cin >> n;
    if (n == 0) break;

    int cnt = 0;
    rep(i, n) cin >> a[i];

    rep(i, n){
      rep(j, n - 1){
        if (a[j] > a[j + 1]){
          swap(a[j], a[j + 1]);
          cnt++;
        }
      }
    }
    cout << cnt << endl;
  }

  return 0;
}

Measured memory_bytes: 2996
#include <bits/stdc++.h>
#define i_love_u_Phuong ios_base::sync_with_stdio(0); cin.tie(0);

using ll = long long;
using namespace std;
typedef pair<int,int> pii;
const int MAXN = 2e5 + 5;
vector<vector<int> >  g;
int d[MAXN];

void bfs(int x)
{
    queue<int> q;
    memset(d,0,sizeof(d));
    q.push(x);
    d[x]=0;
    bitset<MAXN> f;
    f.reset();
    while (!q.empty())
    {
        int u = q.front();
        q.pop();
        if (f[u]==1) continue;
        if (d[u]==2) continue;
        f[u]=1;
        for(int i=0; i<g[u].size(); ++i)
        {
            int v=g[u][i];
            if (!f[v])
            {
                d[v]=max(d[v],d[u]+1);
                q.push(v);
            }
        }
    }
}


int main()
{
#ifndef RICARDO
    //freopen("input.txt", "r", stdin);
#endif // ONLINE_JUDGE
    i_love_u_Phuong;
    int n,m;
    cin >> n >> m;
    g = vector<vector<int>> (n+1);
    for(int i=0; i<m; ++i)
    {
        int u,v;
        cin >> u >> v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    bfs(1);
    if (d[n]==2) cout << "POSSIBLE"; else cout << "IMPOSSIBLE";
    return 0;
}



Measured memory_bytes: 13168
import java.util.*
 
fun main(args: Array<String>) {
 
  val sc = Scanner(System.`in`)
  val numOfMonster = sc.nextInt()
  val numOfSpecialAttack = sc.nextInt()
  val arrayOfMonsterHP = ArrayList<Long>()
  (1..numOfMonster).forEach {
    val monsterHP = sc.nextInt()
    arrayOfMonsterHP.add(monsterHP.toLong())
  }
  
  if(numOfMonster <= numOfSpecialAttack) {
    println(0.toString())
    return
  }
  
  val arrayOfMonstersDescending = arrayOfMonsterHP.sortedDescending()
  val droped = arrayOfMonstersDescending.drop(numOfSpecialAttack)
  
  
  val reduced = droped.reduce { acc, value ->
     acc + value                            
  }
  
  println("$reduced")
}

Measured memory_bytes: 79784
# encoding: utf-8
N = int(input())

cnt = 0
primes = (3, 5, 7, 11, 13, 17) # if N_i-1 * N_i > 200: break

# a = 8
for prime in primes: cnt += int((prime ** 7 <= N))
               
# a = 4, b = 2
for prime_a in primes:
    M_a = prime_a ** 3
    if M_a > N: break
    for prime_b in filter(lambda x: x != prime_a, primes):
        M_b = M_a * (prime_b ** 1)
        if M_b > N: break
        else: cnt += 1
        
# a = b = c = 2
for prime_a in primes:
    M_a = prime_a ** 1
    if M_a > N: break
    for prime_b in filter(lambda x: x > prime_a, primes):
        M_b = M_a * (prime_b ** 1)
        if M_b > N: break
        for prime_c in filter(lambda x: x > prime_b, primes):
            M_c = M_b * (prime_c ** 1)
            if M_c > N: break
            else: cnt += 1

print(cnt)


Measured memory_bytes: 3064
#include <stdio.h>
#include <stdlib.h>

int main()
{
  int n;
  int i;
  int ans = 0;
  
  scanf("%d", &n);

  int a[n];
  int b[n];
  int c[n-1];

  for(i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    a[i] = a[i] - 1;
  }

  for(i = 0; i < n; i++) {
    scanf("%d", &b[i]);
  }

  for(i = 0; i < n-1; i++) {
    scanf("%d", &c[i]);
  }

  for(i = 0; i < n; i++) {
    ans += b[a[i]];
    if(i != 0) {
      if((a[i] - a[i-1] == 1)) {
	ans += c[a[i-1]];
      }
    }
  }

  printf("%d\n", ans);
  
  return(0);
}

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

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

  vector<int> cnt(2, 0);

  for (int i = 0; i < s.size(); i++) {
    cnt[s[i] - '0']++;
  }
  cout << min(cnt[0], cnt[1]) * 2 << endl;
  return 0;
}

Measured memory_bytes: 3232
ii=lambda:map(int,raw_input().split())
n=int(raw_input())
x=ii()
m,k=ii()
a=ii()
y=[x[i+1]-x[i] for i in range(n-1)]
a=[a[i]-2 for i in range(m)]
p=[i for i in range(n-1)]
for i in a:
    p[i],p[i+1]=p[i+1],p[i]
bit=list(reversed(map(int,list(bin(k)[2:]))))
q=[[] for i in range(len(bit))]
ans=[i for i in range(n)]
for i in range(len(bit)):
    if i==0: q[0]=[p[j] for j in range(n-1)]
    else: q[i]=[q[i-1][q[i-1][j]] for j in range(n-1)]
    if bit[i]:ans=[q[i][ans[j]] for j in range(n-1)]
w=x[0]
print w
for i in range(n-1):
    w+=y[ans[i]]
    print w

Measured memory_bytes: 100544
#include <iostream>
#include <algorithm>
#include <vector>
#include <cassert>

using namespace std;

#define reep(i,a,b) for(int i=(a);i<(b);i++)
#define rep(i,n) reep((i),0,(n))
#define F first
#define S second
#define mkp make_pair
#define PB push_back
#define ALL(v) v.begin(),v.end()
#define maxs(a,b) (a=max(a,b))
#define mins(a,b) (a=min(a,b))


typedef long long ll;
typedef vector<int> vint;
typedef vector<vector<int>> vvint;
typedef pair<int,int> pii;
int n;

vector<vector<pii>> vv;
vector<pii> path;
vint used;
int dfs(int x,int pre){
	for(pii y:vv[x]){
		if(y.F==pre) continue;
		dfs(y.F,x);
		maxs(path[x],pii(path[y.F].F+y.S,path[y.F].S));
	}
	return path[x].F;
}


void mainmain(){
	vv=vector<vector<pii>>(n);
	vint _a(n-1),_b(n-1);
	path=vector<pii>(n,pii(0,-1));
	rep(i,n) path[i]=pii(0,i);
	// cout<<"n = "<<n<<endl;
	int ss=0;
	rep(i,n-1) cin>>_a[i];
	rep(i,n-1) cin>>_b[i];
	rep(i,n-1){
		ss+=_b[i];
		_a[i]--;
		vv[_a[i]].PB(pii(i+1,_b[i]));
		vv[i+1].PB(pii(_a[i],_b[i]));
		// cout<<i+1<<" "<<_a[i]<<endl;
	}
	vector<vector<pii>> ww(n);
	rep(i,n-1){
		if(vv[i].size()==1) continue;
		rep(j,vv[i].size()){
			if(vv[vv[i][j].F].size()==1) continue;
			ww[i].PB(vv[i][j]);
			// cout<<i<<" "<<vv[i][j].F<<endl;
		}
	}
	int tt = 0;
	rep(i,n){
		if(vv[i].size()==1){
			tt+=vv[i][0].S;
		}
	}
	vv=ww;
	int p=-1;
	rep(i,n){
		if(vv[i].size()){
			dfs(i,-1);
			p=path[i].S;
			break;
		}
	}
	rep(i,n) path[i]=pii(0,i);
	if(p>=0) dfs(p,-1);
	// if(p>=0) cout<<n<<" "<<ss<<" "<<p<<" "<<path[p].S<<" "<<path[p].F<<" "<<tt<<endl;
	if(p>=0) cout<<ss*3-path[p].F-2*tt<<endl;
	else cout<<ss*3-2*tt<<endl;
}


int main(){
	while(cin>>n,n){
		mainmain();
	}
}

Measured memory_bytes: 3176
import sys
input = sys.stdin.readline
from collections import deque

n = int(input())
P = [-1]*n
C = [[] for i in range(n)]
D = [[] for i in range(n)]
T = [[] for i in range(n)]

for i in range(n):
  s = [int(i) for i in input().split()]
  id = s[0]
  k = s[1]
  if k >= 1:
    c = s[2:]
    C[id] = c
    for j in range(k):
      P[c[j]] = id
  else:
    T[id] = "leaf"

for i in range(n):
  if P[i] == -1:
    root = i
    T[i] = "root"
  elif T[i] == []:
    T[i] = "internal node"

H = deque()
H.append(root)
D[root] = 0

while H:
  x = H.popleft()
  for nx in C[x]:
    H.append(nx)
    D[nx] = D[x] + 1

for i in range(n):
  print("node {}: parent = {}, depth = {}, {}, {}".format(i,P[i],D[i],T[i],C[i]))


Measured memory_bytes: 39584
#include <iostream>
using namespace std;
int main(void){
	int n,m,k;
  cin>>n;
  k=1;
  for(int i=1;i<=9;i++){
  	if(n%i==0){
    	m=n/i;
      if(m<=9){
      	cout << "Yes" <<endl;
        k=0; break;
      }
    }
  }
  if(k==1){
  	cout << "No" <<endl;
  }
}

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

#include <vector>
#include <queue>
#include <unordered_map>
#include <cmath>

using namespace std;


int main(){
    int N, M;
    cin >> N >> M;
    std::priority_queue<long long int> que;
    for(int i=1; i<=N; i++){
        long long int tmp;
        cin >> tmp;
        que.push(tmp);
    }

    for(int i=1; i<=M; i++){
        long long int top = que.top();
        que.pop();
        top/=2;
        que.push(top);
    }

    long long int sum;
    while(!que.empty()){
        sum += que.top();
        que.pop();
    }

    cout << sum << endl;
    return 0;
}


Measured memory_bytes: 1400
// Min, Max and Sum
// Write a program which reads a sequence of n integers ai(i=1,2,...n), and prints the minimum value, maximum value and sum of the sequence.

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

int main(){
    int n ;
    cin >> n;
    int min = 1000001;
    int max = -1000001;
    int64_t sum =0;
    for (int i = 0;i<n;i++)
    {
        int tmp;
        cin >> tmp;
        if(min > tmp) min = tmp;
        if(max < tmp) max = tmp;
        sum+=tmp;
    }
    cout << min<<" "<<max <<" "<<sum<<endl;
    
}


Measured memory_bytes: 3116
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class TEST{
	static void Main(){
		Sol mySol =new Sol();
		mySol.Solve();
	}
}

class Sol{
	public void Solve(){
		Console.WriteLine("A{0}C",rsa()[1][0]);
	}

	public Sol(){
		
	}

	static String rs(){return Console.ReadLine();}
	static int ri(){return int.Parse(Console.ReadLine());}
	static long rl(){return long.Parse(Console.ReadLine());}
	static double rd(){return double.Parse(Console.ReadLine());}
	static String[] rsa(char sep=' '){return Console.ReadLine().Split(sep);}
	static int[] ria(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>int.Parse(e));}
	static long[] rla(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>long.Parse(e));}
	static double[] rda(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>double.Parse(e));}
}


Measured memory_bytes: 11092
n = int(input())
a = list(map(int,input().split()))

ans = 0
now =0

for i in range(n):
    if i == n-1:
        ans =max(ans,now)
        break
    if a[i]>=a[i+1]:
        now+=1
    else:
        ans = max(ans,now)
        now = 0

print(ans)

Measured memory_bytes: 14252
import java.util.Collections;
import java.util.Scanner;
import java.util.Vector;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();

		for(int i = 0; i < n; i++){
			System.out.println(solve(sc.next()));
		}
	}

	static int solve(String str){
		Section root = new Section(null);
		Section current = root;

		int tmpNum = 0;
		for(int i = 1; i < str.length() - 1; i++){
			char c = str.charAt(i);
//			System.out.println(c);

			if(c == '['){
				current = current.add(new Section(current));
			}
			else if(c == ']'){
				if(tmpNum != 0){
					current.add(new Section(current, tmpNum));
//					System.out.println("add "+tmpNum);
					tmpNum = 0;
				}

				current = current.parent;
			}
			//数字
			else {
				tmpNum *= 10;
				tmpNum += c - '0';
			}
		}

		return root.calcSum();
	}

}

class Section implements Comparable<Section>{
	int id;
	static int idseed = 0;
	int sum = 0;
	Vector<Section> sections = new Vector<Section>();
	Section parent;
	int members = 0;

	Section(Section parent){
		this(parent, 0);
	}

	Section(Section parent, int members){
		id = idseed++;
		this.parent = parent;
		this.members = members;

//		System.out.println("id : "+id);
		if(parent != null){
//			System.out.println("my parent is :"+parent.id);
		}
	}

	Section add(Section sec){
		sections.add(sec);

		return sec;
	}

	int calcSum(){
		if(members != 0){
			sum = (members + 1)/2;
//			System.out.println("this is leaf. sum = "+sum);
			return sum;
		}

//		System.out.println("I have "+ sections.size() +" leaves");

		for(int i = 0; i < sections.size(); i++){
			sections.get(i).calcSum();
		}

		Collections.sort(sections);

		for(int i = 0; i < (sections.size() + 1)/2 ; i++){
			this.sum += sections.get(i).sum;
		}

		return sum;
	}

	@Override
	public int compareTo(Section s) {
		return this.sum - s.sum;
	}
}


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

int main(){
    int n;
    cin>>n;
    int x[n];
    rep(i,n) cin>>x[i];
    ll ans=INF;
    for(int i=1;i<=100;i++){
        ll tmp=0;
        rep(j,n){
            tmp+=(x[j]-i)*(x[j]-i);
        }
        ans=min(ans,tmp);
    }
    cout<<ans<<endl;

}

Measured memory_bytes: 256
from fractions import gcd
n,X=map(int,input().split())
x=list(map(int,input().split()))
x.append(X)
x.sort()
y=[x[i+1]-x[i] for i in range(n)]
ans=y[0]
for i in range(n):
	ans=gcd(ans,y[i])
print(ans)

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

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int N;
  cin >> N;
  vector<string> s(N);
  REP(i, N) cin >> s[i];

  int x = 0;
  int y = 0;
  int z = 0;
  int inside = 0;
  for(int i = 0; i < N; i++) {
    int si = s[i].size();
    if(s[i][0] == 'B' && s[i][si - 1] == 'A') {
      z++;
    } else if(s[i][si - 1] == 'A') {
      x++;
    } else if(s[i][0] == 'B') {
      y++;
    } else {
    }
    for(int j = 1; j < si; j++) {
      if(s[i][j - 1] == 'A' && s[i][j] == 'B') { inside++; }
    }
  }
  // cout << x << y << z << inside;
  if(x > 0 || y > 0) {
    cout << min(x, y) + z + inside << endl;
  } else if(z > 0) {
    cout << z - 1 + inside << endl;
  } else {
    cout << inside << endl;
  }
  return 0;
}

Measured memory_bytes: 768