akhauriyash/Code-Regression huggingface dataset:
#include <bits/stdc++.h>

using namespace std;

const long long INF = 1e18;

int a[405];
long long dp[405][405], ps[405];

long long solve(int l, int r) {
    if (dp[l][r] != -1) return dp[l][r];
    if (l == r) return dp[l][r] = 0;

    long long best = INF;

    for (int i = l; i < r; i++) {
        best = min(best, solve(l, i) + solve(i + 1, r));
    }

    best += ps[r] - ps[l - 1];
    return dp[l][r] = best;
}

int main() {
    int n;
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);

    for (int i = 1; i <= n; i++) ps[i] = ps[i - 1] + a[i];
    
    memset(dp, -1, sizeof(dp));

    printf("%lld\n", solve(1, n));
}


Measured memory_bytes: 1536
//shan61916
#include <bits/stdc++.h>
    using namespace std;
#define IOS ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define endl "\n" 
typedef long long ll;
typedef unsigned long long ull ;
typedef double dll ;
vector<vector<pair<ll,ll>> > adj;
vector<ll> dist ;
vector<bool> visited;
void dfs(ll idx) {
  visited[idx] = true;
  for(auto it: adj[idx]) {
    if(!visited[it.first]) {
      dist[it.first] = dist[idx] + it.second;
      dfs(it.first);
    }
  }
}
int main(){
 IOS
#ifdef SHAN
    freopen("input.txt" , "r" , stdin);  
#endif
  ll n;
  cin >> n;
  adj.resize(n+1) ;
  dist.resize(n+1, 0);
  visited.resize(n+1, false);
  for(ll i = 0; i < n-1 ; i++) {
    ll x, y, z;
    cin >> x >> y >> z;
    adj[x].push_back({y,z});
    adj[y].push_back({x,z});
  }
   dfs(1);
   vector<ll> ans(n+1) ;
   ans[1] = 0;
   for(ll i = 2; i <= n; i++){
     if(dist[i]%2 == 0) {
      ans[i] = ans[0] ;
     }
     else {
      ans[i] = ans[0]^1 ;
          }
   }
   for(ll i = 1; i <=n; i++) cout << ans[i] << endl;
  return 0;
} //good night.


Measured memory_bytes: 10752
#include <iostream>

using namespace std;

int main() {
	int a, b, c, k;
	cin >> a >> b >> c >> k;

	if (a > b) swap(a, b);
	if (b > c) swap(b, c);
	if (a > b) swap(a, b);

	for (int i = 0; i < k; i++)
		c *= 2;
	cout << a + b + c << endl;
	return 0;
}


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

int main() {
  vector<vector<char>> a(2,vector<char>(3));
   
  rep(i,2)rep(j,3) cin >> a.at(i).at(j);

  bool  ans = true;
  rep(i,3){
    if(a.at(0).at(i) != a.at(1).at(2-i)) ans = false;
  }
  puts(ans?"YES":"NO");
}

Measured memory_bytes: 3604
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<climits>
#include<iostream>
#include<sstream>
#include<utility>
#include<map>
#include<vector>
#include<queue>
#include<algorithm>
#include<set>
#include<stack>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;

ll N,M,r=0;
int main()
{
	scanf("%lld%lld",&N,&M);
	if(N<M/2)
	{
		r+=N;
		M-=N*2;
	}
	else
	{
		r+=M/2;
		M-=(M/2)*2;
	}
	if(M>0)r+=M/4;
	printf("%lld\n",r);
	return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cmath>
#include <string>
#include <set>
#include <utility>
#include <cstdlib>
#include <queue>
#include <stack>
#include <iomanip>
#include <cstdio>
#include <map>

using namespace std;

using ll = long long;
using P = pair<ll,ll>;

#define rep(i,x) for(ll i = 0; i < (ll)(x); i++)
#define rrep(i,x) for(ll i = ((ll)(x) - 1); i >= 0; i--)

#define _upgrade ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define all(x) (x).begin(), (x).end()
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );

template<class T1, class T2> void chmin(T1 &a, T2 b){if(a>b)a=b;}
template<class T1, class T2> void chmax(T1 &a, T2 b){if(a<b)a=b;}

//ll gcd(ll a, ll b){return b?gcd(b,a%b):a;}
//ll lcm(ll x, ll y) {return x / gcd(x, y) * y;}
/*bool prime(int x) {
	for (int i = 2; i <= sqrt(x); i++) {
		if (x%i == 0)return false;
	}
	return true;
}*/

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

const ll mod = 1e9 + 7;
const ll IMF = 1LL<<29;
const double PI = 3.14159265358979323846;


// ******************************CODE**********************************//






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

        sort(all(a));

        int maxv = a[n-1];

        int x = maxv/2;

        int b = -1, c = 0;

        for(int i = 0; i < n-1; i++)
        {
                if(a[i] >= x){
                        b = a[i];
                        c = a[i-1];
                        break;
                }
        }

        if(b != -1){
                int up = b-x;
                int down = x-c;
                if(up > down){
                        cout << maxv << " " << c << endl;
                }
                else{
                        cout << maxv << " " << b << endl;
                }

        }
        else{
                cout << maxv << " " << a[n-2] << endl;
        }

        return 0;
}


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

int main()
{
    int n;
    cin >> n;
    
    i64 cnt = 0;
    unordered_map<int, int> ht;
    rep2(i,1,n+1)
    {
        if(i%10 == 0) continue;
        int head = 0;
        int tail = i%10;
        int j = i;
        while(j > 0)
        {
            head = j%10;
            j /= 10;
        }

        int key = head*10 + tail;
        // printf("i=%d head=%d tail=%d key=%d\n", i,head,tail,key);
        if(ht.count(key) == 0) ht.insert({key, 1});
        else ht[key]++;
    }

    rep2(i,1,10)
        rep2(j,i,10)
        {
            int key_ij = i*10+j;
            int key_ji = j*10+i;
            if(ht.count(key_ij) == 0 || ht.count(key_ji) == 0)
                continue;
            
            if(i == j) cnt += ht[key_ij]*(ht[key_ij]-1)/2*2 + ht[key_ij];
            else cnt += 2*ht[key_ij]*ht[key_ji];
        }

    cout << cnt << endl;
    return 0;
}

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

const ll INF = 1LL << 62;
const double PI = acos(-1);
const double eps = 1e-10;

int main() {
  ll n, d1, d2, cnt = 0;
  cin >> n;
  rep(i, n) {
    cin >> d1 >> d2;
    if (d1 == d2) {
      cnt++;
      if (cnt == 3) {
        cout << "Yes" << endl;
        return 0;
      }
    } else {
      cnt = 0;
    }
  }
  cout << "No" << endl;
  return 0;
}


Measured memory_bytes: 3592
#include "bits/stdc++.h"
using namespace std;

#define ll long long 
#define ii pair<ll,ll>
const int MAXN = 1e5 + 5;
const ll MOD = 1e9 + 7, INF = 1e18;

int n, m, s, t;
ii fromS[MAXN], fromT[MAXN];
vector<ii> adj[MAXN];
ll ans;

ll add(ll a, ll b){ return (a+b+MOD)%MOD; }
ll mul(ll a, ll b){ return (a*b)%MOD; }

void dijkstra(ii d[], int start){
	for(int i = 1; i <= n; ++i){
		d[i] = ii(INF, 0);
	}
	priority_queue<ii> pq;
	pq.push(ii(0, start));
	while(!pq.empty()){
		ii top = pq.top(); pq.pop();
		ll curDist = -top.first, pos = top.second;
		if(d[pos].first <= curDist)
			continue;
		d[pos] = ii(curDist, 0);
		for(ii i : adj[pos]){
			pq.push(ii(-d[pos].first-i.second, i.first));
		}
	}

	vector<int> dist = {};
	for(int i = 1; i <= n; ++i) dist.push_back(i);
	sort(dist.begin(), dist.end(), [d](int a, int b){ return d[a].first < d[b].first; });
	d[start].second = 1;
	for(int i = 1; i < n; ++i){
		int pos = dist[i];
		for(ii j : adj[pos]){
			if(d[j.first].first+j.second == d[pos].first){
				d[pos].second = add(d[pos].second, d[j.first].second);
			}
		}
	}
}

int main(){
	scanf("%d %d %d %d", &n, &m, &s, &t);
	for(int i = 0; i < m; ++i){
		ll u, v, w;
		scanf("%lld %lld %lld", &u, &v, &w);
		adj[u].push_back(ii(v, w));
		adj[v].push_back(ii(u, w));
	}

	dijkstra(fromS, s);
	dijkstra(fromT, t);
	assert(fromS[t].second == fromT[s].second && fromS[t].first == fromT[s].first);

	// Get all paths
	ll ans = mul(fromS[t].second, fromS[t].second);
	// Minus meet at vertex
	for(int i = 1; i <= n; ++i){
		// printf("(%lld, %lld) (%lld, %lld)\n", fromS[i].first, fromS[i].second, fromT[i].first, fromT[i].second);
		if(fromS[i].first == fromT[i].first)
		if(fromS[i].first+fromT[i].first == fromS[t].first){
			ll tmp = mul(fromS[i].second, fromT[i].second);
			tmp = mul(tmp, tmp);
			// printf("Del %lld %d\n", tmp, i);
			ans = add(ans, -tmp);
		}
	}
	// Minus meet at edge
	for(int i = 1; i <= n; ++i){
		for(ii j : adj[i]){
			if(fromS[i].first != fromT[i].first && fromS[j.first].first != fromT[j.first].first)
			if(fromS[i].first + fromT[j.first].first + j.second == fromS[t].first)
			if(2*fromS[i].first < fromS[t].first && 2*fromS[j.first].first > fromS[t].first){
				ll tmp = mul(fromS[i].second, fromT[j.first].second);
				tmp = mul(tmp, tmp);
				ans = add(ans, -tmp);
			}
		}
	}
	printf("%lld\n", ans);
}

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

#define REP(i,m,n) for(int i=(m); i<(int)(n); i++)
#define RREP(i,m,n) for(int i=(int)((n)-1); i>=m; i--)
#define rep(i,n) REP(i,0,n)
#define rrep(i,n) RREP(i,0,n)
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define fi first
#define se second
#define debug(...) {cerr<<"[L"<<__LINE__<<"] "; _debug(__VA_ARGS__);}

template<typename T>
string join(const vector<T>&v, string del=", "){ stringstream s;
    for(auto x : v) s << del << x; return s.str().substr(del.size());
}
template<typename T>
ostream& operator<<(ostream& o, const vector<T>&v){
    if(v.size()) o << "[" << join(v) << "]"; return o;
}
template<typename T>
ostream& operator<<(ostream& o, const vector<vector<T> >&vv){
    int l = vv.size();
    if(l){ o<<endl; rep(i,l) o << (i==0 ? "[ " : ",\n  " ) << vv[i] << (i==l-1 ? " ]" : ""); }
    return o;
}
template<typename T1, typename T2>
ostream& operator<<(ostream& o, const pair<T1, T2>& p){
    return o << "(" << p.first << ", " << p.second << ")";
}
inline void _debug(){cerr<<endl;}
template<class First, class... Rest>
void _debug(const First& first, const Rest&... rest){cerr<<first<<" ";_debug(rest...);}

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

const double PI = (1*acos(0.0));
const double EPS = 1e-9;
const int INF = 0x3f3f3f3f;
const ll INFL = 0x3f3f3f3f3f3f3f3fLL;
const ll mod = 1e9 + 7;

inline void finput(string filename) {
    freopen(filename.c_str(), "r", stdin);
}

template<typename T>
struct BIT{
    int n;
    vector<T> dat;
    BIT(int n) : n(n), dat(n+1,0){}
    void add(int x, T val){
        for(int i = x+1; i <= n; i += (i & -i)) dat[i] += val;
    }
    T sum(int x){
        T ret = 0;
        for(int i = x+1; i > 0; i -= (i & -i)) ret += dat[i];
        return ret;
    }
    T sum(int a, int b){
        return sum(b) - sum(a-1);
    }
};

int main(){
    ios_base::sync_with_stdio(0);
    // finput("./input");
    int n,q; cin >> n >> q;
    vi C(n+1);
    rep(i,n) cin >> C[i+1];

    vector<tuple<ll,ll,ll>> Q;
    rep(i,q){
        int l,r; cin >> l >> r;
        Q.emplace_back(r,l,i);
    }
    Q.emplace_back(n+10,0,0);
    sort(all(Q));

    auto bit = BIT<ll>(n+10);
    vi last(n+1, -1);

    int pos = 0;
    vi ans(q);
    rep(i,q){
        int qr = get<0>(Q[i]);
        int ql = get<1>(Q[i]);
        int idx = get<2>(Q[i]);
        while(pos <= qr){
            if(last[C[pos]] != -1){
                bit.add(last[C[pos]], -1);
            }
            bit.add(pos, 1);
            last[C[pos]] = pos;
            pos++;
        }
        ans[idx] = bit.sum(ql, qr);
    }
    rep(i,q) cout << ans[i] << endl;
    return 0;
}

Measured memory_bytes: 25300
ABC = "ABC"
s = [input()+ABC[i] for i in range(3)]
turn = s[0]
card = 0
count = [1, 0, 0]

for i in range(305):
    if turn[card] == "a":
        turn = s[0]
        card = count[0]
        count[0] += 1
    elif turn[card] == "b":
        turn = s[1]
        card = count[1]
        count[1] += 1
    else:
        turn = s[2]
        card = count[2]
        count[2] += 1
    
    if turn[card] == "A":
        print("A")
        exit()
    if turn[card] == "B":
        print("B")
        exit()
    if turn[card] == "C":
        print("C")
        exit()

Measured memory_bytes: 62048
#include <bits/stdc++.h>
using namespace std;
const int P = 1e9 + 7;
int main() {
	int n;
	long long k;
	cin >> n >> k;
	vector<int> a(n);
	for(int i = 0; i < n; ++i) {
		cin >> a[i];
	}
	long long ans = 0;
	for(int i = 0; i < n; ++i) {
		long long tmp = 0;
		for(int j = 0; j < i; ++j) {
			if(a[i] < a[j]) {
				++tmp;
			}
		}
		ans = (ans + tmp * k % P) % P;
		tmp = 0;
		for(int j = 0; j < n; ++j) {
			if(a[i] < a[j]) {
				++tmp;
			}
		}
		ans = (ans + (k * (k - 1) / 2) % P * tmp % P) % P;
	}
	cout << ans % P << '\n';
	return 0;
}

Measured memory_bytes: 256
import static java.util.Arrays.deepToString;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		new Main().run();
	}
	void tr(Object... os) {
		System.err.println(deepToString(os));
	}
	
	int n;
	int[] memo = new int[60000];
	Scanner sc = new Scanner(System.in);
	public void run() {
		for (;sc.hasNext();) {
			String s = sc.next();
			if (s.equals("0")) break;
			Arrays.fill(memo, -1);
			
			int ans = -1;
			n = s.length();
			Queue<char[]> q = new ArrayDeque<char[]>();
			q.add(s.toCharArray());
			memo[h(s.toCharArray())] = 0;
			while (!q.isEmpty()) {
				char[] cur = q.poll();
				if (isok(cur)) {
					ans = memo[h(cur)];
					break;
				}
				int w = memo[h(cur)];
				for (int i = 0; i + 1 < cur.length; i++) {
					if (cur[i] != cur[i+1]) {
						char nc = getnc(cur[i], cur[i+1]);
						char[] nxt = cur.clone();
						nxt[i] = nxt[i+1] = nc;
						
						int h = h(nxt);
						if (memo[h] == -1) {
							memo[h] = w + 1;
							q.add(nxt);
						}
					}
				}
			}
			
			if (ans < 0) {
				System.out.println("NA");
			} else {
				System.out.println(ans);
			}
		}
	}
	char getnc(char c1, char c2) {
		if (c1 == 'r' && c2 == 'g') return 'b';
		if (c1 == 'g' && c2 == 'r') return 'b';
		
		if (c1 == 'r' && c2 == 'b') return 'g';
		if (c1 == 'b' && c2 == 'r') return 'g';
		
		if (c1 == 'b' && c2 == 'g') return 'r';
		if (c1 == 'g' && c2 == 'b') return 'r';
		throw new RuntimeException("orz");
	}
	boolean isok(char[] s) {
		for (int i = 0; i + 1 < s.length; i++) {
			if (s[i] != s[i+1]) return false;
		}
		return true;
	}
	int h(char[] s) {
		int h = 0;
		for (char c : s) h = h * 3 + "rgb".indexOf(c);
		return h;
	}
	char[] g(int h) {
		char[] s = new char[n];
		for (int i = n - 1; i >= 0; i--) {
			s[i] = "rgb".charAt(h % 3);
			h /= 3;
		}
		return s;
	}
}

Measured memory_bytes: 50708
using System;
class B{
  static void Main(){
    var a = Console.ReadLine();
    var b = Console.ReadLine();
    var ans = "";
    for (int i = 0; i < b.Length; i++)
      ans += $"{a[i]}{b[i]}";
    if (a.Length > b.Length)
      ans += a[a.Length - 1];
    Console.WriteLine(ans);
  }
}

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

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


Measured memory_bytes: 3040
#include <iostream>
#include <string>
#include <utility>
#include <stack>
#include <vector>
#include <queue>
#include <algorithm>
#include <map>
#include <climits>
#include <set>
using namespace std;

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

    if(S[0] != S[S.size() - 1]){
        if(S.size() % 2 == 0){
            cout << "Second" << endl;
        } else {
            cout << "First" << endl;
        }
    } else {
        if(S.size() % 2 == 0){
            cout << "First" << endl;
        } else {
            cout << "Second" << endl;
        }
    }
    return 0;
}

Measured memory_bytes: 512
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#define ll long long
using namespace std;

const ll mod = 1e9 + 7;

ll C[2005][2005];
ll dp[100005][13];


int main(){
    int N,ans=0;
    string S,T;
    cin >> N;
    cin >> S;
    if(N%2==0 && S.substr(0,N/2) == S.substr(N/2,N/2)){
        cout << "Yes" << endl;
    }else{
        cout << "No" << endl;
    }
}

Measured memory_bytes: 3604
def mapint_inp():
    return map(int, input().split())
 
def intinp():
    return int(input())
 
import math
import itertools
  
K = intinp()
 
ans = 0
for i in range(1, K+1):
    for j in range(1, K+1):
        ij = math.gcd(i, j)
        for k in range(1, K+1):
            ans += math.gcd(ij, k)
 
print(ans)

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

int main(){
  ll N, K;
  cin >> N >> K;
  double res;
  rep(i, N){
    double tmp = 1.0 / N;
    ll nn = i;
    while (nn < K) nn*=2, tmp /= 2;
    res += tmp;
  }
  
  printf("%.12f\n", res);
}

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

void solve(std::istream &ist, std::ostream &ost)
{
    /* ------- 宣言と入力 ------- */

    double A, B, H, M;
    ist >> A >> B >> H >> M;

    /* ------- 計算 ------- */
    double hour_arg = 2 * M_PI / 12;
    double minite_arg = 2 * M_PI / 60;

    double hour_hand = H * hour_arg + M / 60 * hour_arg;
    double minite_hand = M * minite_arg;

    double theta = abs(hour_hand - minite_hand);

    double ans = pow(A, 2) + pow(B, 2) - 2 * A * B * cos(theta);

    ost << fixed << setprecision(15) << (double)sqrt(ans) << endl;
}

#ifndef WOMAIN
int main()
{
    solve(std::cin, std::cout);
    return 0;
}
#endif


Measured memory_bytes: 4224
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class Main {

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

		int n = Integer.parseInt(br.readLine());

		String str[] = br.readLine().split(" ");

		int value[] = new int[n];

		for (int i = 0; i < n - 1; i++) {
			int a = Integer.parseInt(str[i]);

			value[a - 1]++;
		}

		for (int i = 0; i < n; i++) {
			System.out.println(value[i]);
		}
	}
}

Measured memory_bytes: 65228
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <cstdlib>
#include <string.h>

typedef long long ll;

using namespace std;

int main() {
    string a, b;
    cin >> a;
    cin >> b;

    int cnt = 0;

    for (int i = 0; i < 3; i++) {
        if (a.at(i) == b.at(i)) {
            cnt++;
        }
    }

    cout << cnt << endl;
}

Measured memory_bytes: 256
a,b,c,d = list(map(int, input().split()))

def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 10**9+7
N = 10 ** 6 + 2
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)
    
def wh(w,h):
    return cmb(w+h,w,10**9+7)

ans = wh(b-1,a-1)
#print(ans)

for i in range(d):
    tmp = wh(i,a-c-1) * wh(c-1,b-i-1) % p
    ans += p
    ans -= tmp
    ans %= p
    #print(ans)
    
print(ans)




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

int n, m, q, dot[100001] = {}, maxp[100001] = {};
vector<int> g[100001];
int v[100001], d[100001], c[100001];

void dfs(int col, int step, int f)
{
	if (dot[f] == 0) dot[f] = col;
	
	if (maxp[f] >= step) return;
	maxp[f] = step;

	int length = g[f].size();
	for (int i = 0; i < length; i++)
	{
		if (step - 1 >= 0) dfs(col, step - 1, g[f][i]);
	}
}

int main()
{
	cin >> n >> m;
	int f, t;
	for (int i = 1; i <= m; i++)
	{
		cin >> f >> t;
		g[f].push_back(t);
		g[t].push_back(f);
	}
	
	cin >> q;
	for (int i = 1; i <= q; i++)
		cin >> v[i] >> d[i] >> c[i];
		
	for (int i = q; i >= 1; i--)
	{
		dfs(c[i], d[i], v[i]);
	}	
	
	for (int i = 1; i <= n; i++)
		cout << dot[i] << '\n';
	
	return 0;
}

Measured memory_bytes: 8440
import java.io.*;
import java.util.*;

public class Main {

	final static long MOD = 1000000007;
	public static String[] Ws = null;
	public static int wsIndx = 0;
	public static BufferedReader in = null;
	public static void main(String[] args) throws Exception {
		solution(args);
		if(in!=null){
			in.close();
		}
	}

	public static void solution(String[] args) throws Exception{

		int A = nextInt();

		String ans ="ABC";
		if(A>=1200)
			ans="ARC";
		System.out.println(ans);

	}

	public static boolean isPalindromicStr(String s) {
		int h = 0;
		int t = s.length() - 1;
		while (h <= t) {
			if (s.charAt(h) != s.charAt(t)) {
				break;
			}
			h++;
			t--;
		}
		if (h > t) {
			return true;
		}
		return false;
	}
	public static String[] toStringArray(String s) {
		String[] tmp = new String[s.length()];
		char[] c = s.toCharArray();
		for (int i = 0; i < tmp.length; i++) {
			tmp[i] = String.valueOf(c[i]);
		}
		return tmp;
	}

	public static void check() throws Exception{
		if(in == null){
			in = new BufferedReader(new InputStreamReader(System.in));
		}
		if(Ws==null || Ws.length<=wsIndx){
			Ws = in.readLine().split(" ");
			wsIndx=0;
		}
	}
	public static int nextInt()throws Exception{
		check();
		return Integer.parseInt(Ws[wsIndx++]);
	}

	public static long nextLong()throws Exception{
		check();
		return Long.parseLong(Ws[wsIndx++]);
	}

	public static String nextString()throws Exception{
		check();
		return Ws[wsIndx++];
	}

	public static int[] nextInts()throws Exception{
		check();
		int[] tmp = new int[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Integer.parseInt(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static long[] nextLongs()throws Exception{
		check();
		long[] tmp = new long[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Long.parseLong(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static String[] nextStrings()throws Exception{
		check();
		wsIndx=Ws.length;
		return Ws;
	}


}


Measured memory_bytes: 20820
#include <algorithm>
#include <cassert>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>

#include <limits.h>

using namespace std;

typedef long long ll;

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

vector<int> as;

int main(void) {
    int N, D, X;
    cin >> N >> D >> X;

    as.resize(N);
    for (int i = 0; i < N; i++) {
        cin >> as[i];
    }

    int ans = X;
    for (int i = 0; i < N; i++) {
        ans++;
        for (int j = as[i] + 1; j <= D; j += as[i]) {
            ans++;
        }
    }

    cout << ans << endl;

    return 0;
}


Measured memory_bytes: 3568
from collections import deque
N,M=map(int,input().split())
if N-1==M:
  print(0)
  exit()
A=[int(a) for a in input().split()]
G=[[] for i in range(N)]
inf=float("inf")
for i in range(M):
  a,b=map(int,input().split())
  G[a].append(b)
  G[b].append(a)
Tree=[-1]*N

def BFS(x,n):
  global Tree
  stack=deque([x])
  while stack:
    a=stack.popleft()
    Tree[a]=n
    for b in G[a]:
      if Tree[b]<0:
        stack.append(b)
n=0
for i in range(N):
  if Tree[i]<0:
    BFS(i,n)
    n+=1
    
P=[inf]*n
for i in range(N):
  P[Tree[i]]=min(P[Tree[i]],A[i])
P.sort()
ans=sum(P)
P.append(inf)
k=0
A.sort()
for i in range(N):
  if A[i]==P[k]:
    A[i]=inf
    k+=1
A.sort()
if 2*(N-M-1)-n>=N or n>2*(N-M-1) or N-2*(N-M-1)<0:
  print("Impossible")
  exit()
for i in range(2*(N-M-1)-n):
  ans+=A[i]
if ans!=inf:
  print(ans)
    
  
  

Measured memory_bytes: 82968
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int x = scanner.nextInt();
		int y = scanner.nextInt();
		
		System.out.println(String.valueOf(x * y) + " " + String.valueOf(2*x + 2*y));
	}

}

Measured memory_bytes: 17160
#include<iostream>
#include<vector>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);++i)
using ll = long long;
using P = pair<int, int>;
#include<algorithm>
#include<math.h>
#include<map>
#include<queue>
#include<set>

int main() {
	int n;
	cin >> n;
	vector<int>a(n),b(n);
	rep(i, n) {
		cin >> a[i];
		b[i] = a[i];
	}
	sort(a.rbegin(), a.rend());
	int m1 = a[0];
	int m2 = a[1];
	rep(i, n) {
		int k = b[i];
		if (k == m1) {
			cout << m2;
		}
		else {
			cout << m1;
		}
		cout << endl;
	}
	return 0;
}

Measured memory_bytes: 4780
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define SORT(v) sort((v).begin(), (v).end())
#define RSORT(v) sort((v).rbegin(), (v).rend())
const ll MOD = 1000000007;
const ll nmax = 8;
const ll INF = 1e9;
bool graph[nmax][nmax];
vector<vector<ll>> dist = vector<vector<ll>>(nmax, vector<ll>(nmax, INF));
void warshall_floyd(ll n)
{
    for (size_t i = 0; i < n; i++)
    {
        for (size_t j = 0; j < n; j++)
        {
            for (size_t k = 0; k < n; k++)
            {
                dist[j][k] = min(dist[j][k], dist[j][i] + dist[i][k]);
            }
        }
    }
}

class UnionFind
{
public:
    vector<ll> Parent;

    UnionFind(ll N)
    {
        Parent = vector<ll>(N, -1);
    }
    ll find(ll A)
    {
        if (Parent[A] < 0)
            return A;
        return Parent[A] = find(Parent[A]);
    }

    ll size(ll A)
    {
        return -Parent[find(A)];
    }

    bool Union(ll A, ll B)
    {
        A = find(A);
        B = find(B);
        if (A == B)
        {
            return false;
        }
        if (size(A) < size(B))
            swap(A, B);

        Parent[A] += Parent[B];
        Parent[B] = A;

        return true;
    }
};

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 mulMod(ll a, ll b)
{
    return (((a % MOD) * (b % MOD)) % MOD);
}

ll powMod(ll a, ll p)
{
    if (p == 0)
    {
        return 1;
    }
    else if (p % 2 == 0)
    {
        ll half = powMod(a, p / 2);
        return mulMod(half, half);
    }
    else
    {
        return mulMod(powMod(a, p - 1), a);
    }
}

void solve(long long N, std::vector<std::string> s)
{
}

int main()
{
    long long N;
    scanf("%lld", &N);
    std::vector<std::string> s(N);
    for (int i = 0; i < N; i++)
    {
        std::cin >> s[i];
    }
    int ans = 0;
    int endA = 0;
    int startB = 0;
    int each = 0;

    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < s[i].size(); j++)
        {
            if (s[i][j - 1] == 'A' && s[i][j] == 'B')
            {
                ans++;
            }
        }

        if (s[i][0] == 'B' && s[i][s[i].size() - 1] != 'A')
        {
            startB++;
        }
        if (s[i][0] != 'B' && s[i][s[i].size() - 1] == 'A')
        {
            endA++;
        }
        if (s[i][0] == 'B' && s[i][s[i].size() - 1] == 'A')
        {
            each++;
        }
    }

    if (each > 0)
    {
        ans += (each - 1);
        if (endA > 0)
        {
            ans++;
            endA--;
        }
        if (startB > 0)
        {
            ans++ +
                startB--;
        }
    }

    ans += min(endA, startB);
    cout << ans << endl;
    return 0;
}


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

#define pb push_back
#define fi first
#define se second
typedef long long ll;

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

	int a, b, c;
	cin >> a >> b >> c;
	cout << (a + b + c >= 22 ? "bust\n" : "win\n");
}


Measured memory_bytes: 256
function f(i, x, n, acc) {
  if (x > n) return acc;
  var p = new Array(10);
  var m = x;
  while (m > 0) {
    switch(m % 10) {
      case 3: {
        p[3] = true;
        break;
      }
      case 5: {
        p[5] = true;
        break;
      }
      case 7: {
        p[7] = true;
        break;
      }
      default: {
        break;
      }
    }
    m = Math.floor(m / 10);
  }
  acc += p[3] === true && p[5] === true && p[7] === true ? 1 : 0;
  acc += f(i + 1, Math.pow(10, i) * 3 + x, n, 0);
  acc += f(i + 1, Math.pow(10, i) * 5 + x, n, 0);
  acc += f(i + 1, Math.pow(10, i) * 7 + x, n, 0);
  return acc;
}

function Main(input) {
  var n = parseInt(input);
  var acc = 0;
  acc += f(1, 3, n, 0);
  acc += f(1, 5, n, 0);
  acc += f(1, 7, n, 0);
  console.log(acc);
}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


Measured memory_bytes: 13488
#include<stdio.h>
int main(){
  int i,j,k,x,count;
  char A[1025];
  char number[10][6]={
    {".,!? "},
    {"abc"},
    {"def"},
    {"ghi"},
    {"jkl"},
    {"mno"},
    {"pqrs"},
    {"tuv"},
    {"wxyz"},
  };
  scanf("%d",&x);
  for(i=0;i<x;i++){
    count=0;
    scanf("%s",A);
    for(j=0;A[j]!='\0';j++){
      if(A[j]=='0'&& j>0){
	if(('2'<=A[j-1] && A[j-1]<='6') || A[j-1]=='8'){
	  printf("%c",number[A[j-1]-'1'][(count-1)%3]);
	}else if(A[j-1]=='1'){
	  printf("%c",number[A[j-1]-'1'][(count-1)%5]);
	}else if(A[j-1]=='0'){
	}else{
	  printf("%c",number[A[j-1]-'1'][(count-1)%4]);
	}
	count=0;
      }else if(A[j]!='0'){
	count++;
      }
    }
    puts("");
  }
  return 0;
}

Measured memory_bytes: 588
#include <math.h>
#include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>

using namespace std;

using ll = long long;

int A, B;
string s;

int main() {
    cin >> A >> B;
    cin >> s;

    for (int i = 0; i < A; i++) {
        if (!('0' <= s[i] && s[i] <= '9')) {
            cout << "No" << endl;
            return 0;
        }
    }

    if (s[A] != '-') {
        cout << "No" << endl;
        return 0;
    }

    for (int i = A+1; i < s.size(); i++) {
        if (!('0' <= s[i] && s[i] <= '9')) {
            cout << "No" << endl;
            return 0;
        }
    }

    cout << "Yes" << endl;
    return 0;
}

Measured memory_bytes: 256
#include<iostream>
#include<vector>
#include<map>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<bitset>
#include<iomanip>
#define BUG puts("no bug")
#define sci(x) scanf("%d",&x)
#define scl(x) scanf("%lld",&x)
#define ll long long
#define ull unsigned long long
#define REP(a,b,c) for(int a=b;a<=c;a++)
#define PER(a,b,c) for(int a=b;a>=c;a--)
#define lb(a) (a&(-a))
#define pp (p<<1)
#define ppp (p<<1|1)
#define pi pair<int,int>
#define pii pair<pair<int,int>,int>
using namespace std;
const int MAXN=1e6+5;
int n,m,t;
int gcd(int a,int b){ return b==0?a:gcd(b,a%b);}
int main(){
    cin>>n;
    int ans=0;
    REP(i,1,n){
        REP(j,1,n){
            REP(k,1,n){
                ans+=gcd(i,gcd(j,k));
            }
        }
    }
    cout<<ans;
}

Measured memory_bytes: 3192
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

// ここまで

fn topological_sort (g: &Vec<Vec<usize>>, r: usize) -> (Vec<usize>, Vec<usize>) {
    let n = g.len();
    let mut q = std::collections::VecDeque::new();
    let mut a = Vec::with_capacity(n);
    let mut p = vec![n; n];
    q.push_back (r);
    a.push (r);
    while !q.is_empty() {
        let v = q.pop_front().unwrap();
        for &u in &g[v] {
            if u == p[v] {
                continue;
            }
            p[u] = v;
            q.push_back (u);
            a.push (u);
        }
    }
    (p, a)
}

fn run() {
    input! {
        n: usize,
        e: [(usize1, usize1); n - 1],
    }
    let mut g = vec![vec![]; n];
    for (a, b) in e {
        g[a].push (b);
        g[b].push (a);
    }
    let (p, q) = topological_sort (&g, 0);
    let modulo = 1000000007;
    let mut dp = vec![(0, 0); n];
    for i in (0..n).rev() {
        let v = q[i];
        let mut w: u64 = 1;
        let mut b: u64 = 1;
        for &u in &g[v] {
            if u == p[v] {
                continue;
            }
            b = b * dp[u].0 % modulo;
            w = w * (dp[u].0 + dp[u].1) % modulo;
        }
        dp[v] = (w, b);
    }
    let ans = (dp[0].0 + dp[0].1) % modulo;
    println! ("{}", ans);
}

fn main() {
    run();
}


Measured memory_bytes: 21884
using System;


namespace ConsoleApplication43
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = Console.ReadLine();
            string p = Console.ReadLine();
            string ss = s + s;
            int a = 0;
            for (int i = 0; i < s.Length; i++)
            {
                 if (p[0].Equals(ss[i]))
                 {
                     if(ss.Length > (i + p.Length -1))
                     {
                         string S1 = ss.Substring(i, p.Length);
                         if (p.Equals(S1))
                         {
                             a += 1;
                             break;
                         }

                     }
                 }
            }
            if(a > 0)
            {
                Console.WriteLine("Yes");
            }
            else
            {
                Console.WriteLine("No");
            }
        }
    }
}

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

using namespace std;
#ifdef _DEBUG
#define _GLIBCXX_DEBUG
#include "dump.hpp"
#else
#define dump(...)
#endif

#define int long long
#define ll long long
#define DBG 1
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define rrep(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define loop(n) rep(loop, (0), (n))
#define all(c) begin(c), end(c)
const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)(1e9) + 7;
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
using pii = pair<int, int>;
// template<class T> ostream &operator<<(ostream &os,T &t){dump(t);return os;}
template <typename T, typename S>istream &operator>>(istream &is, pair<T, S> &p) { is >> p.first >> p.second; return is; }
//template <typename T, typename S>ostream &operator<<(ostream &os, pair<T, S> &p) {os << p.first << " " << p.second;return os;}

template <typename T> void printvv(const vector<vector<T>> &v) {
	cerr << endl;
	rep(i, 0, v.size()) rep(j, 0, v[i].size()) {
		if (typeid(v[i][j]).name() == typeid(INF).name() and v[i][j] == INF) {
			cerr << "INF";
		}
		else
			cerr << v[i][j];
		cerr << (j == v[i].size() - 1 ? '\n' : ' ');
	}
	cerr << endl;
}

#ifndef _DEBUG
#define printvv(...)
#endif
void YES(bool f) { cout << (f ? "YES" : "NO") << endl; }
void Yes(bool f) { cout << (f ? "Yes" : "No") << endl; }
template <class T, class U>bool chmin(T& a, U b) { if (a > b) { a = b; return true; }return false; }
template <class T, class U>bool chmax(T& a, U b) { if (a < b) { a = b; return true; }return false; }

signed main(signed argc, char *argv[]) {
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout << fixed << setprecision(12);

	int N; cin >> N;
	vector<string>v(N); rep(i, 0, N) { cin >> v[i]; }
	map<string, int>mp;
	for (auto s : v)mp[s]++;
	int a = 0;
	map<int, vector<string>>hoge;
	for (auto p : mp) {
		hoge[p.second].eb(p.first);
	}
	auto mx = max_element(all(hoge));
	auto unko = *mx;
	sort(all(unko.second));
	for (auto aho : unko.second) {
		cout << aho << endl;
	}

	return 0;
}


Measured memory_bytes: 28656
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i,n) for(ll i = 0; i < n; i++)
#define rep2(i,start,end) for(ll i = start; i < end; i++)
#define dwn(i,n) for(int i = n; i >= 0; i--)
#define dwn2(i,start,end) for(ll i = start; i >= end; i--)
#define pll pair<ll,ll>
#define mk(x,y) make_pair(x,y)
#define pdl pair<double, ll>
const ll N = 4e5 + 200;
const ll INF = 0x3f3f3f3f;
const ll mod = 1e9 + 7;


int main(){
	ll n;
	cin>>n;
	cout<<3.1415926*2*n<<endl;



	return 0;
}






Measured memory_bytes: 3788
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iomanip>

using namespace std;

void cout_vec(deque<int> &vec){
    for(int i=0; i<vec.size(); i++){
        if (i!=0){
            cout << ' ';
        }
        cout << vec[i];
    }
    cout << endl;
}

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

    deque<int> ans;
    for(int i=0; i<N; i++){
        int max_=0;
        int j=1;
        int index=0;
        for(int k=1; k<N+1; k++){
            if(b[k]==0)continue;
            if(b[k]==j && max_<j){
                max_=j;
                index=k;
            }
            j++;
        }
        if(max_==0){
            cout << -1 << endl;
            return 0;
        }
        ans.push_front(max_);
        b[index]=0;
    }
    for(int i=0; i<N; i++){
        cout << ans[i] << endl;
    }
}

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

print(" ".join(list(map(str,a))))
def insertionSort(A,N):
    for i in range(1,N):
        v = A[i]
        j = i-1
        while j>=0 and A[j]>v:
            A[j+1]=A[j]
            j-=1
        A[j+1]=v
        print(" ".join(list(map(str,A))))

insertionSort(a,n)


Measured memory_bytes: 5604
#include<iostream>
#include<cmath>
#include<vector>
#include<queue>
#include<algorithm>
#include <stack>
#include<set>
#include<cstring>
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
#include <string.h>
#include<iterator>
#include <map>
using namespace std;
// bool cmp(long long a, long long b){
//     return a > b;
// }
int used[205000];
set<long long> sets[205000];
queue<long long> q;
int n;
int a[100500];
int tree[405004];
long long u = 0, d = 0, r = 0, l = 0;
void build_tree(int v, int tl, int tr) {
    if (tl == tr) {
        tree[v] = a[tl];
    } else {
        int tm = (tl + tr) / 2;
        build_tree(v * 2, tl, tm);
        build_tree(v * 2 + 1, tm + 1, tr);
        tree[v] = tree[v * 2] + tree[v * 2 + 1];
    }
}
int get_sum(int l, int r, int v, int tl, int tr) {
    //вариант 1
    if (l <= tl && tr <= r) {
        return tree[v];
    }
    if (tr < l || r < tl) {
        return 0;
    }
    int tm = (tl + tr) / 2;
    return get_sum(l, r, v * 2,     tl,     tm)
           + get_sum(l, r, v * 2 + 1, tm + 1, tr);
}
void update(int idx, int val, int v, int tl, int tr) {
    //вариант 1
    if (idx <= tl && tr <= idx) {    //То же, что и idx == tl == tr
        a[idx] = val;
        tree[v] = val;
        return;
    }
    if (tr < idx || idx < tl) {
        return;
    }
    int tm = (tl + tr) / 2;
    update(idx, val, v * 2,     tl,     tm);
    update(idx, val, v * 2 + 1, tm + 1, tr);
    tree[v] = (tree[v * 2] + tree[v * 2 + 1]) % (long long)(1e9 + 7);
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(0);
    long long t, ch, i, curr, p = 1, x, y, weight, j, k = 0, n, m = 1, ch1, count, ans = 0;
   // long long a, b;
    int fl, fl1, fl2, fl3;
    string s;
//    cin >> t;
    long long c, e, f;
    long long time;
//    for (auto test_case = 0; test_case < t; test_case++) {
        cin >> n;
        long long minim = 0;
        for (i = 0; i < n; i++){
            cin >> ch;
            if (ch > minim)
                minim = ch;
            else{
                ans += minim - ch;
            }
        }
        cout << ans;
//    }

    return 0;
}
/*2
5
1 1 1 1 1
1
10
 1
 7
5 6 6 1 3 5 4

 */

Measured memory_bytes: 13276
# solution

from collections import deque

data = int(input())
g = tuple(set() for _ in range(data))
for _ in range(data - 1):
    u, v, w = map(int, input().split())
    u -= 1
    v -= 1
    g[u].add((v, w))
    g[v].add((u, w))

d = [-1] * data
d[0] = 0

q = deque()
q.append(0)

while q:
    v = q.popleft()
    for u, w in g[v]:
        if d[u] != -1:
            continue
        d[u] = (d[v] + w) % 2
        q.append(u)

print(*d, sep='\n')


Measured memory_bytes: 52228
# -*- coding:utf-8 -*-

def solve():
    X, N = list(map(int, input().split()))
    Ps = list(map(int, input().split()))

    if N == 0:
        print(X)
        return

    setP = set(Ps)

    ans = float("inf")
    for x in range(0, 102):
        if not x in setP:
            if abs(X-ans) > abs(X-x):
                ans = x

    print(ans)


if __name__ == "__main__":
    solve()


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

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

	int mindiff=t.size();
	int tsize=t.size();
	int maxloop=s.size()-t.size();
	//fprintf(stderr,"%d\n",maxloop);
	for (int i=0;i<=maxloop;++i)
	{
		int diff=0;
		for (int j=0;j<tsize;++j)
		{
			if (s[i+j]!=t[j])
			{
				++diff;
			}
		}
		mindiff=min(mindiff,diff);
	}
	cout << mindiff << endl;
}







Measured memory_bytes: 3620
#include<stdio.h>

struct Card{
  char suit;
  char value;
};

void bubblesort(struct Card *A,int n){
  int i,j;
  struct Card x;
  for(i=0;i<n;i++){
    for(j=n-1;j>=i+1;j--){
      if(A[j].value<A[j-1].value) {
	x=A[j];
	A[j]=A[j-1];
	A[j-1]=x;
      }
    }
  }
  for(i=0;i<n;i++){
    if(i==n-1){
      printf("%c%c\n",A[i].suit,A[i].value);
      break;
    }
    printf("%c%c ",A[i].suit,A[i].value);
  }
}

void selectionsort(struct Card *A,int n){
  int i,j,min;
  struct Card x;
  for(i=0;i<n;i++){
    min=i;
    for(j=i;j<n;j++){
      if(A[j].value<A[min].value) 
	min=j;
    }
    x=A[i];
    A[i]=A[min];
    A[min]=x;
  }
  
  for(i=0;i<n;i++){
    if(i==n-1){
      printf("%c%c\n",A[i].suit,A[i].value);
      break;
    }
    printf("%c%c ",A[i].suit,A[i].value);
  }
}


int main(){
  struct Card C1[101], C2[101],C3[101],C4[101];
  int n, i,a=0;
  char ch;

  scanf("%d%c", &n, &ch);
  for ( i = 0; i <n; i++ ){
    scanf("%c%c%c", &C1[i].suit, &C1[i].value, &ch);
    C2[i].suit=C1[i].suit;
    C2[i].value=C1[i].value;
  }
 
  bubblesort(C1,n);
  printf("Stable\n");
  selectionsort(C2,n);

  for(i=0;i<n;i++){
    if(C1[i].suit!=C2[i].suit) {
      printf("Not stable\n");
      a=1;
      break;
    }
  }
  if(a==0)printf("Stable\n");

  return 0;
}

Measured memory_bytes: 608
#include <bits/stdc++.h>
    
#define int long long
    
#define REP(i,n) for(int i=0;i<n;i++)
#define FOR(i,m,n) for(int i=m;i<n;i++)
#define FORR(i,m,n) for(int i=m;i>=n;i--)
#define pb(x) push_back(x) 
#define SORT(x) sort((x).begin(),(x).end())
#define INF 99999999999
    
using namespace std;
    
bool operator> (const string s1, const string s2){
    int i=0;
    while(s1[i]==s2[i]){
        i++;
    }
    
    return s1[i]-'a' > s2[i]-'a';
};
    
int32_t main(){
    string str;
    int k, n;
    cin >> str >> k;
    n = str.length();
    
    priority_queue<string, vector<string>, greater<string> > q;
    set<string> se;
    REP(i, n){
        REP(j, k+1){
            if(j+i<n){
                string s = str.substr(i, j+1);
                if(se.find(s)==se.end()){
                    q.push(s);
                    se.insert(s);
                }
            }
        }
    }
    
    while(--k){
        q.pop();
    }
    cout << q.top() << endl;
}

Measured memory_bytes: 2300
def bfs(n,e,fordfs):
    #点の数、スタートの点、有向グラフ
    W = [-1]*n
    #各点の状態量、最短距離とか,見たかどうかとか
    W[e] = 0
    que = deque()
    que.append(e)
    len = [0]*n
    while que:
        now = que.popleft()
        nowv = W[now]
        nowlen = len[now]
        for ne in fordfs[now]:
            if nowv == W[ne]:
                #ループが嫌な時
                return -1
            elif W[ne] == -1:
                W[ne] = (nowv+1) % 2
                len[ne] = nowlen+1
                que.append(ne)
    return len

def examD():
    N = I()
    v = [[] for i in range(N)]
    for i in range(N-1):
        a, b = LI()
        v[a-1].append(b-1)
        v[b-1].append(a-1)
    fennec = bfs(N,0,v)
    snuke = bfs(N,N-1,v)
    cur = 0
    for i in range(N):
        if fennec[i]>snuke[i]:
            cur +=1
    if cur>=(N+1)//2:
        ans = "Snuke"
    else:
        ans = "Fennec"
    print(ans)

import sys
import copy
import bisect
import heapq
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
mod = 10**9 + 7
inf = float('inf')

examD()


Measured memory_bytes: 60208
#include<stdio.h>
int selectionSort(int A[], int N){
 int i,j,t,sw=0,minj;
 for(i=0;i<N-1;i++){
  minj=i;
  for(j=i;j<N;j++){
   if(A[j]<A[minj])minj=j;
    }
  t= A[i];A[i]=A[minj];A[minj]=t;
  if(i!=minj)sw++;
  }
 return sw;
}
int main(){
 int A[100],N,i,sw;

 scanf("%d",&N);
 for(i=0;i<N;i++) scanf("%d",&A[i]);
   
  sw=selectionSort(A,N);
  for(i=0;i<N;i++){
 if(i>0)printf(" ");
   printf("%d",A[i]);
   }
  printf("\n");
  printf("%d\n",sw);
 return 0;
}

Measured memory_bytes: 2720
import java.util.*;
import java.io.*;

class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int card = Integer.parseInt(br.readLine());
        String name;
        int t_point=0;
        int h_point=0;
        while ((name=br.readLine())!=null) {
        	if (card>1000 || name.length()>100) break;
            String[] c_name = name.split(" ");
            String tarou = c_name[0];
            String hanako = c_name[1];
            
            int judge = tarou.compareTo(hanako);
            
            if(judge<0){
                h_point += 3;
            }else if(judge>0){
                t_point += 3;
            }else{
                h_point += 1;
                t_point += 1;
            }
        }
        System.out.println(t_point+" "+h_point);
    }
}

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

int main() {

  int N;
  string S;

  cin >> N >> S;

    int64_t count = 0;

    char color1, color2, color3;

    map<char, int64_t> m;

    for(int i = 0; i < N; i++){
        color1 = S[i];
        m[color1]++;
        for(int j = i + 1; j + j - i< N; j++){
            color2 = S[j];
            if(color2 != color1){
                color3 = S[j + j - i];
                if(color3 != color1 && color3 != color2){
                    count++;
                }
            }
        }
    }
    count = m['R'] * m['G'] * m['B'] - count;
    cout << count << endl;
}


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

int main(){
    int n,cnt=0;
    cin>>n;
    string s;
    cin>>s;
    for(int i=0;i<n-1;i++){
        if(s[i]==s[i+1])
        {
            s[i]=-1;
        }
    }
    if(s[n-2]==s[n-1]){s[n-2]=-1;}
    for(int j=0;j<n;j++)
    {
        if(s[j]!=-1){cnt++;}
    }
    cout<<cnt;
    return 0;

}

Measured memory_bytes: 512