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

using namespace std;


#ifdef zxc

#include <sys/resource.h>
#include "debug.h"
#include "profile.h"

#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#define profile(X) LOG_DURATION(X)
#else
#define debug(...) 42
#define profile(...) 42
#endif

using ll = int64_t;
using ld = double;
const ld EPS = 1e-9;
const int MOD = 1e9 + 7;
const ld PI = 3.141592653589793;
const int maxn = 600001;
using cd = complex<double>;

void fast_io() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
}

struct fenwick {
    fenwick(int size) : data(size) {

    }

    void add(int pos, int val) {
        for (; pos < data.size(); pos |= pos + 1) {
            data[pos] += val;
        }
    }

    ll get(int pos) {
        ll res = 0;
        for (; pos >= 0; pos = (pos & (pos + 1)) - 1) {
            res += data[pos];
        }
        return res;
    }

    vector<int> data;

};

signed main() {
#ifdef zxc
    struct rlimit rl;
    const rlim_t kStackSize = 512L * 1024L * 1024L;
    assert(!getrlimit(RLIMIT_STACK, &rl));
    rl.rlim_cur = kStackSize;
    assert(!setrlimit(RLIMIT_STACK, &rl));
    freopen("../input.txt", "r", stdin);
//    freopen("../kolya_output.txt", "w", stdout);
#else
    //    mt19937 mt(std::chrono::high_resolution_clock::now().time_since_epoch().count());
    //            freopen("", "r", stdin);
    //        freopen("hack.out", "w", stdout);
#endif
    profile("all");
    auto solve = [](int _) {
        int n;
        cin >> n;
        int k;
        cin >> k;
        vector<int> a(n + 1);
        vector<ll> pref(n + 1);
        for (int i = 1; i <= n; ++i) {
            cin >> a[i];
            a[i] -= k;
            pref[i] = pref[i - 1] + a[i];
        }
        vector<int> p(n + 1);
        iota(p.begin(), p.end(), 0);
        sort(p.begin(), p.end(), [&](int i, int j) {
            return tie(pref[i], i) < tie(pref[j], j);
        });
        ll ans = 0;
        fenwick fwt(n + 1);
        for (int i:p) {
            ans += fwt.get(i - 1);
            fwt.add(i, 1);
        }
        cout << ans;
    };


    fast_io();

    cout.precision(9);
    cout <<
         fixed;
    for (int i = 1; i <= 1; ++i)
        solve(1);


}


Measured memory_bytes: 7104
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
# 2 * (a+b+c) がKの倍数
# Kが2の時は全て偶数か、全て奇数
# Kが2ではない時、全てKの倍数または全て(K//2）の半公倍数
if K == 2:
    odd = (N+1) // 2
    even = N // 2
    answer = odd ** 3 + even ** 3
else:
    num = N // K    
    answer = num ** 3
    if K % 2 == 0:
        num2 = N // (K//2)
        num2 -= num
        answer += num2 ** 3

print(answer)


Measured memory_bytes: 3060
#include <bits/stdc++.h>
using namespace std;
int main(void){
    int w,a,b;
    cin>>w>>a>>b;
    //AよりBが右側にある場合
    if (w+a<b) {
        cout<<b-(w+a)<<endl;
    } else if (a<=b&&w+a>=b) { //AとBが既に重なっている場合
        cout<<0<<endl;
    } else { //AよりBが左側にある時
        cout<<a-(b+w)<<endl;
    }
}


Measured memory_bytes: 256
#include "bits/stdc++.h"
#define rep(i,a,n) for(int i=(a);i<(int)(n);i++)
using namespace std;
typedef long long ll;
struct start { start() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  cout << fixed << setprecision(10);
}; }start;
void in() {}
template <class Head , class... Tail>
void in(Head&& head, Tail&&... tail) {
  cin >> head;
  in(move(tail)...);
}
template <class T>
  void out(T& t) {
  cout << t << '\n';
}
template <class Head , class... Tail>
void out(Head& head , Tail&... tail) {
  cout << head << ' ';
  out(move(tail)...);
}
int main(void) {
  int a,b,c,d;
  in(a,b,c,d);
  if(abs(c-a)<=d)out("Yes");
  else if(abs(c-b)<=d&&abs(b-a)<=d)out("Yes");
  else out("No");
  return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
#define fast ios::sync_with_stdio(false), cin.tie(0);
#define ll long long
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define endl '\n'

using namespace std;

main()
{
    fast;
    int n,i;
    cin>>n;
    int l[n],sum=0;
    for (i=0;i<n;i++)
    {
        cin>>l[i];
        sum+=l[i];
    }
    if (sum-*max_element(l,l+n)>*max_element(l,l+n))
        cout<<"Yes\n";
    else
        cout<<"No\n";
}

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

public class Main implements Runnable {

    private void solve() throws IOException {
        int A = nextInt();
        int B = nextInt();

        writer.println(Math.max(Math.max(A+B,A-B),A*B));
    }

    public static void main(String[] args) {

        new Main().run();
    }

    BufferedReader reader;
    StringTokenizer tokenizer;
    PrintWriter writer;

    public void run() {
        try {
            reader = new BufferedReader(new InputStreamReader(System.in));
//            reader = new BufferedReader(new FileReader("a_1.txt"));
            tokenizer = null;
            writer = new PrintWriter(System.out);
//            writer = new PrintWriter("aa_1.txt");
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

    String nextToken() throws IOException {
        while(tokenizer == null || !tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }

        return tokenizer.nextToken();
    }
}


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

int main(){
    ll n , m ;
    cin >> n >> m ;
    vector<string> S(n) , T(m) ;
    rep(i,n) cin >> S[i] ;
    rep(i,m) cin >> T[i] ;
    for(int i = 0 ; i < n - m + 1 ; i++ ){
        for(int j = 0 ; j < n - m + 1 ; j++ ){
            ll count = 0 ;            
            rep(k,m){
                rep(l,m){
                    if( S[ i + k ][ j + l ] == T[k][l] )count++ ;
                }
            }
            if( count == m * m ){
                cout << "Yes" << endl ;
                return 0 ;
            }
            //else cout << count << endl ;
        }
    }
    cout << "No" << endl ;
}

Measured memory_bytes: 3640
#include <bits/stdc++.h>
#pragma GCC optimize ("O3,unroll-loops")
#define f first
#define s second
#define ri register int
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
using vi = vector<int>;
using ii = pair<int, int>;
using vii = vector<ii>;
#define MAXN 100000
int main() {
	ios_base :: sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	int n, dp[MAXN][3], pts[MAXN][3];
	cin >> n;
	for(ri k = 0; k < n; ++k)
		for(ri i = 0; i < 3; ++i)
			cin >> pts[k][i];
	dp[0][0] = pts[0][0];
	dp[0][1] = pts[0][1];
	dp[0][2] = pts[0][2];
	for(int k = 1; k < n; ++k) {
		dp[k][0] = pts[k][0] + max(dp[k - 1][1], dp[k - 1][2]);
		dp[k][1] = pts[k][1] + max(dp[k - 1][0], dp[k - 1][2]);
		dp[k][2] = pts[k][2] + max(dp[k - 1][0], dp[k - 1][1]);
	}
	cout << max(dp[n - 1][0], max(dp[n - 1][1], dp[n - 1][2])) << '\n';
    return 0;
}

Measured memory_bytes: 2560
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
string s;
int main() {
	while (cin >> s, s != "#") {
		s += '|';
		int pre = -1; vector<string> v;
		for (int i = 1; i < s.size(); i++) {
			if (s[i] == '|') {
				v.push_back(s.substr(pre + 2, i - pre - 3));
				pre = i;
			}
		}
		bool flag = false;
		for (int i = 0; i < v.size(); i++) {
			v[i] += '&';
			int pre2 = -1; vector<bool> c(256, false);
			for (int j = 1; j < v[i].size(); j++) {
				if (v[i][j] == '&') {
					string w = v[i].substr(pre2 + 1, j - pre2 - 1);
					if (w[0] == '~') c[w[1] + 128] = true;
					else c[w[0]] = true;
					pre2 = j;
				}
			}
			bool ok = true;
			for (int j = 0; j < 128; j++) {
				if (c[j] && c[j + 128]) ok = false;
			}
			if (ok) flag = true;
		}
		cout << (flag ? "yes" : "no") << endl;
	}
	return 0;
}

Measured memory_bytes: 3164
def inputs(num_of_input):
    ins = [input() for i in range(num_of_input)]
    return ins


def solve(inputs):
    i = inputs[0].split()
    times = {"a": {}, "b": {}}
    times["a"]["start"] = int(i[0])
    times["a"]["end"] = int(i[1])
    times["b"]["start"] = int(i[2])
    times["b"]["end"] = int(i[3])

    first_start = "a" if times["a"]["start"] < times["b"]["start"] else "b"
    second_start = "b" if first_start == "a" else "a"

    first_end = "a" if times["a"]["end"] < times["b"]["end"] else "b"
    second_end = "b" if first_end == "a" else "a"

    if second_start == first_end:
        return times[first_end]["end"] - times[second_start]["start"]
    if times[first_end]["end"] < times[second_start]["start"]:
        return 0

    return (
        (times[second_end]["end"] - times[first_start]["start"])
        - (times[second_start]["start"] - times[first_start]["start"])
        - (times[second_end]["end"] - times[first_end]["end"])
    )


if __name__ == "__main__":
    ret = solve(inputs(1))
    print(ret)


Measured memory_bytes: 3064
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rrep(i, n) for (int i = (int)(n - 1); i >= 0; i--)
#define all(x) (x).begin(), (x).end()
#define sz(x) int(x.size())
#define get_unique(x) x.erase(unique(all(x)), x.end());
typedef long long ll;
typedef complex<double> Complex;
const int INF = 1e9;
const ll MOD = 1e9 + 7;
const ll LINF = 1e18;
template <class T>
bool chmax(T &a, const T &b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <class T>
bool chmin(T &a, const T &b) {
    if (b < a) {
        a = b;
        return 1;
    }
    return 0;
}
template <class T>
vector<T> make_vec(size_t a) {
    return vector<T>(a);
}
template <class T, class... Ts>
auto make_vec(size_t a, Ts... ts) {
    return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...));
}

int main() {
    int n;
    cin >> n;
    ll ans = 0;
    ll MIN = LINF;
    bool zero = true;
    rep(i, n) {
        ll a, b;
        cin >> a >> b;
        ans += a;
        if (a > b) chmin(MIN, b);
        if (a != b) zero = false;
    }
    cout << (zero ? 0 : ans - MIN) << endl;
}


Measured memory_bytes: 256
n, k = map(int,input().split())
r, s, p = map(int,input().split())
t = input()
win = ['x' for i in range(n)]
ans = 0
if t[0] == 'r':
    win[0] = 'p'
elif t[0] == 's':
    win[0] = 'r'
else:
    win[0] = 's'
for i in range(1,n):
    if t[i] == 'r':
        win[i] = 'p'
    elif t[i] == 's':
        win[i] = 'r'
    else:
        win[i] = 's'
for i in range(k,n):
    if win[i-k] == win[i] and win[i-k] != 'x':
        win[i] = 'x'
for i in range(n):
    if win[i] == 'r':
        ans += r
    elif win[i] == 's':
        ans += s
    elif win[i] == 'p':
        ans += p
print(ans)

Measured memory_bytes: 4212
#include <iostream>
#include <cstring>
#include <cstdio>
#include<utility>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
typedef pair<double,double>P_D;
#define rep(i, n) for (int i = 0; i < n; i++)
#define reprev(i, n) for (int i = n - 1; i >= 0; i--)
#define MAX 100100
#define MAX_N 200100
#define SENTINEL 2000000000
const int MOD = 1e9+7;
#define NIL -1
const int INF = 1 << 29;
#define ALL(a)  (a).begin(),(a).end()
int n,X;
int GCD(int a,int b){return b?GCD(b,a%b):a;}
int main(){
cin>>n>>X;
vector<ll>x(n+1);
rep(i,n)cin>>x[i];
x[n]=X;
sort(ALL(x));
vector<ll>diff(n);
for(int i=0;i<n;i++){
diff[i]=x[i+1]-x[i];
}
ll a=diff[0];
for(int i=1;i<n;i++){
a=GCD(diff[i],a);
}
cout<<a<<endl;
}

Measured memory_bytes: 1792
#include<bits/stdc++.h>
using namespace std;
long long K[2]= {-1,1},n,A[100005],o,AN[100005];
int main() {
	scanf("%lld",&n);
	for(int i=1; i<=n; i++) 
		scanf("%lld",&A[i]);
	for(int i=1; i<n; i++) o+=A[i]*K[i&1];//o=a1/2-an/2   a1
	AN[1]=o+A[n];
	for(int i=2; i<=n; i++)AN[i]=A[i-1]*2-AN[i-1];
	for(int i=1; i<=n; i++) printf("%lld ",AN[i]);
	return 0;
}

Measured memory_bytes: 2816
// In the name of Allah 


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int ui;
typedef long double ldo;
#define FOR(i,j,k) for(int i = j; i < (int)(k); i++)
#define FORV(i, v) FOR(i, 0, ((v).size()))
#define REP(i,j,k) for(int i = j; i >= (int)(k); i--)
#define pb push_back
#define mp make_pair
#define X first
#define Y second
const int mod = 1e9+7, MAX = 1e6+5;
int n, ar, maj;
int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);	
	cin >> n;
	ar = -1;
	for (int i = 0; i < n; i++) {
		int a;
		cin >> a;
		if ((a%10 && a<ar) || (a%10&&ar==-1))
			ar = a;
		maj += a;
	}
	if (maj%10)
		cout << maj << endl;
	else
	{
		if (ar==-1)
			cout << 0 << endl;
		else
			cout << maj-ar << endl;
	}
	return 0;
}

Measured memory_bytes: 256
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
# import time,random,resource

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)
def IF(c, t, f): return t if c else f


class Seg():
    def __init__(self, na, default, func):
        if isinstance(na, list):
            n = len(na)
        else:
            n = na
        i = 1
        while 2**i <= n:
            i += 1
        self.D = default
        self.H = i
        self.N = 2**i
        if isinstance(na, list):
            self.A = [default] * (self.N) + na + [default] * (self.N-n)
            for i in range(self.N-1,0,-1):
                self.A[i] = func(self.A[i*2], self.A[i*2+1])
        else:
            self.A = [default] * (self.N*2)
        self.F = func

    def find(self, i):
        return self.A[i + self.N]

    def update(self, i, x):
        i += self.N
        self.A[i] = x
        while i > 1:
            i = i // 2
            self.A[i] = self.merge(self.A[i*2], self.A[i*2+1])

    def merge(self, a, b):
        return self.F(a, b)

    def total(self):
        return self.A[1]

    def query(self, a, b):
        A = self.A
        l = a + self.N
        r = b + self.N
        res = self.D
        while l < r:
            if l % 2 == 1:
                res = self.merge(res, A[l])
                l += 1
            if r % 2 == 1:
                r -= 1
                res = self.merge(res, A[r])
            l >>= 1
            r >>= 1

        return res


def main():
    n,q = LI()
    a = LI()
    qa = [LI() for _ in range(q)]

    def f(a, b):
        return a + b

    seg = Seg(a, 0, f)
    r = []
    for t,u,v in qa:
        if t == 0:
            c = seg.find(u)
            seg.update(u, c+v)
        else:
            r.append(seg.query(u,v))

    return JA(r, "\n")


print(main())




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

#define fi first
#define se second
#define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define repr(i,n) for(int i=(int)(n-1);i>=0;i--)
#define rep(i,n) repl(i,0,n)
#define each(itr,v) for(auto itr:v)
#define pb(s) push_back(s)
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout << #x" = " << x << endl
#define print(x) cout << x << endl
#define maxch(x,y) x=max(x,y)
#define minch(x,y) x=min(x,y)
#define uni(x) x.erase(unique(all(x)),x.end())
#define exist(x,y) (find(all(x),y)!=x.end())
#define bcnt(x) bitset<32>(x).count()

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
typedef pair<P, int> PPI;
typedef pair<int, P> PIP;
typedef pair<ll, ll> PL;
typedef pair<P, ll> PPL;
typedef set<int> S;

#define INF INT_MAX/3
#define MAX_N 1000000001
#define MOD 1000000007

int main(){
    cin.sync_with_stdio(false);
    int n, w;
    cin >> n >> w;
    vector<int> f(n);
    rep(i, n) cin >> f[i];
    sort(all(f));


    if (f[0] <= w && n == 2) {
        int ans = 1;
        if ((f[1] <= w && f[0] + f[1] > w)) ans++;
        cout << ans << endl;
    } else if (f[0] <= w && n > 2) {
        ll sum[n] = {};
        rep(i, n) sum[i + 1] = sum[i] + f[i];
        ll ans = sum[n] == w;
        ll dp[w + 1] = {};

        rep(i, n){
            memset(dp, 0, sizeof(dp));
            if(sum[i] > w) break;
            dp[sum[i]]++;
            repl(j, i + 1, n)repr(k, w + 1) {
                if (sum[i] + f[j] > k) break;
                dp[k] = (dp[k] + dp[k - f[j]]) % MOD;
            }
            repl(j, w - f[i] + 1, w + 1) ans = (ans + dp[j]) % MOD;
        }
        cout << ans << endl;
    } else {
        cout << 1 << endl;
    }

    return 0;
}

Measured memory_bytes: 3264
n = int(input())
al = list(map(int,input().split()))

pl = [0 for i in range(61)]

for a in al:
    turn = 0
    while a:
        if a % 2 == 1:
            pl[turn] += 1
        a //= 2
        turn += 1

ans = 0
k = 1
for p in pl:
    ans += p * (n - p) * k
    ans %= 10**9 + 7
    k *= 2
    k %= 10 ** 9 + 7

print(ans)



Measured memory_bytes: 122936
#include<iostream>
#include<vector>
#include<algorithm>
int main(){
	int max=0,count=0;
	std::vector<int> vec(100);
	std::vector<int> vec2(100);
	std::vector<int> vec3;
	while(1){
		for(int i=0;i<100;i++){
			std::cin>>vec[i];
			//if(vec[i]==0)break;
			vec2[vec[i]]++;
			if(vec2[vec[i]]>max)max=vec2[vec[i]];
			count++;
		}
		if(std::cin.eof())break;
	}
	for(int i=0;i<count;i++){
		if(vec2[vec[i]]==max){
			vec3.push_back(vec[i]);
			vec2[vec[i]]=0;
		}
	}
	sort(vec3.begin(),vec3.end());
	for(int i=0;i<vec3.size();i++)std::cout<<vec3[i]<<std::endl;
	return 0;
}

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

using namespace std;

typedef long long ll;

ll count(ll arr[], ll n,ll S){
  ll dp[n+1][n*S+1][n+1]={0};
  
  for(int i=n;i>=0;i--){
    for(int j=0;j<=n*S;j++){
      for(int k=0;k<=n;k++){
        if(i==n){
          if(j==0&&k==0){
              dp[i][j][k]=1;
          }
        }
        else{
          if(j-arr[i]>=0&&k>0){
            dp[i][j][k]=dp[i+1][j][k]+dp[i+1][j-arr[i]][k-1];
          }else{
            dp[i][j][k]=dp[i+1][j][k];
          }
        }
      }
    }
  }
  ll ans=0;
  for(int i=1;i<=n;i=i+1){
    ans+=dp[0][S*i][i];
  }
  return ans;
}

int main(){
  ll n,A;
  cin>>n>>A;
  ll arr[n];
  for(int i=0;i<n;i++){
    cin>>arr[i];
  }
  cout<<count(arr,n,A);
  return 0;
}

Measured memory_bytes: 51072
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {

	private static final String RIGHT_TRIANGLE = "YES";
	private static final String NOT_RIGHT_TRIANGLE = "NO";

	/**
	 * <p>
	 * 与えられた三辺で直角三角形が作れるかを判定する。
	 * </p>
	 *
	 * @param args
	 *            利用しない。
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int lineCount = Integer.parseInt(br.readLine());
		for (int i = 0; i < lineCount; i++) {

			String[] input = br.readLine().split(" ");
			int[] side = { Integer.parseInt(input[0]),
					Integer.parseInt(input[1]), Integer.parseInt(input[2])};
			Arrays.sort(side);

			if (side[2] * side[2] == side[0] * side[0] + side[1] * side[1]) {
				System.out.println(RIGHT_TRIANGLE);
			} else {
				System.out.println(NOT_RIGHT_TRIANGLE);
			}
		}
	}
}

Measured memory_bytes: 20200
#include <iostream>
#include <cstdlib>
using namespace  std;
int main(){
  int n;int sum=0;
  cin >>n;
  int a[n+2];a[0]=0;a[n+1]=0;
  for(int i=1;i<=n;i++){
    cin >> a[i];
    sum+=abs(a[i]-a[i-1]);
  }
  sum+=abs(a[n+1]-a[n]);
  int ans=sum;
  for(int i=1;i<=n;i++){

     ans-=abs(a[i]-a[i-1]);
     ans-=abs(a[i+1]-a[i]);
     ans+=abs(a[i+1]-a[i-1]);
     cout <<ans<<endl;
     ans=sum;
  }
}


Measured memory_bytes: 1664
from collections import deque
n,*t=map(int,open(0).read().split())
con=[[] for _ in range(n)]
dist_f_k=[0]*n
l1,l2=t[:3*n-3],t[3*n-1:]

for a,b,c in zip(*[iter(l1)]*3):
	con[a-1].append((b-1,c))
	con[b-1].append((a-1,c))

k=t[3*n-2]
que=deque([k-1])
while que:
	cur=que.popleft()
	for nxt,dd in con[cur]:
		if dist_f_k[nxt]==0 and nxt!=k-1:
			que.append(nxt)
			dist_f_k[nxt]=dist_f_k[cur]+dd

for x,y in zip(*[iter(l2)]*2):
	print(dist_f_k[x-1]+dist_f_k[y-1])

Measured memory_bytes: 64180
# coding: utf-8
# Your code here!
import numpy as np
N, M, C = (int(i) for i in input().split()) 
B = np.array([[int(i) for i in input().split()] for i in range(1)][0])
e = np.array([[int(i) for i in input().split()] for i in range(N)])
# print(B)
# print(e)
# print(((np.sum(e*B, axis=1)+C)))
c_2 = np.count_nonzero((np.sum(e*B, axis=1)+C)>=1)
print(c_2)

Measured memory_bytes: 13036
/*⠄⢰⣧⣼⣯⠄⣸⣠⣶⣶⣦⣾⠄⠄⠄⠄⡀⠄⢀⣿⣿⠄⠄⠄⢸⡇⠄⠄
⠄⠄⠄⣾⣿⠿⠿⠶⠿⢿⣿⣿⣿⣿⣦⣤⣄⢀⡅⢠⣾⣛⡉⠄⠄⠄⠸⢀⣿⠄
⠄⠄⢀⡋⣡⣴⣶⣶⡀⠄⠄⠙⢿⣿⣿⣿⣿⣿⣴⣿⣿⣿⢃⣤⣄⣀⣥⣿⣿⠄
⠄⠄⢸⣇⠻⣿⣿⣿⣧⣀⢀⣠⡌⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠿⣿⣿⣿⠄
⠄⢀⢸⣿⣷⣤⣤⣤⣬⣙⣛⢿⣿⣿⣿⣿⣿⣿⡿⣿⣿⡍⠄⠄⢀⣤⣄⠉⠋⣰
⠄⣼⣖⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⣿⣿⣿⣿⣿⢇⣿⣿⡷⠶⠶⢿⣿⣿⠇⢀⣤
⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣽⣿⣿⣿⡇⣿⣿⣿⣿⣿⣿⣷⣶⣥⣴⣿⡗
⢀⠈⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠄
⢸⣿⣦⣌⣛⣻⣿⣿⣧⠙⠛⠛⡭⠅⠒⠦⠭⣭⡻⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠄
⠘⣿⣿⣿⣿⣿⣿⣿⣿⡆⠄⠄⠄⠄⠄⠄⠄⠄⠹⠈⢋⣽⣿⣿⣿⣿⣵⣾⠃⠄
⠄⠘⣿⣿⣿⣿⣿⣿⣿⣿⠄⣴⣿⣶⣄⠄⣴⣶⠄⢀⣾⣿⣿⣿⣿⣿⣿⠃⠄⠄
⠄⠄⠈⠻⣿⣿⣿⣿⣿⣿⡄⢻⣿⣿⣿⠄⣿⣿⡀⣾⣿⣿⣿⣿⣛⠛⠁⠄⠄⠄
⠄⠄⠄⠄⠈⠛⢿⣿⣿⣿⠁⠞⢿⣿⣿⡄⢿⣿⡇⣸⣿⣿⠿⠛⠁⠄⠄⠄⠄⠄
⠄⠄⠄⠄⠄⠄⠄⠉⠻⣿⣿⣾⣦⡙⠻⣷⣾⣿⠃⠿⠋⠁⠄⠄⠄⠄⠄⢀⣠⣴
⣿⣿⣿⣶⣶⣮⣥⣒⠲⢮⣝⡿⣿⣿⡆⣿⡿⠃⠄⠄⠄⠄⠄⠄⠄⣠⣴⣿*/

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
#define ll long long
#define ii pair<ll,ll>
#define iii pair<ii,ll>
#define fi first
#define se second
#define endl '\n'
#define debug(x) cout << #x << " is " << x << endl;

#define rep(x,start,end) for(auto x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--))
#define all(x) (x).begin(),(x).end()
#define sz(x) (int)(x).size()

ll MAX(ll a){return a;}
ll MIN(ll a){return a;}
template<typename... Args>
ll MAX(ll a,Args... args){return max(a,MAX(args...));}
template<typename... Args>
ll MIN(ll a,Args... args){return min(a,MIN(args...));}

#define indexed_set tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update>

mt19937 rng(chrono::system_clock::now().time_since_epoch().count());

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	
	int a,b;
	cin>>a>>b;
	
	if (b%2==0 && a*2<=b && b<=a*4) cout<<"Yes"<<endl;
	else cout<<"No"<<endl;
}


Measured memory_bytes: 3652
#include<bits/stdc++.h>
using namespace std ;
int T , x  , l ;
string s = "";
char f ;
int main(){
   //freopen("coloring.in", "r", stdin);

   for( int i = 0 ; i < 9 ; i ++ ){
    cin >> f ;
    if( i == 0 || i == 4 || i == 8  )
        s += f ;
   }

   cout << s ;

}


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

int main() {
  int N;
  cin >> N;
  string S;
  cin >> S;
  int64_t R = 0, B = 0, G = 0;
  for (int i = 0; i < N; i++) {
    if (S.at(i) == 'R') {
      R++;
    }
    else if (S.at(i) == 'B') {
      B++;
    }
    else {
      G++;
    }
  }
  int64_t ans = R * B * G;
  for (int i = 0; i < N; i++) {
    for (int j =  i + 1; j < N; j++) {
      int k = 2 * j - i;
      if (k < N) {
        if (S.at(i) != S.at(k) && S.at(j) != S.at(i) && S.at(k) != S.at(j)) {
          ans--;
        }
      }
    }
  }
  cout << ans << endl;
}

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

namespace Atcoder
{
	class ABC045A
	{
		static void Main()
		{
			var a = int.Parse(Console.ReadLine());
			var b = int.Parse(Console.ReadLine());
			var h = int.Parse(Console.ReadLine());
			Console.WriteLine((a + b) * h / 2);
		}
	}
}


Measured memory_bytes: 2648
import numpy as np
n=int(input())
temp=[]
p=n
while p:
    p-=1
    temp.append(list(map(int,input().split())))
arr=(np.array(temp)).transpose()
dp=np.zeros((3,n))
dp[0][0]=arr[0][0]
dp[1][0]=arr[1][0]
dp[2][0]=arr[2][0]
for i in range(1,n):
    dp[0][i]=max(dp[1][i-1],dp[2][i-1])+arr[0][i]
    dp[1][i]=max(dp[0][i-1],dp[2][i-1])+arr[1][i]
    dp[2][i]=max(dp[1][i-1],dp[0][i-1])+arr[2][i]
print(int(max(dp.transpose()[n-1])))


Measured memory_bytes: 44212
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__;in(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)
#define DBL(...) double __VA_ARGS__;in(__VA_ARGS__)
#define vec(type,name,...) vector<type> name(__VA_ARGS__)
#define VEC(type,name,size) vector<type> name(size);in(name)
#define vv(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define VV(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__));in(name)
#define vvv(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
inline int scan(){ return getchar(); }
inline void scan(int &a){ scanf("%d", &a); }
inline void scan(unsigned &a){ scanf("%u", &a); }
inline void scan(long &a){ scanf("%ld", &a); }
inline void scan(long long &a){ scanf("%lld", &a); }
inline void scan(unsigned long long &a){ scanf("%llu", &a); }
inline void scan(char &a){ cin >> a; }
inline void scan(float &a){ scanf("%f", &a); }
inline void scan(double &a){ scanf("%lf", &a); }
inline void scan(long double &a){ scanf("%Lf", &a); }
inline void scan(vector<bool> &vec){ for(unsigned i = 0; i < vec.size(); i++) { int a; scan(a); vec[i] = a; } }
inline void scan(string &a){ cin >> a; }
template<class T> inline void scan(vector<T> &vec);
template<class T, size_t size> inline void scan(array<T, size> &vec);
template<class T, class L> inline void scan(pair<T, L> &p);
template<class T, size_t size> inline void scan(T (&vec)[size]);
template<class T> inline void scan(vector<T> &vec){ for(auto &i : vec) scan(i); }
template<class T, size_t size> inline void scan(array<T, size> &vec){ for(auto &i : vec) scan(i); }
template<class T, class L> inline void scan(pair<T, L> &p){ scan(p.first); scan(p.second); }
template<class T, size_t size> inline void scan(T (&vec)[size]){ for(auto &i : vec) scan(i); }
template<class T> inline void scan(T &a){ cin>>a; }
inline void in(){}
template <class Head, class... Tail> inline void in(Head &head, Tail&... tail){ scan(head); in(tail...); }
inline constexpr ll gcd(ll a,ll b){if(!a||!b)return 0;while(b){ll c=b;b=a%b;a=c;}return a;}
inline constexpr ll lcm(ll a,ll b){if(!a||!b)return 0;return a*b/gcd(a,b);}
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
using Graph = vector<vector<int>>;
/* 4方向への隣接頂点への移動を表すベクトル */
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

const long long INF = 1LL << 60;
int main(){
 	LL(n,q);
	STR(s);
    vec(ll,ans,q);
	for(int i = 0; i < n-1; ++i){
		if(s[i]=='A'&&s[i+1]=='C'){
            s[i]='a';
        }
	}
	vector<ll> rui(n+2,0);
    for(int i = 0; i < n; ++i){
		rui[i+1]+=rui[i];
		if(s[i]=='a'){
            rui[i+1]++;
        }
	}
 
	for(int i = 0; i < q; ++i){
		LL(l,r);
		cout<<rui[r-1]-rui[l-1]<<endl;
	}
}

Measured memory_bytes: 2688
#include <bits/stdc++.h>
using namespace std;
 
typedef long long lld;
const int NN = 1e5 + 5;
lld aa[NN], dp[NN];
int nn;
 
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
        cin >> nn;
        for (int ii = 1; ii <= nn; ++ii)
            cin >> aa[ii];
        dp[1] = 0;
        dp[2] = abs(aa[2] - aa[1]);
        for (int ii = 3; ii <= nn; ++ii)
            dp[ii] = min(dp[ii - 1] + abs(aa[ii] - aa[ii - 1]), dp[ii - 2] + abs(aa[ii] - aa[ii - 2]));
        cout << dp[nn];
    return 0;
}

Measured memory_bytes: 1792
#include<algorithm>
#include<bitset>
#include<climits>
#include<cmath>
#include<cstdlib>
#include<iomanip>
#include<iostream>
#include<map>
#include<numeric>
#include<queue>
#include<set>
#include<stack>
#include<string>
#include<time.h>
#include<tuple>
#include<utility>
#include<vector>

using namespace std;
const long mod = 1000000007;
long gcd(long x, long y) { if (x > y) { return gcd(y, x); } long r; while (y != 0) { r = x % y; x = y; y = r; }return x; }
long lcm(long x, long y) { return(x / gcd(x, y)) * y; }

int main() {

	string S; cin >> S;
	if (S == "Sunny") cout << "Cloudy" << endl;
	if (S == "Cloudy") cout << "Rainy" << endl;
	if (S == "Rainy") cout << "Sunny" << endl;

}

Measured memory_bytes: 256
use proconio::{fastout, input};

#[fastout]
fn main() {
    input! {
        n: usize,
        mut a: [i64; n],
    }
    a.sort();
    if a[0] == 0 {
        println!("0");
        return;
    }
    let mut prod = 1;
    for x in a {
        if prod > 1_000_000_000_000_000_000 / x {
            println!("-1");
            return;
        }
        prod *= x;
    }
    println!("{}", prod);
}


Measured memory_bytes: 5072
#include <bits/stdc++.h>
#define pb push_back
#define rep(i,n) for(int i=0;i<(n);i++)
#define reps(i,n,s) for(int i=(s);i<(n);i++)
#define rrep(i,n) for(int i=(n-1);i>=0;i--)
#define rreps(i,n,s) for(int i=s;i>=n;i--)
#define MOD 1000000007
using ll = long long;
using namespace std;
template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }

int main(){
cin.tie(0);
ios::sync_with_stdio(false);
string n;
cin>>n;
string inv_n=n;
reverse(inv_n.begin(),inv_n.end());
if(n==inv_n)cout<<"Yes"<<endl;
else cout<<"No"<<endl;
//system("pause");
return 0;
}

Measured memory_bytes: 256
def resolve():
    N = int(input())
    A = list(map(int, input().split()))
    absA = list(map(abs, A))
    negcnt = 0
    for a in A:
        if a < 0:
            negcnt += 1
    if 0 in A or negcnt%2==0:
        print(sum(absA))
    else:
        print(sum(absA)-2*min(absA))



if '__main__' == __name__:
    resolve()

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

//#pragma GCC optimize("Ofast")
//#pragma GCC optimize("unroll-loops")
//#pragma GCC target("avx,avx2")

using namespace std;

#define int long long
#define sz(a) (int) (a).size()
#define all(a) (a).begin(), (a).end()
#define x first
#define y second

mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());

void solve() {
    int x, y, z;
    cin >> x >> y >> z;
    swap(x, y);
    swap(x, z);
    cout << x << " " << y << " " << z << "\n";
}

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

    int t;
//    cin >> t;
t = 1;
    while (t--) {
        solve();
    }

    return 0;
}

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

#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))

using namespace std;

typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;

template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; }
template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; }
template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ","; os << ")"; return os; }
template<typename T> istream& operator >> (istream& is, vector<T>& v) { each (i, v) is >> i; return is; }

template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); }
template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); }

int main(int argc, char *argv[])
{
  ios_base::sync_with_stdio(0);
  cin.tie(0);

  string s;
  while (cin >> s) {
    lli sum = 0;
    reverse(s.begin(), s.end());
    int w = 0;
    for (int i = 0; i < s.size(); ++i) {
      w += (s[i] == 'W');
      if (s[i] == 'B') sum += w;
    }
    cout << sum << endl;
  }
  
  return 0;
}


Measured memory_bytes: 720
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Solve is
   A : Integer;
   B : Integer;
begin
   Get (A);
   Get (B);
   if A > 9 then
      Put_Line ("-1");
   elsif B > 9 then
      Put_Line ("-1");
   else
      Put_Line (Integer'Image (A*B));
   end if;
end Solve;

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

#define FORi(i, a, b) for(int i = a; i < b; ++i)
#define FORd(i, a, b) for(int i = a; i > b; --i)
 
   
int main()
{
    int n;
    cin >> n;
    vector<int> a(n);
    deque<int> b;
    
    FORi(i, 0, a.size()) {
        cin >> a[i];
        if(i % 2 == 0) {
            b.push_front(a[i]);
        }
        else {
            b.push_back(a[i]);
        }
    }
    
    if(n % 2 == 0){
        FORi(j, 0, (b.size() + 1) / 2) {
            int tmp = b[j];
            b[j] = b[b.size() - 1 - j];
            b[b.size() - 1 - j] = tmp;
        }
    }
    
    FORi(i, 0, n) {
        cout << b[i] << " ";
    }
    cout << endl;
    
    return 0;
}

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

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

int main() {
    int M, D;
    cin >> M >> D;
    int count = 0;
    if(D < 20) cout << 0 << endl;
    else{
        for(int m = 2; m < M+1; ++m){
            for(int d = 10; d < D+1; ++d){
                int a = d / 10;
                int b = d % 10;
                int x = a * b;
                if(a < 2 || b < 2) continue;
                else if(x == m) count++;
            }
        }
    cout << count << endl;
    }
}

Measured memory_bytes: 256
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>

using namespace std;

#define   ll            long long
#define   PI            atan(1.0)*4
#define   mst(x,v)      memset(x,v,sizeof(x))
#define   rush()        int T;scanf("%d",&T);while(T--)
#define   debug         puts("debug")

typedef   pair<int,int> P;

const int   M = 2e5+5000;
const int mod = 1e9+7;
const int inf = 1e9;

int main() {

	ll a,b,c,x,y,ans=0;
	scanf("%lld %lld %lld %lld %lld",&a,&b,&c,&x,&y);
	
	if(2*c < a && 2*c < b) {
		ans = max(x,y)*2*c;
	}
	else if(2*c < a ) {
		ans = x*2*c + b*(max((ll)0,y - x));
	}
	else if(2*c < b ) {
		ans = y*2*c + a*(max((ll)0,x - y));
	}
	else
	{
		if( a + b <= 2*c)
			ans = a*x + b*y;
		else
		{
			if(x > y)
				ans = 2*c*y + (x-y)*a;
			else
				ans = 2*c*x + (y-x)*b;
		}
	}
	
	printf("%lld\n",ans);
	return 0;
}

/*
	freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
*/





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

using namespace std;
using ll = long long;
using pii = pair<int, int>;

int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(false);
  
  int h, w;
  cin >> h >> w;

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

  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      bool up = false, left = false;
      if (i > 0) up |= a[i - 1][j] == '#';
      if (j > 0) left |= a[i][j - 1] == '#';
      if (up && left) {
        cout << "Impossible" << endl;
        return 0;
      }
    }
  }
  cout << "Possible" << endl;

  return 0;
}

Measured memory_bytes: 256
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")
#pragma GCC optimize("unroll-loops")
//#pragma warning(disable : 4996)

#ifdef _MSC_VER
#include <intrin.h>
#define __builtin_popcount __popcnt
#endif

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<math.h>
#include<iomanip>
#include<set>
#include<numeric>
#include<cstring>
#include<cstdio>
#include<functional>
#include<bitset>
#include<limits.h>
#include<cassert>
#include<iterator>
#include<complex>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<time.h>
#include<random>
#include<array>


using namespace std;

#define REP(i, n) for(int i = 0;i < (n);++i)
#define REPR(i, n) for(int i = n-1;i >= 0;--i)
#define FOR(i, m, n) for(int i = m;i < n;++i)
#define FORR(i, m, n) for(int i = m-1;i >= n;--i)
#define SORT(v, n) sort(v, v+n);
#define VSORT(v) sort(v.begin(), v.end());
#define REVERSE(v,n) reverse(v,v+n);
#define VREVERSE(v) reverse(v.begin(), v.end())
#define ll long long
#define print(x) cout<<(x)<<'\n'
#define pe(x) cout<<(x)<<" "
#define DEBUG(x) cout<<#x<<": "<<x<<endl
#define lb(v,n) lower_bound(v.begin(), v.end(), (n))
#define ub(v,n) upper_bound(v.begin(), v.end(), (n))
#define int long long
//#define double long double
#define all(x) (x).begin(), (x).end()
#define print_space(v) REP(i,v.size())cout << v[i] << ((i == v.size() - 1) ? "\n" : " ")
template<typename T1, typename T2> inline void chmin(T1 & a, T2 b) { if (a > b) a = b; }
template<typename T1, typename T2> inline void chmax(T1& a, T2 b) { if (a < b) a = b; }
typedef pair<int, int>pii;
typedef array<int, 3> arr3;
std::random_device rd;
std::mt19937 mt(rd());
constexpr ll MOD = 1e9 + 7; constexpr int MAX = 200020;
const double pi = acos(-1); constexpr double EPS = 1e-8;
constexpr ll INF = 1e16;
void yes(bool c) { if (c)print("Yes"); else print("No"); };



bool has[10010];
void solve() {
	int N; cin >> N;
	int K; cin >> K;
	REP(i, K) {
		int d; cin >> d;
		REP(j, d) {
			int a; cin >> a;
			a--;
			has[a] = true;
		}
	}
	int ans = 0;
	REP(i, N) {
		if (!has[i])ans++;
	}
	print(ans);
}
signed main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	//int q; cin >> q;
	//while (q--)
	solve();
}



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

int main(){
  int N;
  cin >> N;
  vector<int> A(N,0);
  for(int i=0;i<N;i++){
    cin >> A[i];
    A[i] --;
  }
  int push=0,cur=0;
  while(true){
    push ++;
    int next=A[cur];
    if(next==-1){
      cout << -1 << endl;
      return 0;
    }else if(next==1){
      cout << push << endl;
      return 0;
    }
    A[cur]=-1;
    cur = next;
  }
}

Measured memory_bytes: 640
#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[80];
    int i, len;
    //int num1, num2, num3;
    char *num1;
    char *num2;
    char *num3;

    /*fgets(str, sizeof(str), stdin);
    len = strlen(str);*/
    //printf("%s\n", str);
    
    while(fgets(str, sizeof(str), stdin) != 0){
        len = strlen(str);

        while (1){
            for (i = 0; i < len; i++){
                if (str[i] == ' ' || str[i] == 46 || str[i] == 13){
                    continue;
                }
                str[i] += 1;
                if (str[i] == 123){
                    str[i] -= 26;
                }
            }
    
            //printf("%s\n", str);
            num1 = strstr(str, "the");
            num2 = strstr(str, "this");
            num3 = strstr(str, "that");
    
            if (num1 != NULL || num2 != NULL || num3 != NULL){
                break;
            }
        }

        printf("%s\n", str);
    }

    return (0);
}


Measured memory_bytes: 2036
#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
int compare_int(const void *a, const void *b)
{
    return *(int*)b - *(int*)a;
}

int main(void){
    int X,Y,A,B,C, P[100000],Q[100000],R[100000];
    std::cin >> X >> Y >> A >> B >> C;
    for(int a=0;a<A;a++){
        std::cin >> P[a];
    }
    for(int a=0;a<B;a++){
        std::cin >> Q[a];
    }
    for(int a=0;a<C;a++){
        std::cin >> R[a];
    }
    qsort(P,A,sizeof(int),compare_int);
    qsort(Q,B,sizeof(int),compare_int);
    std::vector<int> vec;
    for(int a=0;a<X;a++){
        vec.push_back(P[a]);
    }
    for(int a=0;a<Y;a++){
        vec.push_back(Q[a]);
    }
    for(int a=0;a<C;a++){
        vec.push_back(R[a]);
    }
    std::sort(vec.begin(),vec.end(),std::greater<int>());
    long long int count=0;
    for(int a=0;a<X+Y;a++){
        count+=vec[a];
    }
    std::cout << count;
}

Measured memory_bytes: 3952
#include <bits/stdc++.h>
#include <iterator>
#include <vector>
#include <algorithm>
#include <iomanip>

#define v vector
#define ll long long 
#define vpll vector<pair<long long,long long> > 
#define F first
#define S second
#define mp make_pair
#define ld long double
#define pb push_back
#define pii pair<int,int>
#define pll pair<long long,long long>
#define pci pair<char,int>
#define un unsigned

#define mod 1000000007
#define MAXN 3001
using namespace std; 
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)



int main()
{
    fast;
    ll n;
    cin>>n;
    ll ans = 0;
    ans = 1000*(n/500);
    n -= 500*(n/500);
    ans += 5*(n/5);
    cout<<ans<<endl;
    return 0;
}


Measured memory_bytes: 256
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<cmath>
#include<algorithm>
#include<bitset>
#include<map>
#include<functional>
#include<set>
#include<numeric>

#pragma region
using namespace std;
#define FOR(i,r,n) for(ll i = (ll)(r); i < (ll)(n); i++)
#define rep(i,n) FOR(i,0,n)
#define RFOR(i,r,n) for(ll i=(ll)(n-1);i>=r;i--)
#define rrep(i,n) RFOR(i,0,n)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define COUNT(a,x)  upper_bound(all(a), x) - lower_bound(all(a), x)
#define MCOUNT(a,x,y) upper_bound(all(a), y) - lower_bound(all(a), x)
#define UNIQUE(a) sort(all(a)); a.erase(unique(all(a)), a.end())
#define SUM(a) accumulate(all(a),0)
#define scan(x) scanf("%lld",&x)
#define pb push_back
typedef long long int ll;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
typedef vector<string> vs;
typedef map<ll, ll> MAP;
typedef set<ll> SET;
typedef double D;
const ll inf = 5555555555555555555;
const ll mod = 1000000007;
const D pi = acos(-1);
const D eps = 1e-10;

ll n = 0, m = 0, ans = 0, sum = 0, cnt = 0, tmp = 0, ma = -inf, mi = inf;
string s;
bool ok, flag;
ll dx[5] = { 1,-1,0,0,0 }, dy[5] = { 0,0,1,-1,0 };
ll ddx[9] = { 1,-1,0,0,1,1,-1,-1,0 }, ddy[9] = { 0,0,1,-1,1,-1,1,-1,0 };
#pragma endregion
#define MAX 111111

ll sm[2 * MAX];
int main(void) {
  cin >> n;
  vll a(n);
  rep(i, n) cin >> a[i];
  rep(i, n) a[i] -= i + 1;
  sort(all(a));
  sm[0] = a[0];
  FOR(i, 1, n) sm[i] = sm[i - 1] + a[i];
  rep(i, n) {
	ans = a[i] * (i + 1);
	ans -= sm[i];
	ans += (sm[n - 1] - sm[i]);
	ans -= a[i] * (n - i - 1);
	//cout << ans << endl;
	mi = min(mi, ans);
  }
  cout << mi << endl;

  return 0;
}

Measured memory_bytes: 3328
#include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
typedef long long int lint;
using namespace std;

//ただの辺
struct edge {
    using lint = long long int;
    int to;
    lint cost;
    //引数一つの時は距離1
    edge(int t, lint c = 1) : to(t), cost(c) {
    }
};

// path[start]を計算して格納する
void dfs(int start, vector<vector<edge>> &g, vector<int> &path,
         vector<bool> &calced) {
    if (calced[start]) {
        return;
    }
    if (g[start].size() == 0) {
        path[start] = 0;
    } else {
        int temp = 0;
        for (int i = 0; i < g[start].size(); i++) {
            dfs(g[start][i].to, g, path, calced);
            temp = max(temp, path[g[start][i].to]);
        }
        path[start] = temp + 1;
    }
    calced[start] = true;
}

int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<edge>> g(n);
    for (int i = 0; i < m; i++) {
        int x, y;
        cin >> x >> y;
        x--, y--;
        g[x].push_back(edge(y));
    }
    // path[i]:iスタートのパスで最長なものの長さ
    vector<int> path(n);
    vector<bool> calced(n, false);
    int ans = 0;
    for (int i = 0; i < n; i++) {
        dfs(i, g, path, calced);
        ans = max(ans, path[i]);
    }
    cout << ans << endl;
}

Measured memory_bytes: 10880
fn main() {
    let (r, w) = (std::io::stdin(), std::io::stdout());
    let mut sc = IO::new(r.lock(), w.lock());

    let n: usize = sc.read();
    let s = sc.chars();
    let mut r: Vec<i64> = vec![0; n + 1];
    let mut g: Vec<i64> = vec![0; n + 1];
    let mut b: Vec<i64> = vec![0; n + 1];
    for i in 0..n {
        r[i + 1] = r[i] + if s[i] == 'R' { 1 } else { 0 };
    }
    for i in 0..n {
        g[i + 1] = g[i] + if s[i] == 'G' { 1 } else { 0 };
    }
    for i in 0..n {
        b[i + 1] = b[i] + if s[i] == 'B' { 1 } else { 0 };
    }
    let mut ans = 0;
    for i in 0..n {
        for j in i + 1..n {
            let d = 2 * j - i;
            if rg(s[i], s[j]) {
                ans += b[n] - b[j + 1];
                if d < n && s[d] == 'B' {
                    ans -= 1;
                }
            }
            if gb(s[i], s[j]) {
                ans += r[n] - r[j + 1];
                if d < n && s[d] == 'R' {
                    ans -= 1;
                }
            }
            if br(s[i], s[j]) {
                ans += g[n] - g[j + 1];
                if d < n && s[d] == 'G' {
                    ans -= 1;
                }
            }
        }
    }
    println!("{}", ans);
}

fn rg(c: char, d: char) -> bool {
    return (c == 'R' && d == 'G') || (c == 'G' && d == 'R');
}
fn gb(c: char, d: char) -> bool {
    return (c == 'G' && d == 'B') || (c == 'B' && d == 'G');
}
fn br(c: char, d: char) -> bool {
    return (c == 'B' && d == 'R') || (c == 'R' && d == 'B');
}

pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>);

impl<R: std::io::Read, W: std::io::Write> IO<R, W> {
    pub fn new(r: R, w: W) -> IO<R, W> {
        IO(r, std::io::BufWriter::new(w))
    }
    pub fn write<S: ToString>(&mut self, s: S) {
        use std::io::Write;
        self.1.write(s.to_string().as_bytes()).unwrap();
    }
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .0
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}

Measured memory_bytes: 2212
//AtCoder AGC028 A - Two Abbreviations
#include <bits/stdc++.h>
using namespace std;
using ll=int64_t;
#define FOR(i,a,b) for(int64_t i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)
ll lcm(ll num1,ll num2){
    return num1 / __gcd(num1,num2) * num2;
}
int main() {
#if LOCAL&0
    std::ifstream in("./test/sample-2.in"); //input.txt
    std::cin.rdbuf(in.rdbuf());
#endif
    ll N,M; cin>>N>>M;
    string S,T; cin>>S>>T;
    ll ans=lcm(N,M); //ans
    //vector<char> x(ans+1,0);
    unordered_map<ll,char> x;
    ll step=ans/N;
    REP(i,S.size()){
        x[1+step*i]=S[i];
    }
    step=ans/M;
    REP(i,T.size()){
        auto ch=T[i];
        auto it=x.find(1+step*i);
        if(it==x.end()) continue;
        if(it->second!=ch){
            ans=-1;
            break;
        }
    }
    cout<<ans<<endl;
    return 0;
}

Measured memory_bytes: 4260
ma = lambda :map(int,input().split())
ni = lambda:int(input())

n,k = ma()
sn = [0]*n
for i in range(k):
    d = ni()
    for a in ma():
        sn[a-1]=1
c = 0
for w in sn:
    if w==0:c+=1
print(c)


Measured memory_bytes: 9180
#include<stdio.h>
#include <string.h>

int main (){
    
  int r;
  
  scanf("%d",&r);
  
  if(r < 1200){
    printf("ABC");
  }else if(r < 2800){
    printf("ARC");
  }else{
    printf("AGC");
  }
        return 0;
  
}



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

int main(){
  int N;
  long long K;
  cin>>N;
  cin>>K;
  vector<pair<int,int>>sr(N);
  for(int i=0;i<N;i++){
    cin>>sr[i].first>>sr[i].second;
  }
  sort(sr.begin(),sr.end());
  long long temp=0;
  for(int i=0;i<N;i++){
    temp=temp+sr[i].second;
    if(temp>=K){
      cout<<sr[i].first<<endl;
      return 0;
    }
  }
  return 0;
}


  

Measured memory_bytes: 1024