akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
using namespace std;

int u;
int uni[100010];




int oya(int a){
if (uni[a]<0){
    return a;
}
else{
    uni[a]=oya(uni[a]);
    return oya(uni[a]);
}
}
 
bool ren(int a,int b){
    a=oya(a);
    b=oya(b);
    if(a==b){
    return  false;//renketu
    }
    else{
    return true;   //not renketu
    }
}

void con(int a,int b){
	if(ren(a,b)){
		a=oya(a);
		uni[a]=b;
	}
	
}



int main() {
	int n,q;
cin>>n>>q;
	for(u=0;u<n;u++){
	uni[u]=-1;
	}

for(int u=0;u<q;u++){
	int j,a,b;
cin>>j>>a>>b;
if(j==0){
	con(a,b);
}
else{
	if(ren(a,b)==true){
		cout<<0<<endl;
	}
	else{
		cout<<1<<endl;
	}
	
}
	
	
}


	return 0;
}

Measured memory_bytes: 1324
#include<iostream>
#include<string>
using namespace std;
int main(){
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	int k;
	cin>>k;
	string s;
	cin>>s;
	if(k<s.size()){
		for(int i=0;i<k;i++){
			cout<<s[i];
		}
		cout<<"...";
	}
	else{
		cout<<s<<endl;
	}
	return 0;
}

Measured memory_bytes: 3620
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main(void){

	string ANS;
	cin >> ANS;
	int N, cnt = 0;
	cin >> N;
	for(int i = 0; i < N; i++){
		string S;
		cin >> S;
		for(int j = 0; j < 10; j++){
			string L;
			int flag = 0;
			for(int k = 0; k < ANS.size(); k++){
				if((j + k) < 10)
					L += S[j+k];
				else if((j + k) >= 10)L += S[j+k-10];
				//cout << "S:" << S << endl;
				//cout << "L:" << L << endl;
				if(ANS == L){flag++; break;}
			}
			if(flag == 1){cnt++; break;}
		}
	}
	cout << cnt << endl;
}

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

int main(){
  int A,B,C,D;
  cin >> A >> B >> C >>D;
  if((C+B-1)/B > (A+D-1)/D){
    cout<<"No"<<endl;
    return 0;
  }
    cout<<"Yes"<<endl;
}


Measured memory_bytes: 3624
#include<iostream>
#include<vector>
#include<map>
#include<tuple>
#include<string>
#include<cmath>
#include<climits>
#include<algorithm>
#include<bitset>
#include<set>
#include<queue>
using namespace std;  
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
#define rep(i,n) for(ll i=0;i<(n);i++)  
#define pii pair<int,int>
#define piii pair<int,pii>
#define mp make_pair
#define pb push_back  
#define ALL(a) (a).begin(),(a).end()
#define FST first
#define SEC second  
const int INF = (INT_MAX/2);
const ll LLINF = (LLONG_MAX/2);
const double eps = 1e-5;
const double PI = M_PI;  
#define DEB cerr<<"!"<<endl
#define SHOW(a,b) cerr<<(a)<<" "<<(b)<<endl
#define SHOWARRAY(ar,i,j) REP(a,i)REP(b,j)cerr<<ar[a][b]<<((b==j-1)?((a==i-1)?("\n\n"):("\n")):(" "))
#define DIV 1000000007
inline ll pow(ll x,ll n,ll m){ll r=1;while(n>0){if((n&1)==1)r=r*x%m; x=x*x%m;n>>=1;}return r%m;}
using namespace std;

vi G[100001];
int l[100001];

ll n,m;
map<int,int> mii;
void label(int i,int p){
  if(l[i] == !p){
    cout << n * (n-1) / 2 - m << endl;
    exit(0);
  }else if(l[i] == -1){
    l[i] = p; mii[p]++;
    rep(j,G[i].size())
      label(G[i][j],!p);
  }
  return;
}

int main(){
  cin >> n >> m;
  fill_n(l,100001,-1);
  rep(i,m){
    int a,b; cin >> a >> b;
    G[a].pb(b);
    G[b].pb(a);
  }
  
  label(1,0);
  cout << ll(mii[0])*mii[1] - m << endl;
  return 0;
}

Measured memory_bytes: 6656
import java.util.*;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		
	int N = sc.nextInt();
	int A = sc.nextInt();
	int B = sc.nextInt();
	int C = sc.nextInt();
	int[] Di = new int[N];
	
	for(int i=0;i < N;i++){
		Di[i] = sc.nextInt();
	}
	
	Arrays.sort(Di);
	int pc = C;
	int pp = A;
	
	for(int i=N-1;i > -1; i--){
		if(pc / pp <= (pc + Di[i]) / (pp + B)){
			pc = pc + Di[i];
			pp = pp + B;
		}
	}
	System.out.println(pc/pp);
}
}

Measured memory_bytes: 18148
N,K,S=[int(x) for x in input().rstrip().split()]
ans=[]
if S==10**9:
    for i in range(N):
        if i+1<=K:
            ans.append(S)
        else:
            ans.append(1)
else:
    for i in range(N):
        if i+1<=K:
            ans.append(S)
        else:
            ans.append(S+1)
print(*ans)



Measured memory_bytes: 9584
n = int(input())
a = [int(i) for i in input().split()]

ball_count = [0] * (n + 1)

for i in a:
    ball_count[i] += 1
def nCr(i):
    if i<=1:
        return 0
    else:
        return i*(i-1)//2

def get_total(ball_count):
    ans = 0
    for i in ball_count:
        ans += nCr(i)
    return ans


total = get_total(ball_count)
for i in range(1, n + 1):
    num = ball_count[a[i - 1]]
    ans = total - nCr(num) + nCr(num-1)
    print(ans)


Measured memory_bytes: 32236
#include<iostream>
#include<algorithm>
using namespace std;
int n;
long a[111],x;
main()
{
	cin>>n>>x;
	for(int i=0;i<n;i++)cin>>a[i];
	sort(a,a+n);
	int cnt=0;long sum=0;
	for(int i=0;i<n;i++)
	{
		cnt++;
		sum+=a[i];
		if(sum>x)break;
	}
	cout<<(cnt-(sum!=x))<<endl;
}


Measured memory_bytes: 256
#include <iostream>
#include <string>
#include <vector>
#include <bits/stdc++.h>
#define ll long long
#define SIZE_OF_ARRAY(array) (sizeof(array)/sizeof(array[0]))

using namespace std;

int gcd(int x, int y) { return (x % y)? gcd(y, x % y): y; }

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

    for (int i = 0; i < 1250; i++)
    {
      int A=i,B=i;
      if(A*8/100==a && B/10==b){
        cout<<i<<endl;
        return 0;
      }
    }
    

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


Measured memory_bytes: 256
#define _USE_MATH_DEFINES
#include <iomanip>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <tuple>
#include <climits>
#include <algorithm>
#include <cmath>
using namespace std;

typedef long long LL;
typedef vector<int> VI;
typedef vector<double> VD;
typedef vector<LL> VLL;
typedef vector<string> VS;
typedef vector<bool> VB;
typedef vector<vector<int>> VVI;
typedef vector<vector<bool>> VVB;
typedef vector<vector<double>> VVD;

#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define all(a) (a).begin(),(a).end()

const int MOD = 1000000007;

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

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

int main(){
	int a;
	string s;
	cin>>a>>s;
	cout<<(a<3200?"red":s)<<endl;
	return 0;
}


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

#define debug(a) cerr << #a << ": " << a << '\n'
#define endl '\n'

typedef long long ll;
const ll maxn = 200010;

void solve(ll case_no)
{
    ll n;
    cin >> n;

    ll m = 3 * n;
    vector<ll> arr(m);
    for (auto &i : arr)
        cin >> i;

    ll res = 0;
    sort(arr.rbegin(), arr.rend());
    for (ll i = 0, j = 1; i < n; i++, j += 2)
        res += arr[j];

    cout << res << endl;
}

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

    ll test_cnt = 1, case_no = 1;
    // cin >> test_cnt;
    while (case_no <= test_cnt)
        solve(case_no++);

    return 0;
}

Measured memory_bytes: 2560
function f()
    N = parse(Int,readline())
    A = parse.(Int,split(readline()))
    B = parse.(Int,split(readline()))
    
    tot = 0
    for i in 1:N
        a = min(A[i], B[i])
        aa = B[i] - a
        b = min(A[i+1], aa)
        A[i+1] -= b
        tot += a + b
    end
    println(tot)
end

f()

Measured memory_bytes: 200812
#include<bits/stdc++.h>
using namespace std;
int n,i,k=4,f,s[123456];string o;
int main(){
    cin>>n>>o;
    for(i=0;i<n;i++)o[i]&=1;
    for(;k--;){
        s[0]=k>>1;
        s[1]=k&1;
        for(i=2;i<n;i++)s[i]=s[i-1]^o[i-1]^s[i-2];
        for(i=n,f=1;i--&&f;)f^=s[i]^o[i]^s[(n+i-1)%n]^s[(i+1)%n];
        if(f){
            for(i=0;i<n;i++)cout<<"WS"[s[i]];
            cout<<endl;
            return 0;
        }
    }
    cout<<-1<<endl;
    return 0;
}

Measured memory_bytes: 1024
using System;
using System.Linq;
using System.Collections.Generic;
using static System.Console;
using System.Text;
using System.IO;
using static System.Math;
using System.Numerics;

namespace AtCoder
{
    public class Program
    {
        static public long[] Sarray() { return ReadLine().Split().Select(long.Parse).ToArray(); }
        static public List<long> Slist() { return ReadLine().Split().Select(long.Parse).ToList(); }
        static public (T1 a, T2 b) Slice<T1, T2>()
        {
            var t = ReadLine().Split();
            return (
            (T1)Convert.ChangeType(t[0], typeof(T1)),
            (T2)Convert.ChangeType(t[1], typeof(T2)));
        }
        static public (T a, T b) Slice2<T>()
        {
            var t = ReadLine().Split();
            return (
            (T)Convert.ChangeType(t[0], typeof(T)),
            (T)Convert.ChangeType(t[1], typeof(T)));
        }
        static public (T a, T b, T c) Slice3<T>()
        {
            var t = ReadLine().Split();
            return (
            (T)Convert.ChangeType(t[0], typeof(T)),
            (T)Convert.ChangeType(t[1], typeof(T)),
            (T)Convert.ChangeType(t[2], typeof(T)));
        }
        static long Mod = (long)1e9 + 7;
        public static void Main(string[] args)
        {
            //SetOut(new StreamWriter(OpenStandardOutput()) { AutoFlush = false });
            Solve();
            //Out.Flush();
            Read();
        }
        static List<int>[] graph;
        static void Solve()
        {
            (long a, long b, long x) = Slice3<long>();
            if (a == 0)
            {
                WriteLine(b / x + 1);
                return;
            }
            var ans = b / x - (a - 1) / x;
            WriteLine(ans);
        }
    }
}

Measured memory_bytes: 27536
#include <stdio.h>
#include <math.h>

int main(){
    double x1, y1, x2, y2, distance;
    scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2);
    distance=sqrt((pow(x2-x1, 2)+pow(y2-y1, 2)));
    printf("%f\n", distance);

    return 0;
}


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

using ll = long long;
#define int long long
using P = pair<int, int>;

#define LOG(variable) cerr << #variable":\t" << (variable) << "\n"
#define LOGCON(i, container) for(int (i) = 0; (i) < (container).size(); ++(i)) cerr << (i) << ":\t" << (container)[(i)] << "\n"
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define REPS(i, r, n) for (int i = (r); i < (n); ++i)
#define REPR(i, n) for(int i = (n); i >= 0; --i) // from n to 0
#define REPRS(i, n, r) for(int i = (n); i >= (r); --i) // from n to r
#define REPOBJ(itr, obj) for(auto itr = (obj).begin(); itr != (obj).end() ; ++itr)
#define REPROBJ(itr, obj) for(auto itr = (obj).rbegin(), e = (obj).rend(); itr != e; ++itr)
#define COUTB(x) cout << (x) << "\n"
#define COUTS(x) cout << (x) << " "
#define PB push_back
#define SORT(obj) sort((obj).begin(), (obj).end())
#define SORTR(obj) sort((obj).begin(), (obj).end(), greater<>())
#define ALL(obj) (obj).begin(), (obj).end()
#define MOD 1000000007
#define PI (acos(-1))
template<typename T = int>
T in() {T a; cin >> a; return a;}
/***** MAIN *****/
signed main() {
  int n, m, k; cin >> n >> m >> k;
  vector<int> a_cum_sum(n+1, 0LL), b_cum_sum(m+1, 0LL);
  // a_cum_sum[i] は、A配列の[0, i)の範囲を示す。
  // 開区間を用いているので n+1　のサイズの配列が必要
  for(int i = 0; i < n; ++i) {
    int tmp; cin >> tmp;
    a_cum_sum[i+1] = a_cum_sum[i] + tmp;
  }
  for(int i = 0; i < m; ++i) {
    int tmp; cin >> tmp;
    b_cum_sum[i+1] = b_cum_sum[i] + tmp;
  }
  int ans = 0;
  // A配列から取る要素数を0〜n個まで試す
  for(int i = 0; i < n+1; ++i) {
    if(a_cum_sum[i] > k) break; // こしてしまったら終了
    int rest = k - a_cum_sum[i];
    int b_count = upper_bound(ALL(b_cum_sum), rest) - b_cum_sum.begin();
    // b_cum_sumで初めてrestより大きくなった要素のindexが返る
    // 5が返ったとしたら、4まではこしてないということになる
    // ということは、インデックスで考えて[0, 4)の区間の本を読めるので、4冊。つまり、b_count-1冊
    ans = max(ans, i+b_count-1);
  }
  cout << ans;
  cout << "\n";
  return 0;
}
/***** MAIN *****/

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

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

using namespace std;

int main(void)
{
    const int N_MAX = 100;
    int N;
    int a[N_MAX];
    cin >> N;
    REP(i, N) cin >> a[i];
    int s = accumulate(a, a + N, 0);
    int b[N_MAX];
    REP(i, N) b[i] = abs(a[i] * N - s);
    cout << (min_element(b, b + N) - b) << endl;
    return 0;
}

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

class Program
{
    static void Main(string[] args)
    {
        var n = int.Parse(Console.ReadLine());
        var arr = Console.ReadLine().Split().Select(int.Parse).ToArray();
        var max = 10 * 10 * 10 * 10 * 10 * 10;
        var count = new int[max + 1];
        for (int i = 0; i < n; i++)
        {
            count[arr[i]]++;
        }
        var isMultiples = Enumerable.Repeat(true, max + 1).ToArray();
        foreach (var value in arr.Distinct())
        {
            for (int i = value * 2; i <= max; i += value)
                isMultiples[i] = false;
        }
        var answer = 0;
        for (int i = 0; i < n; i++)
        {
            if (isMultiples[arr[i]] && count[arr[i]] == 1) answer++;
        }
        var writer = new StreamWriter(Console.OpenStandardOutput()) {AutoFlush = false};
        Console.SetOut(writer);
        Console.WriteLine(answer);
        Console.Out.Flush();
    }
}

Measured memory_bytes: 53420
n = int(input())
p = [int(i) for i in input().split()]

count = 0
for i, pi in enumerate(p):
    if (i+1) != pi:
        count+=1
    if count > 2:
        break

if count == 2 or count == 0:
    print("YES")
else:
    print("NO")

Measured memory_bytes: 3060
import collections
res=[]
alphabet=list("abcdefghijklmnopqrstuvwxyz")
n=int(input())
S=[collections.Counter(list(input())) for i in range(n)]
for c in alphabet:
    res.append(min(dic[c] for dic in S))
print("".join(alphabet[i]*res[i] for i in range(26)))

Measured memory_bytes: 3316
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define vct vector<ll>
#define umap unordered_map<ll,ll>
#define mpp map<ll,ll>
#define stt set<ll>
#define pir pair<ll,ll>
#define vpp vector<pair<ll,ll> >

ll poww(ll x,ll y,ll m){   
    ll res=1;
    while(y){if(y%2==0){x=(x*x)%m;y=y/2;}else{res=(res*x)%m;y--;}}
    return res;
}
void prt(vct v)
{
    for(ll i=0;i<v.size();i++)cout<<v[i]<<"\n";
    // cout<<"\n";
}
vct siev(ll n)
{
    vct ans;ll ar[n+1];
    memset(ar,-1,sizeof(ar));ar[0]=0;ar[1]=0;
    for(ll i=2;i<=n;i++)
    {if(ar[i]==-1){ans.push_back(i);ar[i]=1;for(ll j=2*i;j<=n;j=j+i)ar[j]=0;}}
    return ans;
}
ll isprime(ll n)
{
    if(n==1||n==0)return 0;
    for(ll i=2;i<=sqrt(n);i++)if(n%i==0)return 0;
    return 1;
}
ll etf(ll n) 
{
    ll result = n;
    for (ll i = 2; i * i <= n; i++) {
        if(n % i == 0) {
            while(n % i == 0)n /= i;
            result -= result / i;
        }
    }
    if(n > 1)result -= result / n;
    return result;
}
vct divsors(ll n)
{
    vct ans;//ans.push_back(1);
    for(ll i=1;i<=sqrt(n);i++)
    {if(n%i==0){ans.push_back(i);if(i!=(n/i))ans.push_back(n/i);}}
    // sort(ans.begin(),ans.end());
    return ans;
}
ll cnd(ll n){ll cnt=0;while(n){cnt++;n=n/10;}return cnt;}
ll t,m,n;
ll t1,t2,k;
ll mod=1000000007;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    cin>>n;
    vct v(n);
    ll su=0;
    for(ll i=0;i<n;i++){
    cin>>v[i];su+=v[i];}
    ll ans=0;
    for(ll i=0;i<n;i++)
    {
        su-=v[i];
        ans+=(su*v[i]);
    }
    cout<<ans;
    
    
    
}

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

int main()
{
    int n,num;
   cin>>n;
   vector<int>t;
   long long s1=0,s2=0;
   for(int i=0;i<n;i++)
   {
       cin>>num;
       t.push_back(num);
   }
   for(int i=0;i<n;i++)
   {
       s1+=t[i];
   }
   int m,p,x;
   cin>>m;
    for(int i=0;i<m;i++)
    {
       s2=s1;
       cin>>p;
       cin>>x;
       s2-=t[p-1];
       s2+=x;
       cout<<s2<<endl;
    }
       
    return 0;
}

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

const int MOD = 1000000007;
const int INF = 1e9;

int main(){
  int n;
  const int max_n = 2 * 1e5;
  cin >> n;

  int cnt[10][10] = {};
  int length = 1;
  int f,l;

  for(int i = 1; i <= n; i++){
    if(i==10) length *= 10;
    if(i==1e2) length *= 10;
    if(i==1e3) length *= 10;
    if(i==1e4) length *= 10;
    if(i==1e5) length *= 10;

    cnt[i%10][(i/length)%10] ++;
    // cout << "i = " << i << ", ue = " << (i/length)%10 << ", sita = " << i%10 << endl;
  }
  // cout << "---" << endl;
  length = 1;
  long long ans = 0;
  for(int i = 1; i <= n; i++){
    if(i==10) length *= 10;
    if(i==1e2) length *= 10;
    if(i==1e3) length *= 10;
    if(i==1e4) length *= 10;
    if(i==1e5) length *= 10;

    ans += cnt[(i/length)%10][i%10];
    // if(cnt[(i/length)%10][i%10]>0) {
    //   cout << "i=" << i << ", cnt = " << cnt[(i/length)%10][i%10] << endl;
    // }
  }
  cout << ans << endl;

  return 0;
}

Measured memory_bytes: 3644
N=int(input())
A=[int(i) for i in input().split()]

up = 1
for a in A:
    up*=a

down = 0
for i in range(N):
    buf=1
    for j in range(N):
        if i==j: continue
        buf*=A[j]
    down+=buf
print(up/down)


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

int main(){
	int N, Y;
	cin >> N >> Y;
	Y /= 1000;
	rep(i,Y/10+2)rep(j,Y/5+2){
		int k = N-i-j;
		if (k < 0 ) break;
		if (10*i+5*j+k == Y) {
			cout << i << " " << j << " " << k << endl;
			return 0;
		}
	}
	cout << "-1 -1 -1" << endl;

	return 0;
}


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

int main() {
  int n;
  int result = 0;
  cin >> n;
  vector<int> vec(n);
  for(int i = 0; i < n; i++) {
    cin >> vec.at(i);
  }

  sort(vec.begin(), vec.end());
  reverse(vec.begin(), vec.end());

  for(int i = 0; i < n; i++) {
    if((i % 2) == 0) {
      result += vec.at(i);
    }
    else {
      result -= vec.at(i);
    }
  }

  cout << result << endl;

}


Measured memory_bytes: 256
A,B,C,X,Y = map(int, input().split())

cand1 = A*X + B*Y
cand2 = 2*C*min(X,Y) + A * max(0,X-Y) + B * max(0,Y-X) 
cand3 = 2*C*max(X,Y)

print(min(cand1,cand2,cand3))

Measured memory_bytes: 3060
#include<bits/stdc++.h>
using namespace std;
#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, n) for (int i = 0; i < n; ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
#define ll long long

//
typedef pair<int, int> pii;
// typedef vector<int> vi;
// typedef vector<pii> vpi;
// typedef vector<vi> vvi;
// typedef long long i64;
// typedef vector<i64> vi64;
// typedef vector<vi64> vvi64;
// typedef pair<i64, i64> pi64;
// typedef double ld;
typedef  long long ui64;

template<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }
template<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }
// ui64 mx=1000*1000*1000+3;
// ui64 dp[mx];
int dp[100000];
bool vis[100000];
int dfs(int n,int dis,vector<int>g[])
{
	if(vis[n])
	return dp[n];
	vis[n]=true;
	for(auto i:g[n])
	{
		if(i==n)
		continue;


		dp[n]=max(dp[n],dfs(i,dis+1,g)+1);
	}
	return dp[n];
}
int main()
{
	ui64 n,m;
	cin>>n>>m;
vector<int>g[n+1];
	forn(i,m)
	{
		ui64 a,b;
		cin>>a>>b;
		g[a].push_back(b);
	}
for1(i,n)
{dp[i]=0;
	// memset(vis,false,sizeof(vis));
dfs(i,0,g);
}
int ans=0;
for1(i,n)
ans=max(ans,dp[i]);

	cout<<ans;
	return 0;
}


Measured memory_bytes: 8960
import java.util.*;
 
public class Main {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long[] nums=new long[n];
        long[] output=new long[n];
        for(int i=0;i<n;i++){
            nums[i]=sc.nextLong();
        }
        output[0]=nums[0];
        long ans=1;
        for(int i=1;i<n;i++){
            output[i]=nums[i]/Euclid(nums[i],output[i-1])*output[i-1];
        }
        System.out.println(output[n-1]);
    }
 
    private static long Euclid(long n, long m) {
        long tmp;
        if(n==0||m==0){
            return Math.max(n,m);
        }
        while (true) {
            if (n == 0) {
                return m;
            } else if (m == 0) {
                return n;
            }
            tmp = n;
            n = m;
            m = tmp;
            n = n % m;
 
        }
    }
}

Measured memory_bytes: 21844
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define UNIQUE(v) v.erase(unique(all(v)), v.end());
#define ZIP(v) sort(all(v)),UNIQUE(v)
#define ADD(a, b) a = (a + b) % mod
#define SUB(a, b) a = (a+mod-b)%mod
#define MUL(a, b) a = (a * b) % mod
#define repi(i,m,n) for(int i = m;i < n;i++)
#define drep(i,n,m) for(int i = n;i >= m;i--)
#define rep(i,n) repi(i,0,n)
#define rrep(i,n) repi(i,1,n+1)
#define chmin(x,y) x = min(x,y)
#define chmax(x,y) x = max(x,y)
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(), v.rend()
#define dmp(x,y) make_pair(x,y)
#define pb(x) push_back(x)
#define fi first
#define se second
typedef pair<int,int> P;
typedef pair<int, P> PP;
typedef pair<P, int> Pi;
typedef vector<int> vi;
typedef deque<int> dq;
const int inf = 1e9+7;
const int INF = 1e18+7;

int a[100000], b[100000];
P p[100000];
signed main(){
	while(1){
		int n;
		scanf("%lld", &n);
		if(n == 0)break;
		rep(i,n)scanf("%lld", &a[i]);
		rep(i,n-1)scanf("%lld", &b[i]);
		rep(i,n-1)p[i] = P(b[i], i);
		sort(p, p+(n-1), greater<P>());
		
		int sum = 0, ans = -1;
		rep(i,n)sum += a[i];
		chmax(ans, sum*n);
		rep(i,n-1){
			int idx = p[i].se, m = n-i-1;
			sum += b[idx];
			chmax(ans, sum*m);
		}
		printf("%lld\n", ans);
		
	}
	return 0;
}





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

#pragma GCC optimize("Ofast")

using namespace std;

typedef long long ll;
typedef long double ld;
mt19937 rnd(time(0));
#define ioss ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define file freopen("avia.in", "r", stdin); freopen("avia.out", "w", stdout);
#define _GLIBCXX_DEBUG
#define s second
#define f first
#define pb push_back
#define add insert
#define del erase
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define pii pair<int,int>
#define res resize
#define PI acos(-1)
const ll INF = 1e9;//9223372036854775807L; //LONG_MAX;
constexpr ll mod = 1e9 + 7;


void solve() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (auto &i : a)cin >> i;
    int k = 0, need = 1;
    for (int i = 0; i < n; i++)if (a[i] == need) k++, need++;
    if (!k)cout << "-1" << '\n';
    else cout << n - k << '\n';
}

signed main() {
    ioss
    //file
    //id.resize(3e5);
    int t = 1;                                                                                                                                                                        //ll
    //cin >> t;
    while (t--) {
        solve();
    }
    return 0;
}


Measured memory_bytes: 1024
import java.io.*;
class Main{
	public static void main(String[]args)throws IOException{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder();
		
		while(true){
			String[] str=br.readLine().split(" ");
			int H=Integer.parseInt(str[0]);
			int W=Integer.parseInt(str[1]);
			
			if(H==0&&W==0) break;
			
			for(int i=0;i<H;i++){
				for(int j=0;j<W;j++){
					sb.append("#");
				}
				sb.append("\n");
			}
			sb.append("\n");
		}
		System.out.print(sb);
	}
}

Measured memory_bytes: 25636
import math
x = int(input())

# 上から減らす
num = math.ceil(x/105)
remain = num * 105 - x

can = False
if remain < num * 5:
  can = True
else:
  # 下から増やす
  num = math.floor(x/100)
  remain = x - num * 100

  if remain < num * 5:
    can = True

if can:
  print(1)
else:
  print(0)

Measured memory_bytes: 3060
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define rep(i, n) for(int(i) = 0; (i) < (n); (i)++)
#define FOR(i, m, n) for(int(i) = (m); (i) < (n); (i)++)
#define All(v) (v).begin(), (v).end()
#define pb push_back
#define MP(a, b) make_pair((a), (b))
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
const int INF = 1 << 30;
const ll LINF = 1LL << 60;
const int MOD = 1e9 + 7;

int main() {
    int N;
    cin >> N;
    vector<int> A(N);
    rep(i, N) { cin >> A[i]; }
    int now = 0;
    int res = 0;
    int ok = 1;
    while(now < N) {
        if(ok)
            res++;
        if(now + 1 < N && A[now + 1] > A[now]) {
            while(now + 1 < N && A[now + 1] >= A[now]) {
                now++;
            }
            now++;
            ok = 1;
        } else if(now + 1 < N && A[now + 1] < A[now]) {
            while(now + 1 < N && A[now + 1] <= A[now]) {
                now++;
            }
            now++;
            ok = 1;
        } else {
            now++;
            ok = 0;
        }
    }
    cout << res << endl;
    return 0;
}

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

#define int long long

#define rep(i,n) for(int i=0;i<(n);i++)
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
typedef vector<int>vint;
typedef pair<int,int>pint;
typedef vector<pint>vpint;

template<typename A,typename B>inline void chmin(A &a,B b){if(a>b)a=b;}
template<typename A,typename B>inline void chmax(A &a,B b){if(a<b)a=b;}

const int mod=1000000007;
inline void add(int &a,int b){
	a+=b;
	if(a>=mod)a-=mod;
}

int N,W;
int w[222];
int acc[222];

int dp[222][11111];
signed main(){
	cin>>N>>W;
	rep(i,N)cin>>w[i];
	sort(w,w+N);reverse(w,w+N);
	for(int i=N-1;i>=0;i--){
		acc[i]=acc[i+1]+w[i];
	}

	dp[0][W]=1;
	rep(i,N){
		rep(j,W+1){
			if(acc[i]<=j)add(dp[N][0],dp[i][j]);
			else{
				add(dp[i+1][j],dp[i][j]);
				if(w[i]<=j)add(dp[i+1][j-w[i]],dp[i][j]);
			}
		}
	}

	cout<<accumulate(dp[N],dp[N]+W+1,0ll)%mod<<endl;
	return 0;
}


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

long long int num_yakusu(long long int N){
    long long int num=0;
    for(long long int i=1;i*i<=N;i++){
        if(i*i==N)num++;
        else if(N%i==0)num+=2;
    }
    return num;
}

long long int num_yakusu_neo(long long int N){
    long long int num=0;
    for(long long int i=2;i*i<=N;i++){
        if(i*i==N)num++;
        else if(N%i==0){
            long long int j = N/i;
            long long int k=N;
            while(k>=i){
                if(k%i==0)k /= i;
                else{k %= i;}
            }
            if(k==1)num++;
            k=N;
            while(k>=j){
                if(k%j==0)k /= j;
                else{k %= j;}
            }
            if(k==1)num++;
    }}
    return num;
}

int main(){
	long long int n;
	cin >> n;
	cout << num_yakusu_neo(n)+num_yakusu(n-1) << endl;
	return 0;
}

Measured memory_bytes: 256
import java.io.*;

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());
        int res = 0;
        for(int i = 1; i <= n; i++){
            res = (res*10+7)%n;
            if(res == 0){
                System.out.println(i);
                System.exit(0);
            }
        }
        System.out.println(-1);
    }
}


Measured memory_bytes: 32728
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <sstream>
#include <string>
#include <utility>
#include <map>
#include <memory>
#include <set>
#include <vector>
#include <deque>
#include <list>
#include <stack>
#include <queue>

using namespace std;

class MergeSort
{
public:
  MergeSort() : cnt(0) {}
  int solve();
  int merge(int left, int mid, int right);
  int mergeSort(int left, int right);
  int showCnt();
  int n, cnt;
  int s[500000];
};

int MergeSort::merge(int left, int mid, int right)
{
  const int infty = 2000000000;
  int n1 = mid - left;
  int n2 = right - mid;

  int *l = new int [n1 + 1];
  int *r = new int [n2 + 1];

  for ( int i = 0; i < n1; i++ )
    l[i] = s[left + i];
  
  for ( int i = 0; i < n2; i++ )
    r[i] = s[mid + i];

  l[n1] = infty;
  r[n2] = infty;

  int i = 0;
  int j = 0;

  for ( int k = left; k < right; k++ )
    {
      cnt++;
      if ( l[i] <= r[j] )
        s[k] = l[i++];
      else
        s[k] = r[j++];
    }

  delete[] l;
  delete[] r;
  
  return 0;
}

int MergeSort::mergeSort(int left, int right)
{
  int mid;

  if ( left + 1 < right )
    {
      mid = (left + right) / 2;
      mergeSort( left, mid );
      mergeSort( mid, right );
      merge( left, mid, right );
    }
  
  return 0;
}

int MergeSort::showCnt()
{
  cout << cnt << endl;
  return 0;
}

int MergeSort::solve()
{
  cin >> n;
  for ( int i = 0; i < n; i++ )
    {
      cin >> s[i];
    }

  mergeSort( 0, n );
  
  for ( int i = 0; i < n; i++ )
    {
      if ( i ) cout << " ";
      cout << s[i];
    }
  cout << endl;

  showCnt();
  
  return 0;
}

int main()
{
  MergeSort ms;

  ms.solve();

  return 0;
}

Measured memory_bytes: 5056
import java.util.*;

class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int t = sc.nextInt();
        int minCost = Integer.MAX_VALUE;
        for(int i = 1;i <= n;i++){
            int cost = sc.nextInt();
            int time = sc.nextInt();
            if(t < time)continue;
            else if(minCost > cost){
                minCost = cost;
            }
        }
        System.out.println(minCost != Integer.MAX_VALUE? minCost:"TLE");
    }
}

Measured memory_bytes: 21972
import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.flush();out.close();
    }
        static class TaskE {
         public void solve(int testNumber, InputReader in, PrintWriter out) {
             int n=in.nextInt();
             long a[]=new long[n];
             for(int i=0;i<n;i++)a[i]=in.nextInt();
             long l=2,r=2;boolean rs=true;
             for(int i=n-1;i>=0;i--){
              long hi=r/a[i],lo=l%a[i]==0?l/a[i]:l/a[i]+1;
              l=lo*a[i];r=hi*a[i];//System.out.println(l+" "+r+" i");
              if(l>r){
               rs=false;break;
              }r=(hi+1)*a[i]-1;//System.out.println(l+" "+r);
             }if(rs){
              out.print(l+" "+r);
             }else out.print("-1");
         }
    }
    static class InputReader {
        BufferedReader br;
        StringTokenizer st;
        public InputReader(InputStream stream) {
            br = new BufferedReader(new InputStreamReader(stream));
            st = null;
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                String s = null;
                try {
                    s = br.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (s == null)
                    return null;
                st = new StringTokenizer(s);
            }
            return st.nextToken();
        }

        boolean hasMoreTokens() {
            while (st == null || !st.hasMoreTokens()) {
                String s = null;
                try {
                    s = br.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (s == null)
                    return false;
                st = new StringTokenizer(s);
            }
            return true;
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }
        public long nextLong() {
            return Long.parseLong(next());
        }
        public double nextDouble() {
            return Double.parseDouble(next());
        }
    }
}

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

using namespace std;

typedef long long int ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

const int INF = 1000000000;
const ll LINF = (ll) 4000000000000000000;
const ll MOD = (ll) 1000000007;
const double PI = acos(1.0);
const int limit = 100010;

#define REP(i,m,n) for(ll i = m; i < (ll)(n); ++i)
#define rep(i,n) REP(i, 0, n)
#define MP make_pair
#define YES(n) cout << ((n) ? "YES" : "NO") << endl
#define Yes(n) cout << ((n) ? "Yes" : "No") << endl
#define Possible(n) cout << ((n) ? "Possible" : "Impossible") << endl
#define NP(v) next_permutation(v.begin(),v.end())
#define smaller_queue  priority_queue <ll, vector<ll>, greater<ll> >
//------------------------------------------------------

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

    for (int i = 0; i < s.length(); i += n) {
        cout << s[i];
    }
    cout << endl;
    return 0;
}



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

#define XGreaterLess(min, max) (min <= X) && (X <= max)

int main(){
  int X;
  cin >> X;
  
  int result = 0;
  
  if(XGreaterLess(1800, 1999)) result = 1;
  else if (XGreaterLess(1600, 1799)) result = 2;
  else if (XGreaterLess(1400, 1599)) result = 3;
  else if (XGreaterLess(1200, 1399)) result = 4;
  else if (XGreaterLess(1000, 1199)) result = 5;
  else if (XGreaterLess( 800,  999)) result = 6;
  else if (XGreaterLess( 600,  799)) result = 7;
  else if (XGreaterLess( 400,  599)) result = 8;
  
  cout << result << endl;
  return 0;
}

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

int main() {
  int N;
  cin >> N;
  vector<int> x(N);
  int min = 101;
  int max = 0;
  for(int i=0; i<N; i++) {
    int a;
    cin >> a;
    if(a<min) min = a;
    if(a>max) max = a;
    x[i] = a;
  }
  int ans = INT_MAX;
  int cost;
  for(int i=min; i<=max; i++) {
    for(int j=0; j<N; j++) {
      int tmp = i-x[j];
      if(tmp < 0) tmp *= -1;
      cost += tmp * tmp;
    }
    if(cost < ans) ans = cost;
    cost = 0;
  }
  cout << ans << endl;
}


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

using namespace std;

int main(){
	
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	
	int n;
	cin >> n;
	vector <int> v(n);
	for(int i = 0; i < n; i++){
		cin >> v[i];
	}
	int sum = accumulate(v.begin(), v.end(), 0);
	float target = (float) sum / n;
	int sol = 0;
	float razlika = 100000.0;
	for(int i = 0; i < n; i++){
		if((float) abs(v[i] - target) < razlika){
			sol = i;
			razlika = (float) abs(v[i] - target);
		}
	}
	cout << sol;
}

Measured memory_bytes: 256
#define DEBUG 0

/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2019-3-30 21:04:45
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef long long ll;

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

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, Q;
string S;
char T[200010];
char D[200010];

int f(int n)
{
  for (auto i = 0; i < Q; i++)
  {
    if (S[n] == T[i])
    {
      if (D[i] == 'L')
      {
        n--;
      }
      else
      {
        n++;
      }
    }
    if (!(0 <= n && n < N))
    {
      return n;
    }
  }
  return n;
}

int main()
{
  cin >> N >> Q >> S;
  for (auto i = 0; i < Q; i++)
  {
    char t, d;
    cin >> t >> d;
    T[i] = t;
    D[i] = d;
  }
  int ok = N;
  int ng = -1;
  while (abs(ok - ng) > 1)
  {
    int t = (ok + ng) / 2;
    if (f(t) == -1)
    {
      ng = t;
    }
    else
    {
      ok = t;
    }
  }
  int left = ok;
  ok = -1;
  ng = N;
  while (abs(ok - ng) > 1)
  {
    int t = (ok + ng) / 2;
    if (f(t) == N)
    {
      ng = t;
    }
    else
    {
      ok = t;
    }
  }
  int right = ok;
#if DEBUG == 1
  cerr << "left = " << left << ", right = " << right << endl;
  cerr << "f(" << left << ") = " << f(left) << endl;
  cerr << "f(" << right << ") = " << f(right) << endl;
#endif
  cout << right - left + 1 << endl;
}

Measured memory_bytes: 900
import sys
import math
#a,b= map(int,input().split())
a=int(input())
li= [int(x) for x in input().split()]
i=j=sum=0
for i in range(len(li)-1):
  for j in range(len(li)-i-1):
    sum+=li[i]*li[i+j+1]
print(sum)




Measured memory_bytes: 3060
//----------------------------おまじない
#pragma GCC optimize ("O3")
#pragma GCC target ("tune=native")
#pragma GCC target ("avx")
//----------------------------
#define FOR(i,j,n) for (int i=(j);i<(n);i++)
#define REP(i,n) for (int i=0;i<(n);i++)
#define REPN(i,n) for (int i=(n);i>=0;i--)
#define I(n) scanf("%d", &(n))
#define LL(n) scanf("%lld", &(n))
#define pb(n) push_back((n))
#define mp(i,j) make_pair((i),(j))
#define eb(i,j) emplace_back((i),(j))
#include <bits/stdc++.h>
using namespace std;

//------------------------------typedef集
typedef vector<int> vi;
typedef pair<int,int> pi;
typedef vector<pi> vpi;
typedef vector<vi> vvi;
typedef vector<vpi> vvpi;
typedef vector<vvi> vvvi;
typedef long long ll;
const int mod = 1000000009;

int n,q,k,a,b,c;
ll dist[100010];
vvpi tree;

int main(){
    I(n);
    tree.resize(n+1);
    REP(i,n-1){
        I(a); I(b); I(c);
        tree[a].eb(b,c);
        tree[b].eb(a,c);
    }
    I(q); I(k);
    deque<int> dq;
    dist[k] = 1;
    dq.pb(k);
    while(!dq.empty()){
        int tp = dq.front();
        dq.pop_front();
        for (auto p: tree[tp]){
            if (!dist[p.first]){
                dq.pb(p.first);
                dist[p.first] = dist[tp] + p.second;
            }
        }
    }
    REP(i,q){
        I(a); I(b);
        printf("%lld\n",(dist[a]+dist[b]-2));
    }
}


Measured memory_bytes: 8820
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<iomanip>
#include<cmath>



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

using namespace std;
string s;
string ans;
int main(){
  cin >> s;
  REP(i,s.size()){
    if(s[i]=='1') ans += "1";
    else if(s[i]=='0') ans += "0";
    else if(ans.size()>0) ans = ans.substr(0,ans.size()-1);
    //cout << ans << endl;
  }
  cout << ans << endl;
  return 0;
}


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

int main()
{
    int n,i;
    int a[1000];

    cin >> n;

    for (i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    for (i = n - 1; i > 0; i--)
    {
        cout << a[i] << " ";
    }
    cout << a[0];
    cout << endl;
}



Measured memory_bytes: 3100
#include<bits/stdc++.h>
#define int long long
#define loop(i, a, b) for(int i = a; i < b; i++)
#define rep(i, a) loop(i, 0, a)
#define all(a) (a).begin(),(a).end()
using namespace std;
const int MOD = 1e9 + 7, INF = 1e9;
using vi = vector <int>;
using vvi = vector <vi>;
//g++ -std==c++14

signed main(){
    string s;
    cin >> s;
    string va = s;
    reverse(s.begin(), s.end());
    rep(i, s.size()){
        if(s[i] == 'b')s[i] = 'd';
        else if(s[i] == 'd')s[i] = 'b';
        else if(s[i] == 'p')s[i] = 'q';
        else if(s[i] == 'q')s[i] = 'p';
    }
    if(s == va)
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
}

Measured memory_bytes: 512
import java.math.BigInteger;
import java.util.*;
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int a[]=new int[1001];
		for(int i=1;i<=n;i++){
			int b=i;
			int j=2;
			while(b!=1){
				if(b%j==0){
					a[j]++;
					b/=j;
				}else{
					j++;
				}
			}
			
			
		}
		long sum=1;
		
		//System.out.println(Arrays.toString(a));
		for(int i=0;i<=1000;i++){
			if(a[i]!=0){
				sum*=(a[i]+1);
			}
			sum%=1000000007;
		}
		System.out.println(sum);
		
		
	}

}

Measured memory_bytes: 21844
#include <algorithm>
#include <cstdio>
#include <climits>
#include <vector>
using namespace std;

int main() {
    while(true) {
        int n,m; scanf("%d%d", &n, &m);
        if(m==0) break;
        vector<vector<pair<int,pair<int,int> > > > graph;
        graph.resize(m);
        for(int i = 0; i < n; i++) {
            int a,b,c,t; scanf("%d%d%d%d", &a, &b, &c, &t); a--; b--;
            graph[a].push_back(make_pair(b,make_pair(c,t)));
            graph[b].push_back(make_pair(a,make_pair(c,t)));
        }
        int k; scanf("%d", &k);
        for(int ii = 0; ii < k; ii++) {
            int p,q,r; scanf("%d%d%d", &p, &q, &r); p--; q--;
            const int INIT = INT_MAX/2;
            const int FIN = INT_MAX/2-1;
            static int segt[1<<8];
            fill(segt, segt+(1<<8), INIT);
            segt[p+(1<<7)] = 0;
            for(int j = p+(1<<7); j > 1; j>>=1) segt[j>>1] = min(segt[j],segt[j^1]);
            while(segt[1] < FIN) {
                int j;
                for(j = 1; j < (1<<7);) if(segt[j*2]<segt[j*2+1]) j=j*2; else j=j*2+1;
                int cur = j&~(1<<7);
                int curcost = segt[j];
                segt[j] = FIN;
                for(; j > 1; j>>=1) segt[j>>1] = min(segt[j],segt[j^1]);
                if(cur == q) {
                    printf("%d\n", curcost);
                    break;
                }
                for(int i = 0; i < (int)graph[cur].size(); i++) {
                    int to = graph[cur][i].first;
                    int ecost = graph[cur][i].second.first;
                    if(r==1) ecost = graph[cur][i].second.second;
                    if(segt[to+(1<<7)] != FIN && segt[to+(1<<7)] > curcost+ecost) {
                        segt[to+(1<<7)] = curcost+ecost;
                        for(j = to+(1<<7); j > 1; j>>=1) segt[j>>1] = min(segt[j],segt[j^1]);
                    }
                }
            }
        }
    }
    return 0;
}

Measured memory_bytes: 912
#include <bits/stdc++.h>
#define MOD 1000000007LL
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

int n;
string s[1000005];
int cnt[1000005],mi[1000005];
vector<P> vec[4];

bool solve(){
	for(int i=0;i<n;i++){
		if(cnt[i]>0 && mi[i]>=0){
			vec[0].push_back(P(cnt[i],mi[i]));
			continue;
		}else if(cnt[i]>0){
			vec[1].push_back(P(cnt[i],mi[i]));
			continue;
		}else if(cnt[i]>mi[i]){
			vec[2].push_back(P(cnt[i],mi[i]));
			continue;
		}else{
			vec[3].push_back(P(cnt[i],mi[i]));
		}
	}
	int cur=0;
	for(int i=0;i<vec[0].size();i++){
		cur+=vec[0][i].first;
	}
	for(int i=0;i<vec[1].size();i++){
		swap(vec[1][i].first,vec[1][i].second);
	}
	sort(vec[1].begin(),vec[1].end());
	reverse(vec[1].begin(),vec[1].end());
	for(int i=0;i<vec[1].size();i++){
		if(-vec[1][i].first>cur){
			return false;
		}
		cur+=vec[1][i].second;
	}
	for(int i=0;i<vec[2].size();i++){
		swap(vec[2][i].first,vec[2][i].second);
	}
	sort(vec[2].begin(),vec[2].end());
	for(int i=0;i<vec[2].size();i++){
		if(-vec[2][i].first>cur){
			return false;
		}
		cur+=vec[2][i].second;
	}

	for(int i=0;i<vec[3].size();i++){
		cur+=vec[3][i].first;
	}
	if(cur==0)return true;
	return false;
}

int main(void){
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		cin >> s[i];
		for(int j=0;j<s[i].size();j++){
			if(s[i][j]=='('){
				cnt[i]++;
			}else{
				cnt[i]--;
			}
			mi[i]=min(mi[i],cnt[i]);
		}
	}
	printf("%s\n",solve()?"Yes":"No");
	return 0;
}


Measured memory_bytes: 50280
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)

def getN():
    return int(input())
def getList():
    return list(map(int, input().split()))
import math
from bisect import bisect_left

INF = 10**10
n, m = getList()

dp = [INF for i in range(1<<n)]
dp[0] = 0

for i in range(m):
    a, b = getList()
    cnums = getList()
    state = 0
    for cn in cnums:
        state += 1<<(cn-1)
    # print(state)
    for i, d in enumerate(dp):
        nstate = i | state
        # print(i, nstate, state)
        # print(dp[nstate] , dp[state])
        if dp[nstate] > dp[i] + a:
            dp[nstate] = dp[i] + a

# print(dp)
if dp[-1] == INF:
    print(-1)
else:
    print(dp[-1])

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

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;

#define F first
#define S second
#define PB push_back
#define MK make_pair
#define REP(i, a, b) for (int i=a; i < b; i++)


bool sort_by(pi c, pi d){
	return c.S < d.S;
}

int main() {
	int n;
	cin >> n;
	int a[n], b[n];
	int tmp = 0;
	REP(i, 0, n){
		cin >> tmp;
		a[i] = tmp;
		b[i] = tmp;
	}
	sort(b, b+n);
	REP(i, 0, n){
		if(a[i] < b[n/2]) cout << b[n/2] << endl;
		else cout << b[n/2-1] << endl;
		/*if(i < n/2 && b[n/2] != a[i]) cout << b[n/2] << endl;
		else if(i < n/2) cout << b[n/2-1] << endl;
		else if(b[n/2-1] != a[i]) cout << b[n/2-1] << endl;
		else cout << b[n/2] << endl;*/
	}

}


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

#define _overload(_1,_2,_3,name,...) name
#define _rep(i,n) _range(i,0,n)
#define _range(i,a,b) for(int i=int(a);i<int(b);++i)
#define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__)

#define _rrep(i,n) _rrange(i,n,0)
#define _rrange(i,a,b) for(int i=int(a)-1;i>=int(b);--i)
#define rrep(...) _overload(__VA_ARGS__,_rrange,_rrep,)(__VA_ARGS__)

#define _all(arg) begin(arg),end(arg)
#define uniq(arg) sort(_all(arg)),(arg).erase(unique(_all(arg)),end(arg))
#define getidx(ary,key) lower_bound(_all(ary),key)-begin(ary)
#define clr(a,b) memset((a),(b),sizeof(a))
#define bit(n) (1LL<<(n))
#define popcount(n) (__builtin_popcountll(n))

using namespace std;

template<class T>bool chmax(T &a, const T &b) { return (a<b)?(a=b,1):0;}
template<class T>bool chmin(T &a, const T &b) { return (b<a)?(a=b,1):0;}

typedef long long ll;
typedef long double R;
const R EPS=1e-9L; // [-1000,1000]->EPS=1e-8 [-10000,10000]->EPS=1e-7
inline int sgn(const R& r){return(r > EPS)-(r < -EPS);}
inline R sq(R x){return sqrt(max(x,0.0L));}

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

// Problem Specific Parameter:

int main() {
  int n, a, b; cin >> n >> a >> b;
  string s; cin >> s;
  int passN = 0;
  int passBN = 0;
  for(int i = 0; i < s.length(); i++) {
    if(s[i] == 'c') cout << "No" << endl;
    else if(s[i] == 'a' && passN < a+b) {
      cout << "Yes" << endl;
      passN++;
    } else if(s[i] == 'b' && passN < a+b && passBN < b) {
      cout << "Yes" << endl;
      passN++;
      passBN++;
    } else {
      cout << "No" << endl;
    }
  }

  return 0;
}

Measured memory_bytes: 896
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool f(int64_t mid, const vector<int64_t> & A, int64_t M) {
    int64_t sum = 0;
    for(int i = 0; i < A.size(); i++) {
        sum += A.size() - (lower_bound(A.begin(), A.end(), mid - A.at(i)) - A.begin());
    }
    return sum >= M;
}

int main() {

    int64_t N, M;
    cin >> N >> M;
    vector<int64_t> A(N);
    for(size_t i = 0; i < N; i++) cin >> A.at(i);

    sort(A.begin(), A.end());

    int64_t ok = 1, ng = 1e6;
    while(ng - ok > 1) {
        int64_t mid = (ng + ok) / 2;
        if(f(mid, A, M)) ok = mid;
        else ng = mid;
    }

    std::vector<int64_t> sum(N + 1, 0);
    for(int i = 0; i < N; i++) sum.at(i + 1) = sum.at(i) + A.at(i);
    int64_t happiness = 0;
    int64_t num = 0;
    for(int i = N - 1; i >= 0 && num < M; i--) {
        int64_t range = upper_bound(A.begin(), A.end(), ok - A.at(i)) - A.begin();
        int64_t count = N - range;
        happiness += (sum.at(N) - sum.at(range)) + count * A.at(i);
        num += count;
    }
    happiness += (M - num) * ok;

    cout << happiness << endl;
    
    return 0;
}

Measured memory_bytes: 1792