akhauriyash/Code-Regression huggingface dataset:
#include <cstdio>
using namespace std;
 
const int MAX_N = 100001;
const int MAX_K = 20;
 
// 連続で x 回半額弁当をゲットしたときに半額弁当を得る確率
double P(int x){
    return 1.0 / (1 << x);
}
 
// dp[i][k] := i 日目で k 回連続ゲットしたときの期待値
double dp[MAX_N+1][MAX_K+1] = {0};
// ans[i] := i 日目の半額弁当を得る個数の期待値
double ans[MAX_N+1] = {0};
 
int main(){
    int n;
    double sum = 0;
     
    dp[0][0] = 1.0;
    for(int i=0 ; i < MAX_N ; i++ ){
        for(int k=0 ; k < MAX_K ; k++ ){
            if( dp[i][k] > 0 ){
                sum += dp[i][k] * P(k);
                 
                // 半額弁当を得るとき
                dp[i+1][k+1] += dp[i][k] * P(k);
                // 半額弁当を得られないとき
                dp[i+1][0] += dp[i][k] * (1.0 - P(k));
                 
            }
        }
        ans[i] = sum;
    }
     
    while( scanf("%d", &n ) , n ){
        printf("%.8f\n", ans[n-1] );
    }
}

Measured memory_bytes: 18252
#include <bits/stdc++.h>
using namespace std;
int main() {
  int x,n;
  cin>>x>>n;
  int arr[n];
  unordered_map<int,int> m;
  for(int i=0;i<n;i++)
  {
      cin>>arr[i];
      m[arr[i]]=1;
  }
  int ans=x;
  int i=0;
  while(true)
  {
int a=x-i;
int b=x+i;
if(m.find(a)==m.end())
{
ans=a;
break;
}
if(m.find(b)==m.end())
{
    ans=b;
    break;
}
i++;
  }
  cout<<ans;
   
}


Measured memory_bytes: 3640
#include<bits/stdc++.h>
using namespace std;
pair<int,int> pii;
vector<int> vec;
#define LL long long 
int main()
{
  LL n,ans=0,x,y;
  cin>>n;
  x=1;
  ans=1+n-2;
  for(int i=2; i<=sqrt(n); i++){
    if(n%i==0){
      ans=min(ans,i+n/i-2);
    }
  }

  cout<<ans<<'\n';

  return 0;
}


Measured memory_bytes: 384
n,m=map(int,input().split())
mod=10**9+7
data=[0]*(n+1)
for i in range(m):
	data[int(input())]=1
dp=[0]*(n+1)
dp[0]=1
dp[1]=0 if data[1] else 1
for i in range(2,n+1):
	if data[i]:
		dp[i]=0
	else:
		dp[i]=(dp[i-1]+dp[i-2])%mod
print(dp[n])


Measured memory_bytes: 44888
n,m,x=map(int,input().split())
C=[]
for inp in range(n):
    C.append([int(i) for i in input().split()])

import itertools
bit=list(itertools.product([0,1], repeat=n))

ans=10**15

for comb in bit:
    pri=0
    R=[0 for i in range(m)]
    for i in range(n):
        if comb[i]==1:
            pri+=C[i][0]
            for q in range(m):
                R[q]+=C[i][q+1]
    if min(R)>=x:
        ans=min(ans,pri)

if ans==10**15:
    print(-1)
else:
    print(ans)

Measured memory_bytes: 9396
N=int(input())
ai=list(map(int,input().split()))
c=int(0)
if N > 2:
  for i in range(N):
    for k in range(i+1,N):
      for l in range(k+1,N):
        if ai[i] != ai[k] and ai[i] != ai[l] and ai[l] != ai[k]:
          if max(ai[i],ai[k],ai[l]) < ai[i] + ai[k] + ai[l] - max(ai[i],ai[k],ai[l]):
             c += 1          
print(c)

Measured memory_bytes: 9140
#include <iostream>
#include <cstdio>
#define int long long
using namespace std;
const int Mod=1e9+7;
const int INF=2005;
int n,f[INF];
signed main()
{
        scanf("%lld",&n); f[0]=1;
        // for (int i=3; i<=n; i++) f[i]=1;
        for (int i=3; i<=n; i++) {
                for (int j=3; j<=i; j++) {
                        f[i]=(f[i]+f[i-j])%Mod;
                        // cout<<j<<" "<<f[j]<<endl;
                }
        }
        cout<<f[n]<<"\n";
        return 0;
}


Measured memory_bytes: 3760
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		new Main().solveA();
		// new Main().solveB();
		// new Main().solveC();
		// new Main().solveD();
	}

	private void solveA() {
		Scanner scanner = null;
		int numN = 0;
		int numA = 0;
		int numB = 0;

		try {
			scanner = new Scanner(System.in);
			numN = scanner.nextInt();
			numA = scanner.nextInt();
			numB = scanner.nextInt();

			System.out.println(Math.min(numA * numN, numB));

		} finally {
			if (scanner != null) {
				scanner.close();
			}
		}
	}

	private void solveB() {
		Scanner scanner = null;
		int lineAB = 0;
		int lineBC = 0;
		int lineCA = 0;

		try {
			scanner = new Scanner(System.in);
			lineAB = scanner.nextInt();

			System.out.println("");

		} finally {
			if (scanner != null) {
				scanner.close();
			}
		}
	}

	private void solveC() {
		Scanner scanner = null;
		int lineAB = 0;
		int lineBC = 0;
		int lineCA = 0;

		try {
			scanner = new Scanner(System.in);
			lineAB = scanner.nextInt();

			System.out.println("");

		} finally {
			if (scanner != null) {
				scanner.close();
			}
		}
	}

	private void solveD() {
		Scanner scanner = null;
		int lineAB = 0;
		int lineBC = 0;
		int lineCA = 0;

		try {
			scanner = new Scanner(System.in);
			lineAB = scanner.nextInt();

			System.out.println("");

		} finally {
			if (scanner != null) {
				scanner.close();
			}
		}
	}
}

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

int main() {
  vector<vector<int>> a(3, vector<int>(3, 0));
  vector<vector<bool>> b(3, vector<bool>(3, false));

  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      cin >> a[i][j];
    }
  }

  int n;
  cin >> n;
  for (int p = 0; p < n; p++) {
    int num;
    cin >> num;
    for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
        if (a[i][j] == num) b[i][j] = true;
      }
    }
  }

  if (b[0][0] && b[0][1] && b[0][2] || b[1][0] && b[1][1] && b[1][2] ||
      b[2][0] && b[2][1] && b[2][2] || b[0][0] && b[1][0] && b[2][0] ||
      b[0][1] && b[1][1] && b[2][1] || b[0][2] && b[1][2] && b[2][2] ||
      b[0][0] && b[1][1] && b[2][2] || b[0][2] && b[1][1] && b[2][0]) {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }
}


Measured memory_bytes: 3620
#include <stdio.h>
#include <stdlib.h>
#define N 10000
#define Q 500

int main(){
  int s[N],t[Q],a[N],i,n,q,j,count=0,b,judge;

  scanf("%d",&n);
  for(i=0;i<n;i++) scanf("%d",&s[i]);
  scanf("%d",&q);
  for(i=0;i<q;i++) scanf("%d",&t[i]);
  
  for(i=0;i<n;i++){
    t[q]=s[i];
    j=0;
    judge=0;
    while(t[j]!=s[i]) j++;
    for(b=0;b<count;b++){
      if(t[j]==a[b]){
	judge=1;
	break;
      }
    }
    if(j==q) continue;
    else if(judge==0){
      a[count]=t[j];
      count++;
    }
  } 

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

  return 0;
}



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

int main() {
	int W, H, x, y, r;
	cin >> W >> H >> x >> y >> r;

	if ((x - r < 0 || x + r >W) || (y - r < 0 || y + r > H)) cout << "No" << endl;
	else cout << "Yes" << endl;

	return 0;
}


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

using namespace std;

int N, M;
int x[100];
int a[10], b[10], c[10];

int dp[100][101][10];

int rec(int l, int r, int myan)
{
  if(~dp[l][r][myan]) return (dp[l][r][myan]);
  if(l + 1 == r) return (x[l] == a[myan]);
  bool ret = false;
  for(int m = l + 1; m < r && !ret; m++)
    ret |= rec(l, m, b[myan]) & rec(m, r, c[myan]);
  return (dp[l][r][myan] = ret);
}


int main()
{
  cin >> N;
  for(int i = 0; i < N; i++) {
    cin >> x[i];
  }
  cin >> M;
  for(int i = 0; i < M; i++) {
    cin >> a[i] >> b[i] >> c[i];
    --b[i];
    --c[i];
  }
  memset(dp, -1, sizeof(dp));
  if(rec(0, N, 0)) cout << "Yes" << endl;
  else cout << "No" << endl;
}

Measured memory_bytes: 3484
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; (i) < (n); ++ (i))
#define loop(i,a,n) for (int i = (a); (i) < (n); ++ (i))
#define ll long long
#define ld long double
#define EPS 0.0000000001
#define INF 1e9
#define MOD 0
//#define int ll
using namespace std;

typedef vector<int> vi;
typedef unsigned long long ull;

signed main(){
    string T,Qu;
    vector<ull> hash,phash,pow,hashrec;
    int n,m,count = 0,r = 0,l = 0;
    ull _b=1000000007;
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> n >> m >> T;
    int sz = T.length();
    hash.assign(sz+1,0);
    phash.assign(sz+1,0);
    pow.assign(sz+1,0);
    pow[0]=1;
    for(int i=0;i<sz;i++){
        pow[i+1]=pow[i]*_b;
    }
    for(int i=0;i<sz;i++){
        hash[i+1]=(hash[i]+T[i])*_b;
        phash[i+1]=T[i]*_b;
    }
    rep(q,m) {
        cin >> Qu;
        if(Qu=="L++") l++;
        if(Qu=="L--") l--;
        if(Qu=="R++") r++;
        if(Qu=="R--") r--;
        hashrec.push_back(hash[r+1]-hash[l]*pow[r+1-l]);
    }
    sort(hashrec.begin(),hashrec.end());
    count++;
    for(int q=1;q<m;q++) {
        if(hashrec[q]!=hashrec[q-1]) count++;
    }
    cout << count << endl;
    return 0;
}



Measured memory_bytes: 14504
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            var NM = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
            var N = NM[0];
            var M = NM[1];
            var ls = new List<int>();
            for (var i = 0; i < N; i++)
            {
                ls.Add(2);
            }
            for (var i = 0; i < M; i++)
            {
                ls.Add(3);
            }

            var ans = 0;
            for (var i = 0; i<ls.Count;i++)
            {
                for (var k = i+1;k<ls.Count;k++)
                {
                    if ((ls[i] + ls[k]) % 2 == 0) ans++;
                }
            }
            Console.WriteLine(ans);
        }
    }
}


Measured memory_bytes: 13268
h,w=map(int,input().split())
r=[]
for _ in range(h):
    a_i=input()
    r.append(a_i)

ans='Possible'
for i in range(h-1):
    for j in range(w-1):
        if r[i][j]=='#'and r[i][j+1]=='#' and r[i+1][j]=='#' and r[i+1][j+1]=='#':
            ans='Impossible'
        elif r[i][j]=='.' and r[i][j+1]=='#' and r[i+1][j]=='#' and r[i+1][j+1]=='#':
            ans='Impossible'
        elif r[i][j]=='#' and r[i][j+1]=='#' and r[i+1][j]=='#' and r[i+1][j+1]=='.':
            ans='Impossible'

print(ans)

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

dp = [[0]*440 for i in range(440)]
s = [[0]*440 for i in range(440)]
for l in range(n):
    s[l][l+1] = a[l]
    for r in range(l+2,n+1):
        s[l][r] = s[l][r-1] + a[r-1]

for width in range(2,n+1):
    for l in range(n-width+1):
        r = l + width
        dp[l][r] = float('inf')
        for m in range(l+1,r):
            dp[l][r] = min(dp[l][r], dp[l][m] + dp[m][r] + s[l][r])

print(dp[0][n])

Measured memory_bytes: 51036
using System;
using System.Linq;//リストの使用
using System.Collections.Generic;
class Program
{
	static void Main()
	{
		string[] input = Console.ReadLine().Split(' ');//Splitで区切り文字を指定して複数個受け取る。
		long n = long.Parse(input[0]);
		long k = long.Parse(input[1]);
		long answer = 0;

    for(long i = 1; i <= n; i++)
    {
      if(i <= k) continue;
      else
      {
        answer += (n+1)/i * (i-k);
        answer += Math.Max(0, ((n+1)%i)-k);
      }
    }
    
		if(k != 0) Console.WriteLine(answer);
    else Console.WriteLine(n*n);
	}
}

Measured memory_bytes: 11092
#include<iostream>
#include<string>
#include<string.h>
#include<cstring>
#include<math.h>
#include<iomanip>
#include<vector>
#include<cmath>
#include<algorithm>
#include<numeric>
#include<cctype>
#include<utility>
#include<set>
#include<map>
#include<sstream>
#include<iterator>
#include<limits>
#include<map>
#include<deque>
#include<stack>
#include<queue>
using namespace std;
#define pb push_back
#define ff(i,a,b) for(int i=a;i<b;++i)
#define ffl(i,a,b) for(long long i=a;i<b;++i)
#define all(v) v.begin(), v.end() 
#define X first
#define Y second
#define mp make_pair
typedef long long ll;
typedef std::vector<int> vec;
typedef std::vector<long long> vecl;
typedef map<int,int> mii;
typedef map<ll,ll> mll;
typedef std::pair<int,int> pii;
typedef pair<ll,ll> pll; 
const int md = 1000000007;
#define pi 3.141592653589793238462643383279


int main() {
	ios_base::sync_with_stdio(false); 
    cin.tie(NULL);    
    
 	int tt{},T{};
 	//cin>>tt;T=tt;
    tt=1;
 	while(tt--){
        //cout<<"------------- #"<<T-tt<<endl;
        ll n{},m{},ans{},k{},a{},b{},c{},f{};
        
        cin>>n>>a>>b>>c;
        ll x,y,z,w;
        x=n*b;y=n*c;z=a*b;w=a*c;
        cout<<max(max(x,y),max(z,w))<<"\n";
        
    }
    
    
	return 0;
}

Measured memory_bytes: 3648
#include<bits/stdc++.h>
using namespace std;
#define ll                          long long
#define in(a)                       ll a; cin>>a;
#define in2(a,b)                    ll a,b; cin>>a>>b;
#define in3(a,b,c)                  ll a,b,c; cin>>a>>b>>c;
#define in4(a,b,c,d)                ll a,b,c,d; cin>>a>>b>>c>>d;
#define in5(a,b,c,d,e)              ll a,b,c,d,e; cin>>a>>b>>c>>d>>e;
#define lelo(b)                     for(auto &i:b)cin>>i;
#define ff                          first
#define ss                          second
#define call(v)                     v.begin(),v.end()
#define rall(v)                     v.rbegin(),v.rend()
#define show(x)                     for(auto t:x)cout<<t<<" ";
#define pb                          push_back
#define bhar(s,v)                   memset(s,v,sizeof(s))
#define endl                        "\n"                       
#define ce(x)                       cout<<x<<"\n";
#define nl                          cout<<endl;
#define jaldi                       ios_base::sync_with_stdio(false);cin.tie(NULL);
#define dekh_lo                     ce("dekh_lo");
#define sz(x)                       (ll)x.size()
#define re                          return

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

typedef pair<ll,ll> pii;
typedef vector<pii> vii;
typedef vector<ll> vi;

const ll mod=1e9+7;
const ll N=4e5+5;

/*


*/

void solve(){
    in3(d,t,s);
    ll temp=s*t;
    if(temp>=d){
    	ce("Yes");
    	re;
    }
    ce("No");
}

int32_t main(){
    // jaldi
    ll t; 
    // cin>>t;
    t=1;     
    while(t--){
        solve();
    }
}

/*


*/

  

Measured memory_bytes: 3640
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
const int N=10001;
int n,m;
int main(){
	scanf("%d%d",&n,&m);
	if (n<=10)	printf("%d\n",m+(10-n)*100);
	else printf("%d\n",m);
	return 0;	
}

Measured memory_bytes: 128
n, m = map(int, input().split())
rec1, rec2 = [], []
for i in range(n):
    a, b = map(int, input().split())
    rec1.append((a, b))

for i in range(m):
    c, d = map(int, input().split())
    rec2.append((c, d))

rec = []
for i in range(n):
    a, b = rec1[i]
    num = float("inf")
    for j in range(m):
        c, d = rec2[j]
        if abs(a - c) + abs(b - d) < num:
            index = j
            num = abs(a - c) + abs(b - d)
    rec.append(index)


for i in range(n):
    print(rec[i] + 1)

Measured memory_bytes: 3064
#include <cstdio>

using namespace std;

int main()
{
	int n;
	long long tmp = 1;
	
	scanf("%d", &n);
	
	for (int i = n; i >= 1; i--){
		tmp *= i;
	}
	
	printf("%lld\n", tmp);
	
	return (0);
}

Measured memory_bytes: 1020
N = int(input())
L = list(map(int,input().split()))
L = sorted(L)
ans = 0
for i in range(len(L)):
    for j in range(i + 1, len(L)):
        for k in range(j + 1, len(L)):
            if L[k] < L[j] + L[i] and L[j] < L[k] + L[i] and L[i] < L[j] + L[k]:
                if L[k] != L[i] and L[i] != L[j] and L[j] != L[k]:
                    ans += 1
print(ans)


Measured memory_bytes: 9184
#include <bits/stdc++.h>
using namespace std;
int main(){
  int n;
  long long answer = 0;
  cin >> n;
  int l0 = 2;
  int l1 = 1;
  long long memo1 = l0;
  long long memo2 = l1;
  long long memory = 0;
  if (n == 1)
    answer = l1;
  else{
  for(int i = 0; i < n - 1; i++){
    memory = memo2;//大きい方をメモリーに移す
    memo2 += memo1;//小さい方をでかい方に足す
    memo1 = memory;//大きい方を新しい小さい方とする
  }
  }
  answer = memo1;
  cout << memo2 << endl;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
const int M = 1e5+5;
const int Mx = 1e9+5;
int a[M],dp[M],k;
int solve(int i){
	//cout << i << " " << dp[i] << endl;
	if(i < 0 )return 0;
	if(dp[i] != Mx)return dp[i];
	if(i == 0){
		return 0;
	}if(i == 1){
		return abs(a[1]-a[0]);
	}
	for(int x=1;x<=k;x++){
		if(i-x <0)break;
		dp[i] = min(dp[i],solve(i-x)+abs(a[i]-a[i-x]));
	}
	return dp[i];
}
int main(){
	int n;
	cin>>n>>k;
	for(int i=0;i<n;i++){
		cin>>a[i];
		dp[i] = Mx;
	}
	cout << solve(n-1) << '\n';
	return 0;
}

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

#define int long long

#define REP(i, b) for(int i = 0; i < (b); i++)
#define REPS(i, b) for(int i = 1; i <= (b); i++)
#define ALL(v) (v).begin(), (v).end()

using namespace std;

using ll = long long;
using ld = long double;
using pi = pair<int, int>;
using pl = pair<ll, ll>;
using vi = vector<int>;
using vl = vector<ll>;
using vd = vector<double>;
using vs = vector<string>;
using vb = vector<bool>;
using vpi = vector<pi>;
using vpl = vector<pl>;
using vvi = vector<vi>;
using vvl = vector<vl>;
using vvb = vector<vb>;

const int INF = 1e9;
const int MOD = 1e9+7;

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

signed main()
{
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(10);

    int N; cin >> N;
    vi A(N); REP(i, N) cin >> A[i];
    int r = 0, ans = 0;
    int sum = 0;
    for(int l = 0; l < N; l++)
    {
        while(r < N && (sum + A[r]) == (sum ^ A[r]))
        {
            sum += A[r++];
        }
        ans += r-l;
        sum -= A[l];
    }
    cout << ans << endl;
}

Measured memory_bytes: 1792
#include <iostream>
#include <stdio.h>       // printf,scanf
#include <stdlib.h>
#include <math.h>
#include <string>
#include <vector>
#include <algorithm>  //sort,binarySearch
#include <functional> 
#include <iomanip> // setprecision
#include <utility>    // c+11 Array
#include <set>
#include <sstream>
#define PI 3.141592653589793238462643383279
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)
#define debug(x) cout << #x << " = " << x << endl;
#define debret(x) debug(x) ; return 0;

using namespace std;


int main()
{
    int N;
    cin >> N;
    int a[N+1];

    a[0] = (int)1e+9;
    int tmp;
    REP(i,N) {
        cin >> tmp;
        a[tmp] = i+1;
    }

    FOR(i,i+1,N+1) {
        cout << a[i];
        if (i != N) cout << " ";
    }
    cout << endl;

    return 0;
}

Measured memory_bytes: 1152
import re
while True:
    try:
        line = input()
    except:
        break

    arr = re.findall(r"[0-9X]+", line)

    ans = -1
    for i in "0123456789":
        a, b, r = [s.replace("X", str(i)) for s in arr]
        if i == "0" and \
            (a[0] == "0" and len(a) > 1) or \
            (b[0] == "0" and len(b) > 1) or \
            (r[0] == "0" and len(r) > 1):
                continue
#        print([a, b, r])
        if int(a) + int(b) == int(r):
            ans = i
            break
    if ans == -1:
        print("NA")
    else:
        print(ans)

Measured memory_bytes: 7820
N = int(input())
e_list = [[] for i in range(N)]
for i in range(N-1):
        a,b = list(map(int,input().split()))
        a,b = a-1,b-1
        e_list[a].append(b)
        e_list[b].append(a)
c = list(map(int,input().split()))

vi = 0 #時と場合によってここを変える
from collections import deque
Q = deque([vi])
checked_list = [False for i in range(N)]
checked_list[vi]=True
min_path_list = [10**27 for i in range(N)] #問題によりここを変える
min_path_list[vi] = 0
while len(Q)>0:
    v = Q.pop()
    for v1 in e_list[v]:
        if not checked_list[v1]:
            checked_list[v1]=True
            Q.appendleft(v1)
            min_path_list[v1]=min(min_path_list[v1],min_path_list[v]+1) #問題によりここを変える


min_i_list = [[i,min_path_list[i]] for i in range(N)]
min_i_list.sort(key=lambda x:x[1],reverse=True)

c.sort()

ans = [[min_i_list[i][0]+1, c[i]] for i in range(N)]

ans.sort(key=lambda x:x[0])
ans = [ans[i][1] for i in range(N)]
print(sum(c[:-1]))
print(*ans)

Measured memory_bytes: 53848
#include <bits/stdc++.h>
#define int long long
#define rep(i, a, n) for(int i = (int)(a);(i) < (int)(n);++(i))
#define repe(i, a, n) for(int i = (int)(a);(i) <= (int)(n);++(i))
#define repif(i, a, x) for(int i = (int)(a);(x);++(i))
#define repr(i, a, n) for(int i = ((int)(a)-1);(i) >= (int)(n);--(i))
#define reper(i, a, n) for(int i = (int)(a);(i) >= (int)(n);--(i))
#define SZ(x) ((int)(x).size())
#define ALL(x) begin(x), end(x)
#define RNG(x, a, n) begin(x)+(a), end(x)+(n)
#define ADD(a, b) (((a%MOD+MOD)%MOD+(b%MOD+MOD)%MOD)%MOD)
#define SUB(a, b) (((a%MOD+MOD)%MOD-(b%MOD+MOD)%MOD+MOD)%MOD)
#define MUL(a, b) ((((a%MOD+MOD)%MOD)*((b%MOD+MOD)%MOD))%MOD)
#define CHADD(a, b) (a = ADD(a, b))
#define CHMUL(a, b) (a = MUL(a, b))
#define CEIL(x) ((int)ceil(((double)x)))
#define POW(x, y) ((int)pow(x, y))
#define UNIQUE(x) (x).erase(unique(ALL((x))), (x).end())
#define gcd(x, y) __gcd(x, y)
#define lcm(x, y) ((x)/gcd(x,y)*(y))
#define isin(x, l, r) ((l) <= (x) && (x) < (r))
#define YES cout << "YES" << endl
#define NO cout << "NO" << endl
#define Yes cout << "Yes" << endl
#define No cout << "No" << endl
#define yes cout << "yes" << endl
#define no cout << "no" << endl
#define fcout cout << fixed << setprecision(10)
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define PI (acos(-1))
#define EPS (1e-10)
#define INF LLONG_MAX
#define MOD 1000000007LL
using namespace std;
using VI = vector<int>;
using PII = pair<int, int>;
using TIII = tuple<int, int, int>;
using VPII = vector<PII>;
using VTIII = vector<TIII>;
using Complex = complex<double>;
template<typename T, template<typename> typename C = less> using PQ = priority_queue<T, vector<T>, C<T>>;
template<typename T> bool chmax(T& a, const T& b){ if(a<b){ a=b; return true; } return false; }
template<typename T> bool chmin(T& a, const T& b){ if(a>b){ a=b; return true; } return false; }


struct UF {
    int n, num;
    VI r, p, s;
    UF(){}
    UF(int sz) : n(sz), num(sz), r(sz, 1), p(sz, 0), s(sz, 1){ iota(ALL(p), 0); }
    int find(int x){
        return (x == p[x] ? x : p[x] = find(p[x]));
    }
    bool same(int x, int y){
        return find(x) == find(y);
    }
    void unite(int x, int y){
        x = find(x), y = find(y);
        if(x == y) return;
        if(r[x] < r[y]) swap(x, y);
        r[x] += r[y];
        p[y] = x;
        s[x] += s[y];
        num--;
    }
    int rank(int x){
        return r[find(x)];
    }
    int count() const{
        return num;
    }
    int size(int x){
        return s[find(x)];
    }
};


int N, M;
UF uf;


signed main(){
    cin >> N >> M;

    uf = UF(N);

    rep(i, 0, M){
        int X, Y, Z;
        cin >> X >> Y >> Z;
        uf.unite(X-1, Y-1);
    }

    cout << uf.count() << endl;

    return 0;
}

Measured memory_bytes: 2560
import numpy as np
n, m, c = map(int, input().split())
B = np.array([int(i) for i in input().split()])
cnt = 0
for i in range(n):
    A = np.array([int(j) for j in input().split()])
    if np.dot(A,B)+c > 0:
        cnt += 1
print(cnt)

Measured memory_bytes: 21792
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

class State{
public:
  int x1, y1, x2, y2, cost;

  State(){}
  State(int x1, int y1, int x2, int y2, int cost) :
    x1(x1), y1(y1), x2(x2), y2(y2), cost(cost) {}

  bool goal(){
    return x1 == x2 && y1 == y2;
  }
};

int w, h;
int t[52][52];
int sx, sy, gx, gy;

bool closed[52][52][52][52];

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

void move(int &x, int &y, int d){
  int nx = x + dx[d];
  int ny = y + dy[d];

  if(nx < 0 || w <= nx || ny < 0 || h <= ny || t[ny][nx] == 1){
    return;
  }
  x = nx;
  y = ny;
}

void solve(){
  queue<State> open;
  open.push(State(sx, sy, gx, gy, 0));
  memset(closed, 0, sizeof(closed));
  closed[sy][sx][gy][gx] = true;

  while(!open.empty()){
    State st = open.front();
    open.pop();

    if(st.cost >= 100){
      continue;
    }
    if(st.goal()){
      cout << st.cost << endl;
      return;
    }

    for(int i = 0; i < 4; i++){
      int nx1 = st.x1;
      int ny1 = st.y1;
      int nx2 = st.x2;
      int ny2 = st.y2;

      move(nx1, ny1, i);
      move(nx2, ny2, (i + 2) % 4);

      if(nx1 == st.x1 && ny1 == st.y1 &&
         nx2 == st.x2 && ny2 == st.y2) continue;
      if(closed[ny1][nx1][ny2][nx2]) continue;

      closed[ny1][nx1][ny2][nx2] = true;
      open.push(State(nx1, ny1, nx2, ny2, st.cost + 1));
    }
  }

  cout << "NA" << endl;
}

int main(){
  while(cin >> w >> h, w || h){
    cin >> sx >> sy;
    cin >> gx >> gy;
    sx--;
    sy--;
    gx--;
    gy--;

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

    solve();
  }
}

Measured memory_bytes: 8672
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
#define REP(var, a, b) for (int var = (a); var < (b); var++)
#define rep(var, n) for (int var = 0; var < (n); ++var)
#define ALL(c) (c).begin(), (c).end()
#define rALL(c) (c).rbegin(), (c).rend()

bool cmp(pii& lhs, pii& rhs) {
  if (lhs.first < rhs.first)
    return true;
  else if (lhs.first == rhs.first)
    return (lhs.second > rhs.second);
  return false;
}

int main() {
  string s, t;
  cin >> s >> t;
  int last = -1;
  for (int i = 0; i <= (int)s.size() - (int)t.size(); i++) {
    bool ok = true;
    rep(j, t.size()) {
      if (!(s[i + j] == '?' || s[i + j] == t[j])) {
        ok = false;
        break;
      }
    }
    if (ok) last = i;
  }
  if (last < 0) {
    cout << "UNRESTORABLE" << endl;
    return 0;
  }
  rep(i, s.size()) {
    if (last <= i && i < last + t.size()) {
      cout << t[i - last];
    } else {
      if (s[i] == '?')
        cout << 'a';
      else
        cout << s[i];
    }
  }
  cout << endl;
  return 0;
}


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

int64_t pow(int64_t b, int64_t p) {
  int64_t ans = 1;
  for (int64_t i = 0; i < p; i++) {
    ans *= b;
  }
  return ans;
}

int main() {
  int x;
  std::cin >> x;
  int64_t ans = 1;

  for (int64_t i = 2; i <= 100; i++) {
    int64_t p = 2;
    while (pow(i, p) <= x) {
      const auto v = pow(i, p);
      ans = std::max(ans, v);
      p++;
    }
  }

  std::cout << ans << std::endl;
  return 0;
}

Measured memory_bytes: 256
use std::io::BufRead;

const P: u64 = 1_000_000_007;

fn main() {
    let stdin = std::io::stdin();
    let n = stdin.lock().gets().parse::<usize>().unwrap();
    let s = stdin.lock().gets().into_bytes();
    let mut count = vec![0; n + 3];
    let mut prev = count.clone();
    count[0] = 1;
    for i in 1..n + 1 {
        std::mem::swap(&mut count, &mut prev);
        let kmax = std::cmp::min(i, n - i + s.len());
        count[0] = prev[0] + prev[1] * 2;
        for k in 1..kmax + 1 {
            // The digit deleted by BS can be either 0 or 1,
            // so double the count.
            count[k] = prev[k - 1] + prev[k + 1] * 2;
        }
        count[kmax + 1] = 0;
        count[kmax + 2] = 0;
        if i % 20 == 0 {
            for k in 0..kmax + 1 {
                count[k] %= P;
            }
        }
    }
    println!("{}", count[s.len()] % P);
}

trait Gets { fn gets(&mut self) -> String; }
impl<T: std::io::BufRead> Gets for T {
    fn gets(&mut self) -> String { self.lines().next().unwrap().unwrap() } }


Measured memory_bytes: 4352
#include <bits/stdc++.h>
using namespace std;
#define repd(i,a,b) for (int i=(a);i<(b);i++)
#define rep(i,n) repd(i,0,n)
#define all(x) (x).begin(),(x).end()
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
typedef long long ll;
const long long INF = 1LL << 60;
typedef pair<int, int> P;
int main()
{
    int H, W, N;
    cin >> H >> W >> N;
    vector<int> a(N);
    vector<vector<int>> c(H, vector<int>(W));
    rep(i, N) cin >> a[i];

    int h = 0, w = 0;
    rep(i, N) {
        rep(j, a[i]) {
            c[h][w] = i + 1;
            w++;
            if (w == W) {
                h++;
                w = 0;
            }
        }
    }

    rep(i, H) {
        if (i % 2 == 0) {
            rep(j, W) {
                cout << c[i][j];
                if (j != W - 1) cout << " ";
            }
        }
        else {
            for (int j = W - 1; j >= 0; j--) {
                cout << c[i][j];
                if (j != 0) cout << " ";
            }
        }
        cout << endl;
    }
    return 0;
}

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

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        
        String[] nums = reader.readLine().split(" ");
        int trains = Integer.parseInt(nums[0]);
        int index = Integer.parseInt(nums[1]);
        
        System.out.println(trains - index + 1);
    }
}


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

int main(){
   string s;cin>>s;
   int a=0,b=0;
   for(char x:s){
       if(x=='1')a++;
       else b++;
   }
   cout<<min(a,b)*2;
}

Measured memory_bytes: 512
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <map>

int N, C, ans;

struct element
{
	int time;
	int channel;
	int Open; // Open : 1, Close : 0
};

bool operator<(const element &a, const element &b)
{
	if (a.time != b.time) return a.time < b.time;
	return a.Open > b.Open;
}

int main()
{
	std::vector<element> arr;

	scanf("%d %d", &N, &C);
	for (int i = 0, si, ti, ci; i < N; i++)
	{
		scanf("%d %d %d", &si, &ti, &ci);
		arr.push_back({ si, ci, 1 });
		arr.push_back({ ti, ci, 0 });
	}
	std::sort(arr.begin(), arr.end());
	std::map<int, int > m;

	for (int i = 0; i < arr.size(); i++)
	{
		int time = arr[i].time, channel = arr[i].channel, Open = arr[i].Open;
		if (Open == 1) m[channel] = time;
		else if (Open == 0 && m[channel] != time) m.erase(channel);
		ans = std::max(ans, (int)m.size());
	}
	printf("%d\n", ans);
	return 0;
}

Measured memory_bytes: 4852
#include<bits/stdc++.h>
using namespace std;
main(){
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  string s; cin >> s;
  int res1 = 0, res2 = 0, N = s.size();
  for(int i = 0, n1 = 0, n2 = 1; i < N; i++, n1 ^= 1, n2 ^= 1){
  	if(s[i]-'0' != n1) res1++;
    if(s[i]-'0' != n2) res2++;
  }
  cout << min(res1, res2);
}

Measured memory_bytes: 512
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace AtCoder
{
    public class QuestionA
    {
        public static void Main(string[] args)
        {
            string result = "";

            // 整数配列の入力
            var inputLongArray = Console.ReadLine().Split(' ').Select(i => int.Parse(i)).ToArray();
            var K = inputLongArray[0];
            var X = inputLongArray[1];

            var start = X - (K - 1);
            var end = X + (K - 1);
            for (int i = start; i <= end  ; ++i) {
                result += i + " ";
            }

            Console.WriteLine(result);
        }
    }
}

Measured memory_bytes: 19048
#include <stdio.h>
int main(void){
    int n,i,j,k,b,f,r,v;
    int room[4][3][10];
    scanf("%d\n",&n);
    for(i=0;i<4;i++){
        for(j=0;j<3;j++){
            for(k=0;k<10;k++){
                room[i][j][k]=0;
            }
        }
    }
    for(i=0;i<n;i++){
        scanf("%d %d %d %d\n",&b,&f,&r,&v);
        room[b-1][f-1][r-1]+=v;
    }
    for(i=0;i<4;i++){
        for(j=0;j<3;j++){
            for(k=0;k<10;k++){
                printf(" %d",room[i][j][k]);
            }
            if(j!=2||(j==2&&i==3)){
                printf("\n");
            }
            else if(i!=3){
                printf("\n####################\n");
            }
        }
    }
    
    return 0;
}


Measured memory_bytes: 2144
n, m = map(int,input().split())
A = []
for i in range(n):
  A.append( list(map(int,input().split())))
b = []
for i in range(m):
  b.append(int(input()))

Ab = []
for i in range(n):
  Ab.append(0)
  for k in range(m):
    Ab[i] += A[i][k] * b[k]

for i in range(n):  
  print(Ab[i])




Measured memory_bytes: 6020
void main() {
	auto ip = readAs!(long[]), N = ip[0], M = ip[1];
	Cake[] cakes;

	foreach(_; 0..N) {
		auto ip2 = readAs!(long[]), a = ip2[0], b = ip2[1], c = ip2[2];
		long[] score;
		foreach(i; [1,-1]) foreach(j; [1,-1]) foreach(k; [1,-1]) {
			score ~= a*i+b*j+c*k;
		}
		cakes ~= Cake(a, b, c,score);
	}
	ulong res;
	foreach(i; 0..8) {
		cakes.sort!((a, b) => a.score[i] > b.score[i]);
		res = max(res, calc(cakes[0..M]));
	}
	res.writeln;
}
alias Cake = Tuple!(long, "x", long, "y", long, "z", long[], "score");


ulong calc(Cake[] cakes) {
	long beat, deli, popu;
	foreach(i; cakes) {
		beat += i.x;
		deli += i.y;
		popu += i.z;
	}
	return abs(beat)+abs(deli)+abs(popu);
}

// ===================================

import std.stdio;
import std.string;
import std.conv;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;

T readAs(T)() if (isBasicType!T) {
	return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
	return readln.split.to!T;
}

T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		res[i] = readAs!(T[]);
	}
	return res;
}

T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		auto s = rs;
		foreach(j; 0..width) res[i][j] = s[j].to!T;
	}
	return res;
}

int ri() {
	return readAs!int;
}

double rd() {
	return readAs!double;
}

string rs() {
	return readln.chomp;
}

Measured memory_bytes: 764
s_str = input()
t_str = input()
t_len = len(t_str)
roop_num = len(s_str)-t_len+1
max_num = 0
for i in range(roop_num):
    match_str = s_str[i:i+t_len]
    match_num = sum([match_str[j]==t_str[j] for j in range(t_len)])
    if max_num < match_num:
        max_num = match_num
print(t_len-max_num)

Measured memory_bytes: 67824
MOD = 998244353
N, K = map(int, input().split())
rl = [list(map(int, input().split())) for _ in range(K)]
dp = [0] * (N + 1)
sdp = [0] * (N + 1)
dp[1] = 1
sdp[1] = 1

for i in range(2, N + 1):
    for j in range(K):
        l, r = rl[j][0], rl[j][1]
        tl = max(1, i - r)
        tr = max(0, i - l)
        dp[i] += sdp[tr] - sdp[tl - 1]
        dp[i] %= MOD
    sdp[i] += dp[i] + sdp[i - 1]
    sdp[i] %= MOD

print(dp[N])

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

using namespace std;
typedef pair<int, int> P;
typedef pair<string, P> PP;

void solve()
{
	int n;
	while(cin >> n, n)
	{
		vector<PP> Vec;
		int sum_weight = 0;
		for(int i = 0; i < n; ++i)
		{
			string name;
			cin >> name;
			int w, s;
			cin >> w >> s;
			Vec.push_back(PP(name, P(w, s)));
			sum_weight += w;
		}	
		for(int i = 0; i < n; ++i)
		{
			vector<int> ok;
			for(int j = 0; j < n; ++j)
			{
				if(sum_weight - Vec[j].second.first <= Vec[j].second.second)
				{
					ok.push_back(j);
				}
			}
			if(ok.size() == 1)
			{
				cout << Vec[ok[0]].first << endl;
				sum_weight -= Vec[ok[0]].second.first;
				Vec[ok[0]].second.second = -9999999;
			}
			else
			{
				int heaviest = 0;
				int pos = 0;
				for(int k = 0; k < ok.size(); ++k)
				{
					if(heaviest < Vec[ok[k]].second.first)
					{
						heaviest = Vec[ok[k]].second.first;
						pos = k;
					}
				}
				cout << Vec[ok[pos]].first << endl;
				sum_weight -= Vec[ok[pos]].second.first;
				Vec[ok[pos]].second.second = -9999999;
			}
		}
	}
}

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

Measured memory_bytes: 1228
#!/usr/bin/env ruby

require 'set'

class Hash
  def push(key, value)
    self[key] = [] if self[key] == nil
    self[key].push(value)
  end
end

class Array
  def lower_bound(value)
    left = -1;
    right = self.length;
    while left + 1 < right
      mid = left + (right - left) / 2;
      if self[mid] >= value
        right = mid
      else
        left = mid
      end
    end
    right
  end

  def unique
    res = [self.first]
    each_cons(2) do |a, b|
      if a != b
        res.push(b)
      end
    end
    res
  end
end

def get_ints
  gets.chomp.split.map(&:to_i)
end

def get_ints_minus_one
  get_ints.map { |x| x - 1 }
end

def get_int
  gets.chomp.to_i
end

N = get_int
X = []
N.times do |i|
  X[i] = get_ints
end

ans = nil

[*0..100].each do |cx|
  [*0..100].each do |cy|
    dame = false
    h_min = 0
    h_max = 10 ** 24
    X.each do |x, y , h|
      if h == 0
        test = (x - cx).abs + (y - cy).abs
        h_max = test if test < h_max
      else
        test = h + (x - cx).abs + (y - cy).abs
        if test < h_min || test > h_max
          dame = true
          break
        end
        h_min = test
        h_max = test
      end
    end
    if dame || h_min != h_max
      next
    else
      ans = [cx, cy, h_min]
    end
  end
end

puts "#{ans[0]} #{ans[1]} #{ans[2]}"



Measured memory_bytes: 14400
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < n; ++i) // マクロ
using namespace std;                          // stdの省略
using pii = pair<int, int>;                   // pairの略記
using ll = long long;                         // long longの略記
using ull = unsigned long long;                         // long longの略記

int main(void)
{

    int n;
    cin >> n;

    vector<int> a(n);
    ll sum = 0;
    ll mod = pow(10, 9) + 7;
    rep(i, n) {
        cin >> a.at(i);
        sum += a.at(i);
        sum %= mod;
    }

    ll ans = 0;
    rep(i,n) {
        sum -= a.at(i);
        if (sum < 0) sum += mod;
        ans += a.at(i) * sum;
        ans %= mod;
    }
    
    cout << ans << endl;

    return 0;
}

Measured memory_bytes: 3980
#gcdは3.4.3だとfractionsにある
from fractions import gcd
import math

from math import factorial as f

from math import ceil,floor,sqrt

from sys import exit

from copy import deepcopy
import numpy as np

import bisect
import re
import heapq


from copy import deepcopy
import itertools

ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))






def main():
    n = ii()
    xylist = []
    for i in range(n):
        xtmp,ytmp = mi()
        xylist.append([xtmp,ytmp])
    
    nf = f(n)
    dist = [ [] for i in range(n+1)]

    for i in range(n):
        for j in range(n):
            dist[i].append(sqrt(((xylist[i][0]-xylist[j][0])**2)+((xylist[i][1]-xylist[j][1])**2)))

    junbantmp = list(range(n))
    junban = list(itertools.permutations(junbantmp))

    ans = 0.0
    for jun in junban:
        distsum = 0.0
        for i in range(n-1):
            distsum += dist[jun[i]][jun[i+1]]
        ans+=distsum/nf
    
    print(ans)
        
    





main()


Measured memory_bytes: 17812
object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val w, h, n = sc.nextInt()
  val xya = List.fill(n)((sc.nextInt(), sc.nextInt(), sc.nextInt()))
  var l = 0
  var r = w
  var b = 0
  var t = h
  for ((x, y, a) <- xya) {
    a match {
      case 1 => l = l.max(x)
      case 2 => r = r.min(x)
      case 3 => b = b.max(y)
      case 4 => t = t.min(y)
    }
  }
  println((r-l).max(0) * (t-b).max(0))
}


Measured memory_bytes: 55536
#include <bits/stdc++.h>
#define il inline
#define RG register
#define ll long long
#define inf (2147483640)
#define N (1000010)

using namespace std;

struct edge{ int u,v,w; }e[N];

int fa[N],a[N],n,m;
ll ans;

il int gi(){
  RG int x=0,q=1; RG char ch=getchar();
  while ((ch<'0' || ch>'9') && ch!='-') ch=getchar();
  if (ch=='-') q=-1,ch=getchar();
  while (ch>='0' && ch<='9') x=x*10+ch-48,ch=getchar();
  return q*x;
}

il int cmp(const edge &a,const edge &b){ return a.w<b.w; }

il int find(RG int x){ return fa[x]==x ? x : fa[x]=find(fa[x]); }

int main(){
  n=gi(),m=gi();
  for (RG int i=0;i<n;++i) fa[i]=i,a[i]=a[i+n]=inf;
  for (RG int i=1;i<=m;++i){
    e[i].u=gi(),e[i].v=gi(),e[i].w=gi();
    a[e[i].u]=min(a[e[i].u],e[i].w+1);
    a[e[i].v]=min(a[e[i].v],e[i].w+2);
  }
  for (RG int i=1;i<(n<<1);++i) a[i]=min(a[i],a[i-1]+2);
  for (RG int i=0;i<n;++i) e[++m]=(edge){i,(i+1)%n,min(a[i],a[i+n])};
  sort(e+1,e+m+1,cmp);
  for (RG int i=1,x,y;i<=m;++i){
    x=find(e[i].u),y=find(e[i].v);
    if (x!=y) fa[x]=y,ans+=e[i].w;
  }
  cout<<ans; return 0;
}


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

//typedef
//------------------------------------------
typedef long long LL;
typedef vector<LL> VL;
typedef vector<VL> VVL;
typedef vector<string> VS;
typedef pair<LL, LL> PLL;

//container util
//------------------------------------------
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())

//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI  = acos(-1.0);
const int MOD = 1000000007;

//debug
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

//main code

int main(int argc, char const* argv[])
{
	int n;
	cin >> n;
	VL x(n),srt(n);
	for (int i = 0; i < n; i++) {
		cin >> x[i];
		srt[i] = x[i];
	}
	SORT(srt);
	int chuou = srt[n/2-1];
	for (int i = 0; i < n; i++) {
		if (x[i] <= chuou) {
			cout << srt[n/2] << endl;
		}
		else {
			cout << srt[n/2-1] << endl;
		}
	}
 
	return 0;
}


Measured memory_bytes: 5376
//author: Harsh :)
#include <bits/stdc++.h>
using ll = long long;
using ld = long double;
#define F first
#define S second
const ll mod = 1e9 + 7;
const ll INF = 922337203685477;
#define pb push_back
#define deb(x) cout << '>' << #x << ':' << x << endl;
#define fastio ios_base::sync_with_stdio(false); cin.tie(0);
#define maxN 100007
using namespace std;
int main() {
  fastio;
  ll n = 0;
  cin >> n;
  vector<ll>a(n + 1, 0), b(n, 0);
  for (ll i = 0; i < n + 1; ++i) {
    cin >> a[i];
  }
  for (ll i = 0; i < n; ++i) cin >> b[i];
  ll ans = 0;
  for (ll i = 0; i < n; ++i) {
    ans += min(a[i], b[i]);
    b[i] -= min(a[i], b[i]);
    ans += min(a[i + 1], b[i]);
    a[i + 1] -= min(b[i], a[i + 1]);
  }
  cout << ans;
}


Measured memory_bytes: 4720
module Main where

-- "times transformer"
type Times a = Int -> (Int, a)

-- Apply And Increase Counter
aaic :: (a -> b) -> a -> Times b
aaic f x n = (1 + n, f x)

nextYear :: Int -> Int
nextYear current = floor $ 1.01 * (fromIntegral current)

countUntil :: (a -> a) -> (a -> Bool) -> a -> Times a
countUntil f cond x n
    | cond x = (n, x)
    | otherwise = countUntil f cond (f x) (n + 1)

main :: IO ()
main = interact $ show . fst . (\n -> countUntil nextYear (>= n) 100 0) . read


Measured memory_bytes: 4000
#include <iostream>
#include <fstream>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <functional>
#include <algorithm>
#include <climits>
#include <cmath>
#include <iomanip>
using namespace std;
#define ll long long int
#define rep(i,n) for( int i = 0; i < n; i++ )
#define rrep(i,n) for( int i = n; i >= 0; i-- )
#define REP(i,s,t) for( int i = s; i <= t; i++ )
#define RREP(i,s,t) for( int i = s; i >= t; i-- )
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define INF 2000000000
#define mod 1000000007
#define INF2 1000000000000000000
#define int long long
typedef pair<int, int> P;
int dp[3010][3010][4];
int CC[3010][3010];
signed main(void)
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int R, C, K;
    cin >> R >> C >> K;
    rep(i, K) {
        int a, b, c;
        cin >> a >> b >> c;
        a--; b--;
        //G[a].push_back({b, c});
        CC[a][b] = c;
    }
    //rep(i, 3010) sort(G[i].begin(), G[i].end());
    rep(i, R) {
        rep(j, C) {
            rep(k, 4) {
                if(k < 3) { 
                    dp[i + 1][j + 1][k + 1] = max(dp[i + 1][j + 1][k + 1], dp[i + 1][j + 1][k]);
                    dp[i + 1][j + 1][k + 1] = max(dp[i + 1][j + 1][k + 1], dp[i + 1][j][k] + CC[i][j]);
                }
                int tmp = max({dp[i][j + 1][0], dp[i][j + 1][1], dp[i][j + 1][2], dp[i][j + 1][3]});
                dp[i + 1][j + 1][k] = max(dp[i + 1][j + 1][k], dp[i + 1][j][k]);
                dp[i + 1][j + 1][1] = max({dp[i + 1][j + 1][1], tmp + CC[i][j]});
            }
        }
    }
    // rep(i, R + 1) {
    //     rep(j, C + 1) {
    //         cout << dp[i][j][3] << " ";
    //     }
    //     cout << endl;
    // }
    int ans = 0;
    rep(i, R + 1) rep(j, C + 1) rep(k, 4) ans = max(ans, dp[i][j][k]);
    cout << ans << endl;

    return 0;
}


Measured memory_bytes: 356056
#include <stdio.h>
#define MAX 101
#define INFINITY 1048576 // 2???20???
#define WHITE -1
#define GRAY 0
#define BLACK 1
#define true 1

int serch(int);

int M[MAX][MAX];

int main() {
  
  int n,i,j,x,y;
  scanf("%d",&n);
  for(i = 1; i <= n; i++) {
    for(j = 1; j <= n; j++) {
      scanf("%d",&M[i][j]);
      if(M[i][j]==-1) M[i][j]=INFINITY;   
    }
  }
  
  printf("%d\n",serch(n));
  return 0;
}

int serch(int n) {
  int u, v, min, i, j, d[MAX], p[MAX], c[MAX], sum = 0;
  
  for(i = 1; i <= n; i++) {
    c[i] = WHITE;
    d[i] = INFINITY;
    p[i] = -1;
  }
  
  
  p[1] = -1;
  d[1] = 0;
  
  while(true) {
    min = INFINITY;
    u = -1;
    for(i = 1; i <= n; i++) {
      if(min > d[i] && c[i] != BLACK) {
        u = i;
        min = d[i];
      }
    }
    if(u == -1) break;
    c[u] = BLACK;
    for(v= 1; v <= n; v++) {
      if(c[v] != BLACK && M[u][v] != INFINITY) {
        if(d[v] > M[u][v]) {
          d[v] = M[u][v];
          p[v] = u;
          c[v] = GRAY;
        }
      }
    }
  }
  for(i = 1; i <= n; i++) {
    sum += d[i];
  }
  
  return sum;
}

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

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

  if (d == 0) {
    if (n==100) {
      ans = 101;
    }else{
      ans = 1*n;
    }
  }else if (d == 1){
    if (n == 100) {
      ans = 10100;
    }else{
      ans = pow(100,d)*n;
    }
  }else if (d == 2){
    if (n == 100) {
      ans = 1010000;
    }else{
      ans = pow(100,d)*n;
    }
  }
  printf("%d", ans);
  return 0;
}


Measured memory_bytes: 256