akhauriyash/Code-Regression huggingface dataset:
//													\[T]/ Praise
//													 (*)  The
//													 / \  Sun



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

typedef long long ll;
typedef long double dbl;
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef pair<long long, long long> pll;
typedef vector<long long> vl;
typedef vector< pair<int, int> > vii;
#define mp make_pair
#define pb push_back
#define invec(a, n) for(ll i = 0; i < n; i++) {cin >> a[i];}
#define rep(n) for(ll i = 0; i < n; i++)
#define fr(i,j,k) for(ll i = j; i < k; i++)
#define FR(i,j,k) for(ll i = j; i >= 0; i--)
#define MOD 1000000007
#define all(v) v.begin(), v.end()
#define INF 1000000
#define xx first
#define yy second

void fast()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
}

int main()
{
	int n, k;
	cin >> n >> k;

	vl a(n);
	invec(a,n);
	sort(all(a));

	// fr(i,0,n)
	// 	cout << a[i] << " ";

	vector< vector<ll> > dp(n+1, vector<ll> (k+1, 0));
	vl pref(k+1, 0);


	dp[0][0] = 1;
	pref[0] = dp[0][0];
	fr(i,1,k+1)
		pref[i] = pref[i-1] + dp[0][i];

	fr(i,1,n+1)
	{
		fr(j,0,k+1)
		{
			if(j > a[i-1])
				dp[i][j] += pref[j] - pref[j - a[i-1] - 1];
			else
				dp[i][j] += pref[j];
			
			dp[i][j] = dp[i][j] % MOD;
		}

		pref[0] = dp[i][0];
		fr(j,1,k+1)
				pref[j] = pref[j-1] + dp[i][j];
	}

	// cout << "\n";
	// fr(i,0,n+1)
	// {
	// 	fr(j,0,k+1)
	// 		cout << dp[i][j] << " ";
	// 	cout << "\n";
	// }

	cout << dp[n][k];
}

Measured memory_bytes: 80256
extern crate proconio;
use proconio::input;
fn main() {
    input!{
        n: usize,
        q: usize,
        query: [(u64, usize); q],
    }

    let arr = [(n-2) as u64; 200000];
    let mut tree_x = DualSegmentTree::new(&arr, n-2, std::cmp::min, (n-2) as u64, std::cmp::min);
    let mut tree_y = DualSegmentTree::new(&arr, n-2, std::cmp::min, (n-2) as u64, std::cmp::min);

    let mut ans = ((n-2)*(n-2)) as u64;
    for i in 0..q {
        match query[i] {
            (1, t) => {
                let mx = tree_y.get(t-2); 
                ans -= mx;
                tree_x.range_query(0, mx as usize, (t-2) as u64);
            },
            (2, t) => {
                let mx = tree_x.get(t-2);
                ans -= mx;
                tree_y.range_query(0, mx as usize, (t-2) as u64);
            },
            (_, _) => panic!(),
        }
    }

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

struct DualSegmentTree<T, U>{
    elements: Vec<u64>,
    size: usize,
    unite: T,
    operator: Vec<u64>,
    unit: u64,
    composite: U,
}

impl<T, U> DualSegmentTree<T, U> 
    where 
        U: Fn(u64, u64) -> u64,
        T: Fn(u64, u64) -> u64,
{
    pub fn new(arr: &[u64], n: usize, unite: T, unit: u64, composite: U ) -> DualSegmentTree<T, U>{
        let mut size: usize = 1;
        while size < n  {
            size <<= 1;
        }
        let mut elements = vec![0; size];
        for i in 0..n {
            elements[i] = arr[i];
        }
        let unit = unit;
        let operator = vec![unit; 2*size];
        DualSegmentTree{
            elements,
            size,
            unite,
            operator,
            unit,
            composite,
        }
    }

    // [l, r)での関数をセットする.
    pub fn range_query(&mut self, l: usize, r: usize, op: u64) {
        if l != r {
            self.sub_range(0, self.size, l, r, op);
        }
    }

    fn sub_range(&mut self, min: usize, max: usize, l: usize, r: usize, op: u64) -> u64{
        let mid = (min + max)/2;
        if l == min && r == max {
            self.operator[self.size/(r-l) + l/(r-l)] = (self.composite)(op, self.operator[self.size/(r-l) + l/(r-l)]);
            0
        }else{
            if l < mid && mid < r{
                self.sub_range(min, mid, l, mid, op) + self.sub_range(mid, max, mid, r, op)
            }else if mid <= l {
                self.sub_range(mid, max, l, r, op)
            }else if r <= mid {
                self.sub_range(min, mid, l, r, op)
            }else{
                panic!("invalid input: min: {}, max: {}, l: {}, r: {}", min, max, l, r );
            }
        }
    }

    pub fn get(&self, index: usize) -> u64{
        (self.unite)(self.elements[index], self.sub_get(index + self.size))
    }

    fn sub_get(&self, index: usize) -> u64 {
        if index == 0 {
            self.unit
        }else{
            (self.composite)(self.operator[index], self.sub_get(index >> 1))
        }
    }

    pub fn debug(&self) {
        println!("{:?}", self.operator);
    }
}

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

typedef long long  ll;

ll MOD = 1000000007;
ll INF = 100000000000;
double PI = 3.1415926535;

template<typename T>
void remove(std::vector<T>& vector, unsigned int index)
{
    vector.erase(vector.begin() + index);
}


int main(){
    ll N;cin >> N;
    vector<ll> A(N);
    ll memo = 10000000000;
    ll cnt = 0;
    ll sum = 0;
    for(int i = 0;i < N;i++){
        cin >> A[i];
        if(abs(A[i]) < memo){
            memo = abs(A[i]);
        }
        if(A[i] < 0){
            cnt++;
        }
        sum += abs(A[i]);
    }
    ll ans = 0;
    if(cnt % 2 == 0){
        cout << sum << endl;
    }else{
        cout << sum - 2 * memo << endl;
    }
}

Measured memory_bytes: 1024
(n,m),*t=[map(int,t.split())for t in open(0)]
*e,=eval('[],'*-~n)
for a,b in t:e[a]+=b,;e[b]+=a,
q=[g:=1]
f=q*2+[-1]*n
for v in q:
 for w in e[v]:
  if~f[w]:g&=f[v]^f[w]
  else:f[w]=f[v]^1;q+=w,
r=sum(f)
print((n*~-n//2,r*(n-r))[g]-m)

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

using namespace std;

int N,K,L;
int p[200001];
int Rank[200001];
map <pair<int,int>,int> ans;
int a[200001];
int b[200001];

void init() {
  for(int i = 0; i < N; i++) {
    p[i] = i;
    Rank[i] = 0;
  }
}

int Find (int x) {
  if(p[x] == x) return x;
  return p[x] = Find(p[x]);
}

void Union (int a, int b) {
  int x = Find(a);
  int y = Find(b);
  if(x == y) return;
  else {
    if(Rank[x] > Rank[y]) p[y] = x;
    else p[x] = y;
    if(Rank[x] == Rank[y]) Rank[x]++;
  }
}
    
    
    
  

int main () {
  cin >> N >> K >> L;

  init();
  for(int i = 0; i < K; i++){
    int a,b;
    cin >> a >> b;
    a--; b--;
    Union(a,b);
  }

  for(int i = 0; i < N; i++) a[i] = Find(i);

  init();

  for(int i = 0; i < L; i++) {
    int a,b;
    cin >> a >> b;
    a--; b--;
    Union(a,b);
  }

  for(int i = 0; i < N; i++) b[i] = Find(i);
 
  
  for(int i = 0; i < N; i++)  ans[make_pair(a[i],b[i])]++;

  for(int i = 0; i < N; i++)
    cout << ans[make_pair(a[i],b[i])] <<endl;
}
  

  


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

int main()
{
    int n1,n2,flag,i;
    string s,t;
    cin>>s;
    cin>>t;
    flag=0;
    n1=(int)(s.length());
    n2=(int)(t.length());
    if (n1<1 || n1>10 || n2-n1!=1) flag=1;
    for ( i = 0; i < n1; i++)
    {
        if (s[i]!=t[i])
        {
            flag=1;
            break;
        }
    }
    if (flag==0) cout<<"Yes"<<endl;
    else cout<<"No"<<endl;
}

Measured memory_bytes: 3628
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <string>
#include <string.h>
#include <bitset>
#include <map>
#include <climits>
#include <set>
#include <cmath>
#include <queue>

using namespace std;

int main()
{
    int N;
    cin >> N;

    queue<int> q;
    vector<int> visited(N, 0);
    vector<int> an(N + 1);
    for (int i = 1; i <= N; ++i)
    {
        cin >> an[i];
    }

    q.push(1);
    visited[1] = 1;

    int cnt = 0;
    while (!q.empty())
    {
        int i = q.front();
        q.pop();
        ++cnt;
        int next = an[i];
        if (next == 2)
        {
            cout << cnt << endl;
            return 0;
        }
        if (visited[next] == 1)
        {
            cout << -1 << endl;
            return 0;
        }
        else
        {
            visited[next] = 1;
        }
        q.push(next);
    }
    return 0;
}

Measured memory_bytes: 1024
#include<bits/stdc++.h>
using namespace std;
const int MOD=1000000007;
#define ll long long
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL);
int main()
{
ll n,x,t;
cin>>n>>x>>t;
if(n%x==0)
cout<< (n/x)*t <<endl;
else
cout<< (n/x+1)*t <<endl;
}


Measured memory_bytes: 3628
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
  int n;
  cin >> n;
  
  vector<int> v;
  while (n--) {
    int a;
    cin >> a;
    v.push_back(a);
  }
  sort(v.begin(), v.end());
  
  cout << v.back() - v.front() << endl;
}

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

typedef double du ;
typedef string st ;
typedef long long ll ;

int main ()
{
    int num1 , num2 ;

    cin >> num1 >> num2 ;

    if (num2 == num1 )
        cout << "Yes" << endl ;
    else
        cout << "No" << endl ;
    return 0 ;
}


Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <string>
#include <istream>
 
#define INPUT_FROM_FILE (0)
#if INPUT_FROM_FILE
#include <fstream>
#endif

//素数判定クラス
class PrimeTest{
private:
	std::vector<bool> is_prime_;					//nが素数かどうかをis_prime[n]で判定
	std::vector<unsigned int> prime_numbers_;		//素数の集合

public:
	PrimeTest();

	~PrimeTest();

	const std::vector<unsigned int>& get_prime_numbers() const;

	bool is_prime(unsigned int n);

};


PrimeTest::PrimeTest(){
	is_prime_.push_back(false);	//0
	is_prime_.push_back(false);	//1
	is_prime_.push_back(true);	//2
	is_prime_.push_back(true);	//3

	prime_numbers_.push_back(2);
	prime_numbers_.push_back(3);
}
PrimeTest::~PrimeTest(){}

const std::vector<unsigned int>& PrimeTest::get_prime_numbers() const{
	return prime_numbers_;
}

bool PrimeTest::is_prime(unsigned int n){
	if(n >= is_prime_.size()){
		unsigned int i_s = is_prime_.size();
		is_prime_.resize(n + 1, false);

		//i_sからnまでの各数が素数かどうか判定
		for(unsigned int i = i_s; i <= n; i++){
			unsigned int max_val = int(sqrt((double)i));
			bool b = true;
			for(unsigned int j = 0; j < prime_numbers_.size(); j++){
				if(prime_numbers_[j] > max_val){ break;}
				if(i % prime_numbers_[j] == 0){
					b = false;
					break;
				}
			}
			if(b){
				prime_numbers_.push_back(i);
				is_prime_[i] = true;
			}
		}

	}
	return is_prime_[n];
}

int count_prime(PrimeTest& prime_test, int n){
	int count = 0;

	for(int i = 2; i <= n; i++){
		if(prime_test.is_prime(i)){
			count++;
		}
	}
	return count;
}

 int main(int argc, char **argv){
	int n = 0;
	std::string buf;
	int count = 0;
	PrimeTest prime_test;
 
#if INPUT_FROM_FILE
	std::ifstream ifs("test.txt");
#endif
 
 
#if INPUT_FROM_FILE
	while(std::getline(ifs, buf)){
#else
	while(std::getline(std::cin, buf)){
#endif
		n = std::atoi(buf.c_str());
		count = count_prime(prime_test, n);

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


Measured memory_bytes: 3480
#include <iostream>
#include <cmath>

using namespace std;

int main() {
    double v, t;
    int y;
    while (cin >> v) {
        t = v / 9.8;
        y = ceil(4.9 * t * t);
        while (y % 5 != 0) {
            y++;
        }
        cout << y / 5 + 1 << endl;
    }

    return 0;
}

Measured memory_bytes: 1224
#include <bits/stdc++.h>
using namespace std;
#define ALL(a) (a).begin(),(a).end()
#define rALL(a) (a).rbegin(),(a).rend()
typedef pair<int, int> Pint;
typedef pair<int64_t, int64_t> Pll;
typedef int64_t ll;

int main() {
    string s;
    cin >> s;
    if (s.at(2) == s.at(3) && s.at(4) == s.at(5)){
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << endl;
    }
}


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

int main(){
    double n,ans=0;
    cin>>n;
    int a=1;
    while(a<=n){
        if(a%2==1)
        ans++;
        a++;
    }
    cout<<setprecision(8)<<ans/n<<endl;
    return 0;
}


Measured memory_bytes: 256
k = int( input() )

# a = 7
# for _ in range( 30 ):
#     print( a % k )
#     a = 10 * a + 7

rem_list = []
first_rem = 7 % k
a = 7
cnt = 0
while True:
    r = a % k
    cnt += 1
    if r == 0:
        print( cnt )
        break
    elif cnt > 2 and cnt > k:
        print( -1 )
        break
    else:
        a = ( 10 * r + 7 ) % k

Measured memory_bytes: 9112
def dijkstra(v, G):
    import heapq

    ret = [10 ** 10] * len(G)
    ret[v] = 0
    q = [(ret[i], i) for i in range(len(G))]
    heapq.heapify(q)

    while len(q):
        tmpr, u = heapq.heappop(q)
        if tmpr == ret[u]:
            for w, l in G[u]:
                if ret[w] > ret[u] + l:
                    ret[w] = ret[u] + l
                    heapq.heappush(q, (ret[w], w))
    return ret


H, W = map(int, input().split())
C = [list(map(int, input().split())) for _ in range(10)]
G = [[] for _ in range(10)]
for i in range(10):
    for j in range(10):
        if i != j:
            G[i].append((j, C[i][j]))

LUT = [dijkstra(i, G)[1] for i in range(10)]

ans = 0
for _ in range(H):
    for a in list(map(int, input().split())):
        if a != -1:
            ans += LUT[a]

print(ans)


Measured memory_bytes: 3188
#include<iostream>
#include<vector>
#include<algorithm>
int main(void) {
	int c;
	int g;
	std::cin >> c;
	std::vector<int> vv;
	vv.assign(c, 0);
	for (int l1 = 0; l1 < c; l1++)
		std::cin >> vv[l1];
	std::sort(vv.begin(), vv.end());
	int save = 0,count = 0,count_inner = 0;
	for (int l1 = 0; l1 < c; l1++) {
		if (save != vv[l1]) {
			if (count_inner >= save)
				count += count_inner - save;
			else
				count += count_inner;
			save = vv[l1];
			count_inner = 0;
		}
		count_inner++;
	}
	if (save != count_inner) {
		if (count_inner >= save)
			count += count_inner - save;
		else
			count += count_inner;
	}
	std::cout << count << std::endl;
}

Measured memory_bytes: 640
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cctype>
#include<math.h>
#include<string>
#include<string.h>
#include<stack>
#include<queue>
#include<vector>
#include<utility>
#include<set>
#include<map>
#include<stdlib.h>
#include<iomanip>

using namespace std;

#define ll long long
#define ld long double
#define EPS 0.0000000001
#define INF 1e9
#define MOD 1000000007
#define rep(i,n) for(int i=0;i<(n);i++)
#define loop(i,a,n) for(i=a;i<(n);i++)
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)

typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int,int> pii;

int gcd(int a, int b){
    if(b==0) return a;
    return gcd(b,a%b);
}
int lcm(int a, int b){
    return a*b/gcd(a,b);
}


int main(void) {
    int i,j;
    int n,m;
    cin >> n >> m;
    vector<vi> v(n,vi(2,0));
    rep(i,m){
        string s;
        cin >> s;
        rep(j,n)v[j][s[j] == 'E']++;
    }
    rep(i,n-1)v[i+1][0] += v[i][0], v[i+1][1] += v[i][1];

    int ans = 0, sum = v[n-1][0];
    loop(i,1,n){
        int t = v[i-1][1] + (v[n-1][0]-v[i-1][0]);
        if(t < sum)ans = i, sum = t;
    }
    if(v[n-1][1] < sum)ans = n, sum = v[n-1][1];
    cout << ans << " " << ans+1 << endl;
}



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

using namespace std;
using ll = long long;
using ull = unsigned long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vl = vector<ll>;
using vvl = vector<vl>;

void DDCC2019C()
{
	int N, W, K;
	cin >> N >> W >> K;
	vvi grid(N, vi(W));
	vi g(N);
	for (int i = 0; i < N; ++i)
	{
		string S;
		cin >> S;
		for (int j = 0; j < W; ++j)
		{
			if (S[j] == '#')
			{
				grid[i][j] = 1;
				++g[i];
			}
		}
	}
	vvi dst(N, vi(W));
	int n = N - 1;
	for (int i = N - 1; i > -1; --i)
	{
		if (g[i] != 0)
		{
			n = i;
			break;
		}
	}

	int prev = -1;
	int ct = 1;
	for (int i = 0; i <= n; ++i)
	{
		if (g[i] == 0)
		{
			continue;
		}
		int cc = 0;
		for (int j = 0; j < W; ++j)
		{
			if (cc == g[i])
			{
				for (int k = prev + 1; k <= i; ++k)
				{
					dst[k][j] = dst[k][j - 1];
				}
				continue;
			}
			for (int k = prev + 1; k <= i; ++k)
			{
				dst[k][j] = ct;
			}
			if (grid[i][j] != 0)
			{
				++cc;
				++ct;
			}
		}
		prev = i;
	}
	for (int i = n + 1; i < N; ++i)
	{
		for(int j = 0; j < W; ++j)
			dst[i][j] = dst[i - 1][j];
	}

	for (int i = 0; i < N; ++i)
	{
		for (int j = 0; j < W; ++j)
		{
			cout << dst[i][j];
			if (j < W - 1)
				cout << ' ';
		}
		cout << endl;
	}
}

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

Measured memory_bytes: 1536
#include <stdio.h>
  int main(){
   int x[10]={1,2,4,8,16,32,64,128,256,512};
   int n,i,sum=0;
    while(scanf("%d",&n) != EOF){
		int y[10]={};
     for(i=9;i>=0;i--){
		 if(n>=x[i]){  n -= x[i]; y[i]=1; sum++;}
       }
      for(i=0;i<10;i++){
		  if(y[i]==1) {sum--; if(sum!=0){printf("%d ",x[i]);}
		  else{printf("%d\n",x[i]);
		  }}}
	  sum=0;
}
return 0;
}

Measured memory_bytes: 1024
n = int(input())
xl = []
yl = []
for i in range(n):
    x,y = map(int,input().split())
    xl.append((x,i))
    yl.append((y,i))

xl = sorted(xl)
yl = sorted(yl)

import heapq
al = []
for i in range(n-1):
    al.append((abs(xl[i+1][0] - xl[i][0]), xl[i][1], xl[i+1][1]))
    al.append((abs(yl[i+1][0] - yl[i][0]), yl[i][1], yl[i+1][1]))

heapq.heapify(al)

class UnionFind():
   def __init__(self, n):
       self.n = n
       self.parents = [-1] * n

   def find(self, x):
       if self.parents[x] < 0:
           return x
       else:
           self.parents[x] = self.find(self.parents[x])
           return self.parents[x]

   def union(self, x, y):
       x = self.find(x)
       y = self.find(y)

       if x == y:
           return

       if self.parents[x] > self.parents[y]:
           x, y = y, x

       self.parents[x] += self.parents[y]
       self.parents[y] = x

   def size(self, x):
       return -self.parents[self.find(x)]

   def same(self, x, y):
       return self.find(x) == self.find(y)

   def members(self, x):
       root = self.find(x)
       return [i for i in range(self.n) if self.find(i) == root]

   def roots(self):
       return [i for i, x in enumerate(self.parents) if x < 0]

   def group_count(self):
       return len(self.roots())

   def all_group_members(self):
       return {r: self.members(r) for r in self.roots()}

   def __str__(self):
       return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

uf = UnionFind(n)

ans = 0
for i in range(n-1):
    while True:
        c, a, b = heapq.heappop(al)
        if not uf.same(a, b):
            ans += c
            uf.union(a,b)
            break

print(ans)

Measured memory_bytes: 50748
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.Math;

public class Main {
    public static void main(String[] args) {
        try {
            BufferedReader stdReader = new BufferedReader(new InputStreamReader(System.in));
            
            String line;
            int count = 0;
            int n = 0;
            while((line = stdReader.readLine()) != null) {
                // ?????????????????°???????????????
                if(count == 0) {
                    n = Integer.parseInt(line);
                    count++;
                    continue;
                }
                
                String[] input = line.split(" ", 0);
                
                int min = 1000000;
                int max = -1000000;
                long sum = 0;
                for(int i = 0; i < n; i++) {
                    int x = Integer.parseInt(input[i]);
                    // ????°????
                    if(x < min) {
                        min = x;
                    }
                    // ?????§???
                    if(x > max) {
                        max = x;
                    }
                    // ????¨?
                    sum += Long.parseLong(input[i]);
                }
                
                System.out.println(min + " " + max + " " + sum);
                
            }
            stdReader.close();
        } catch(Exception e) {
            e.getStackTrace();
            System.exit(-1);
        }
    }
}

Measured memory_bytes: 28740
n,m,x = map(int,input().split())
a = [int(i) for i in input().split()]

ans1 = 0
ans2 = 0

for i in range(x+1,n+1):
  if i in a:
    ans1 += 1

for j in range(x):
  if j in a:
    ans2 += 1
    
ans = min(ans1,ans2)
  
  
print(ans)

Measured memory_bytes: 3064
#include "bits/stdc++.h"
#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i,N) for(LL i=0;i<N;++i)
typedef long long int LL;

int A, B, C;

int main()
{
	in >> A >> B >> C;
	if (C >= A&&C <= B)
	{
		out << "Yes" << std::endl;
	}
	else
	{
		out << "No" << std::endl;
	}
	return 0;
}

Measured memory_bytes: 256
from bisect import bisect_right, bisect_left
A, B, Q = map(int, input().split())
INF = 10**18

S = [-INF] + [int(input()) for _ in range(A)] + [INF]
T = [-INF] + [int(input()) for _ in range(B)] + [INF]

for _ in range(Q):
    x = int(input())

    lS, lT = S[bisect_right(S, x) - 1], T[bisect_right(T, x) - 1]
    rS, rT = S[bisect_left(S, x)], T[bisect_left(T, x)]

    ans = min(
        abs(lS - lT) + (x - max(lS, lT)),
        abs(rS - rT) + (min(rS, rT) - x),
        (rT - lS) + min(x - lS, rT - x),
        (rS - lT) + min(x - lT, rS - x)
    )

    print(ans)


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

using namespace std;

int main() {
  int A, B;
  size_t K;
  cin >> A >> B >> K;

  vector<int> v;
  int upper = min(A, B);
  for (int i = 1; i <= upper; ++i) {
    if (((A % i) == 0) && ((B % i) == 0)) {
      v.push_back(i);
    }
  }
  if (K <= v.size()) {
    cout << v[v.size() - K] << endl;
  }
  return 0;
}


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

int main()
{
  int n, r;
  for ( ; ; ) {
    cin >> n >> r;
    if (n == 0 && r == 0)
      break;

    vector<int> Card;
    for (int i = n; i > 0; --i)
      Card.push_back(i);

    for (int i = 0; i < r; ++i) {
      int p, c;
      cin >> p >> c;
      vector<int> Card_new;
      for (int j = 0; j < c; ++j) {
	Card_new.push_back(Card[p-1]);
	Card.erase(Card.begin() + p - 1);
      }
      for (unsigned int j = 0; j < Card.size(); ++j)
	Card_new.push_back(Card[j]);
      Card = Card_new;
    }
    cout << Card[0] << endl;
  }
  return 0;
}

Measured memory_bytes: 0
#include <iostream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <iomanip> // cout<<setprecision(n)
#include <functional> // std::function<void(int)>
using namespace std;
#define All(v) (v).begin(),(v).end()
const long long mod = 1000000007;
const long long inf = mod*mod;
const double EPS=1e-10;
const double INF=1e+10;
const double PI=acos(-1.0);
signed main(){
    int n,k;
    cin>>n>>k;
    int A[1000000];
    for(int i=0;i<n;i++)cin>>A[i];
    map<int,int> d;
    for(int i=0;i<n;i++)d[A[i]]++;
    vector<int> v;
    for(auto it:d)v.push_back(it.second);
    sort(All(v),greater<int>());
    if(v.size()<=k)cout<<0<<endl;
    else{
        int res=0;
        for(int i=k;i<v.size();i++)res+=v[i];
        cout<<res<<endl;
    }
}

Measured memory_bytes: 13308
/*
 *  author : Atul Anand   
 *  created on : Wed Apr 01 2020
 */

import java.io.*;
import java.util.*;

public class Main{

    public static void main(String[] args) throws IOException {
        int A = in.nextInt();
        int B = in.nextInt();
        if(A >= 1 && A <= 9 && B >= 1 && B <= 9){
            println(A*B);
        }
        else{
            println(-1);
        }
        
        in.close();
        out.close();
    }

    static int MIN = Integer.MIN_VALUE;
    static int MAX = Integer.MAX_VALUE;
    static Reader in = new Reader();
    static PrintWriter out = new PrintWriter(System.out);

    static void read(int arr[], int N) throws IOException { 
    	for(int i = 0; i < N; i++){ 
    		arr[i] = in.nextInt(); 
    	} 
    }
    
    static void read(long arr[], int N) throws IOException { 
    	for(int i = 0; i < N; i++){ 
    		arr[i] = in.nextLong(); 
    	} 
    }
    
    static void read(String arr[], int N) throws IOException { 
    	for(int i = 0; i < N; i++){ 
    		arr[i] = in.next(); 
    	} 
    }
    
    static void print(Object O) {  
    	out.print(O); 
    }
    
    static void println(Object O) { 
    	out.println(O); 
    }
    
    static void println(int arr[]) { 
    	for(int i = 0; i < arr.length; i++){ 
    		print(arr[i]+" "); 
    	} 
    	println(""); 
    }

    static void println(int arr[][]) { 
    	for(int i = 0; i < arr.length; i++){ 
    		println(arr[i]); 
    	}
    }
    
    static void debug(Object O) { 
    	System.out.println(O); 
    }
}

class Reader {
    BufferedReader reader;
    StringTokenizer tokenizer;

    Reader() {
        reader = new BufferedReader(new InputStreamReader(System.in));
        tokenizer = new StringTokenizer("");
    }

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

    int nextInt() throws IOException { 
        return Integer.parseInt(next()); 
    }
    
    double nextDouble() throws IOException { 
        return Double.parseDouble(next());
    }
    
    long nextLong() throws IOException { 
        return Long.parseLong(next()); 
    }
    
    String nextLine() throws IOException { 
        return reader.readLine(); 
    }
    
    void close() throws IOException { 
        reader.close(); 
    }
}

Measured memory_bytes: 22868
N = int(input())
H = list(map(int, input().split()))
flag = True
for i in range(N-2, 0, -1):
    defe = H[i] - H[i+1]
    if defe > 1:
        flag = False
        break
    elif defe == 1:
        H[i] -= 1
print('Yes' if flag else 'No')


Measured memory_bytes: 63984
/*

Author : @karngyan
Team : BlundersPride
Date : 02-03-2019
Time : 00:02:04

*/


#include<bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//using namespace __gnu_pbds;
//typedef tree<int,null_type,less<int>,rb_tree_tag,
//tree_order_statistics_node_update> indexed_set;
using namespace std;

typedef long long ll;
typedef long double ld;
typedef std::vector<ll> vll;
typedef std::pair<ll,ll> pll;
typedef std::vector<vll> vvll;

#define fast ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
#define endl '\n'
#define pb push_back
#define rep(i,a,b) for(ll i=a;i<b;++i)
#define rrep(i,a,b) for(ll i=a;i>b;--i)
#define max3( a, b, c ) max( a , max(b , c))
#define cres(c,n) (c).clear(),(c).resize(n)
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
#define ff first
#define ss second
#define mk make_pair

vector<char> v;

signed main()
{
	fast;
////////////////////////////////////////////////////////////////////////////////////////////
	
	string s;
	cin >> s;
	ll ans = 0;
	v.pb(s[0]);
	ll n = s.size();
	char last = s[0];
	rep(i,1,n)
	{
		char cur = s[i];
		if(last == 'x')
		{
			last = s[i];
			v.pb(last);
			continue;
		}

		if((cur == '1' and last == '0') or (last == '1' and cur == '0'))
		{
			if(v.size() != 0)
			{
				v.pop_back();
				if(v.size()!=0)
					last = v[v.size() - 1];
				else
					last = 'x';
			}
		}
		else
		{
			v.pb(s[i]);
			last = s[i];
		}
	}

	cout<<n - v.size()<<endl;






////////////////////////////////////////////////////////////////////////////////////////////
	
	return 0;
}



Measured memory_bytes: 592
#include<iostream>
#include<iomanip>
#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
#include<vector>
#include<array>
#include<string>
#include<stack>
#include<queue>
#include<algorithm>
#include<cassert>
#include<functional>
#include<random>
#include<complex>
#include<bitset>
#include<chrono>
//#include<boost/multiprecision/cpp_int.hpp>
#define int int64_t
#define uint uint64_t
#define REP(i, a, b) for (int64_t i = (int64_t)(a); i < (int64_t)(b); i++)
#define rep(i, a) REP(i, 0, a)
#define EACH(i, a) for (auto i: a)
#define ITR(x, a) for (auto x = a.begin(); x != a.end(); x++)
#define ALL(a) (a.begin()), (a.end())
#define HAS(a, x) (a.find(x) != a.end())
#define Min(x) *min_element(ALL(x))
#define Max(x) *max_element(ALL(x))
#define Unique(L) (L.erase(unique(ALL(L)), L.end()))
#define veccat(v1, v2) std::copy((v2).begin(),(v2).end(),std::back_inserter(v1)/*v1の後ろにv2を入れる*/)
#define intmax (std::numeric_limits<int64_t>::max() / 4)
using namespace std;
//typedef boost::multiprecision::cpp_int bigint;
const double EPS = 1e-9;
const double PI = acos(-1.0);



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

	int H, W, h, w;
	cin >> H >> W >> h >> w;

	if ((H%h) == 0 && (W%w) == 0) {
		cout << "No" << endl;
		return 0;
	}
	vector<vector<int>>ans(H, vector<int>(W, 0));
	if (H%h) {
		rep(i, W) {
			int count = 0;
			rep(j, H) {
				count++;
				if (count < h)ans[j][i] = 10000;
				else {
					ans[j][i] = -(count - 1) * 10000 - 1;
					count = 0;
				}
			}
		}
	}
	else {
		rep(i, H) {
			int count = 0;
			rep(j, W) {
				count++;
				if (count < w)ans[i][j] = 10000;
				else {
					ans[i][j] = -(count-1) * 10000 - 1;
					count = 0;
				}
			}
		}
	}
	cout << "Yes" << endl;
	rep(i, H) {
		rep(j, W) {
			if (j)cout << " ";
			cout << ans[i][j];
		}
		cout << endl;
	}

	return 0;
}





Measured memory_bytes: 3840
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def f(n):
        res = set([1])
        i = 2
        m = n
        while i**2 <= n:
            while m%i == 0:
                res.add(i)
                m //= i
            i += 1
        res.add(m)
        return res

    a,b = LI()
    fa = f(a)
    fb = f(b)
    l = fa&fb
    print(len(l))
    return

#Solve
if __name__ == "__main__":
    solve()


Measured memory_bytes: 38512
cards = []
suits = ['S', 'H', 'C', 'D']
suits.each do |s|
  (1..13).each do |i|
    cards << "#{s} #{i}"
  end
end
input_cards = []
n = gets.chomp.to_i
n.times do
  input_cards << gets.chomp
end
puts cards - input_cards



Measured memory_bytes: 6872
fn read_stdin() -> String {
    use std::io::Read;
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input).unwrap();
    input
}

fn scan<'a, I: Iterator<Item = &'a str>, T: std::str::FromStr>(tokens: &mut I) -> T {
    tokens.next().unwrap().parse().ok().unwrap()
}

fn vec<T, F: FnMut(usize) -> T>(n: usize, mut f: F) -> Vec<T> {
    (0..n).map(|i| f(i)).collect()
}

fn main() {
    let input = read_stdin();
    let tokens = &mut input.split_whitespace();
    let n: usize = scan(tokens);
    let q: Vec<usize> = {
        let mut q = vec![0; n + 1];
        for i in 1..n + 1 {
            let p: usize = scan(tokens);
            q[p] = i;
        }
        q
    };
    let mut l: Vec<usize> = vec(n + 2, |i| std::cmp::max(i, 1) - 1);
    let mut r: Vec<usize> = vec(n + 2, |i| std::cmp::min(i, n) + 1);
    let mut ans: usize = 0;
    for p in 1..n {
        let c = q[p];
        let b = l[c];
        let a = l[b];
        let d = r[c];
        let e = r[d];
        ans += p * (b - a) * (d - c);
        ans += p * (c - b) * (e - d);
        l[d] = b;
        r[b] = d;
    }
    println!("{}", ans);
}


Measured memory_bytes: 8444
fun main(args:Array<String>) {
    val (n,t) = readLine()!!.split(" ").map { it.toLong() }
    val oyu = readLine()!!.split(" ").map { it.toLong() }
    var ans = 0L
    var prev = t * -1
    oyu.forEach {
        ans += Math.min(t, it-prev)
        prev = it
    }
    println(ans)
}


Measured memory_bytes: 81820
object Main {
  def main(args: Array[String]): Unit = {
    val counts = new Array[Int]('z' - 'a' + 1)

    Iterator.continually(io.StdIn.readLine())
      .takeWhile(Option(_).exists(_.nonEmpty))
      .foreach(_.foreach { c =>
        if ('A' <= c && c <= 'Z') {
          counts(c - 'A') += 1
        } else if ('a' <= c && c <= 'z') {
          counts(c - 'a') += 1
        }
      })

    counts
      .zipWithIndex
      .map { case (s, i) => s"${('a' + i).toChar} : $s" }
      .foreach(println)
  }
}

Measured memory_bytes: 43960
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define rrep(i,a,b) for(ll i=a;i>=b;i--)
#define fore(i,a) for(auto &i:a)
#define all(x) (x).begin(),(x).end()

ll dp[100000];

int main(void){
    ll n, m;
    cin >> n >> m;

    string s;
    cin >> s;

    vector<ll> ans;
    bool flag;
    rrep(i, n, 1){
        if(s[i] == '1')continue;
        flag = true;
        rrep(j, min(i, m), 1){
            if(s[i - j] == '0'){
                i = i - j + 1;
                ans.push_back(j);
                flag = false;
                break;
            }
        }
        if(flag){
            cout << -1 << endl;
            return 0;
        }
    }

    while(ans.size()){
        ll tmp = ans.back();
        ans.pop_back();
        cout << tmp << " ";
    }

    cout << endl;
    return 0;
}


Measured memory_bytes: 1528
#include<iostream>
#include<stack>

using namespace std;

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

	stack<char> stk;
	for(int i = 0; i < s.size(); ++i){
		if(s[i] == 'S')
			stk.push(s[i]);
		else{
			if(stk.empty() || stk.top() == 'T')
				stk.push(s[i]);
			else
				stk.pop();
		}
	}
	cout << stk.size() << '\n';
	return 0;
}


Measured memory_bytes: 3744
#include<stdio.h>


int main(void)
{
	int w,h,x,y,r;
	scanf("%d %d %d %d %d",&w,&h,&x,&y,&r);
	if(x+r<=w && x-r>=0 && y+r<=h && y-r>=0){printf("Yes\n");}
	else{printf("No\n");}
	return 0;
}

Measured memory_bytes: 584
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase #-}
module Main where

import           Data.List
import           Control.Monad
import           Debug.Trace
import qualified Data.ByteString.Char8         as BC
import           Data.Maybe                     ( fromJust )
import qualified Data.Set                      as S
import qualified Data.IntMap.Strict            as IM
import qualified Data.IntMap.Lazy            as IML
import qualified Data.Map.Strict               as M
import           Data.Char
import qualified Data.Array.IArray as A
import qualified Data.Array.Unboxed as UA
import Data.Bits
import Control.Monad.State.Strict
import qualified Data.Array.ST as STA
import qualified Data.Array.MArray as MA
import Control.Monad.ST



readTuple2 :: IO (Int, Int)
readTuple2 = do
    [a, b] <- map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine
    return (a, b)

readTuple3 :: IO (Int, Int, Int)
readTuple3 = do
    [a, b, c] <- map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine
    return (a, b, c)

readInt :: IO Int
readInt = fst . fromJust . BC.readInt <$> BC.getLine

readInts :: IO [Int]
readInts = map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine

split :: (a -> Bool) -> [a] -> [[a]]
split f [] = []
split f as =
    let (fo, la) = span f as
        las      = case la of
            [] -> []
            xs -> split f $ tail xs
    in  case fo of
            [] -> las
            xs -> xs : las


main :: IO ()
main = do
    s <- getLine
    putStrLn $ if s == "ABC" then "ARC" else "ABC"





Measured memory_bytes: 3752
#ABC-123-B
cook_times = []
mod_times = []
for _ in range(5):
    cook_time = int(input())
    mod_ten = cook_time % 10
    if mod_ten == 0:
        mod_ten = 124
    cook_times.append(cook_time)
    mod_times.append(mod_ten)
    
min_mod = mod_times.index(min(mod_times))

for i in range(5):
    if i == min_mod:
        continue
    if cook_times[i] % 10 != 0:
        cook_times[i] = (cook_times[i] // 10) * 10 + 10
    
print(sum(cook_times))

Measured memory_bytes: 3064
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
const ll inf = 1e18;
vector<pair<int, int> > e1[N];
vector<pair<int, int> > e2[N];
ll a[N], b[N];
bool flag[N];
int n, m, s, t;
void spfa(int s, int t, vector<pair<int, int> > e[], ll d[]) {
	memset(flag, 0, sizeof(flag));
	for (int i = 1; i <= n; i++) d[i]=inf;
	queue<int> q;
	q.push(s);
	d[s] = 0;
	flag[s] = true;
	while (!q.empty()) {
		int u = q.front();
		q.pop();
		flag[u] = false;
		for (auto t : e[u]) {
			int v = t.first;
			int w = t.second;
			if (d[u] + w < d[v]) {
				d[v] = d[u] + w;
				if (!flag[v]) {
					flag[v] = true;
					q.push(v);
				}
			}
		}
	}
}

int main() {
	scanf("%d%d%d%d", &n, &m, &s, &t);
	for (int i = 0; i < m; i++) {
		int u, v, a, b;
		scanf("%d%d%d%d", &u, &v, &a, &b);
		e1[u].emplace_back(v, a);
		e1[v].emplace_back(u, a);
		e2[u].emplace_back(v, b);
		e2[v].emplace_back(u, b);
	}
	spfa(s, t, e1, a);
	spfa(t, s, e2, b);
	set<pair<ll, int> > S;
	for (int i = 1; i <= n; i++) S.insert(make_pair(a[i]+b[i], i));
	ll sum = 1e15;
	for (int i = 0; i < n; i++) {
		while ((*S.begin()).second <= i) S.erase(S.begin());
		printf("%lld\n", sum-(*S.begin()).first);
	}
	return 0;
}


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

int main() {
    int a, b, c, d;
    cin >> a >> b >> c >> d;
    int i=0;
    while(a>0 && c>0){
        if(i % 2 == 0){
            c -= b;
        }else{
            a -= d;
        }
        i++;
    }
    if(c <= 0) cout << "Yes" << endl;
    else cout << "No" << endl;
    return 0;
}

Measured memory_bytes: 3672
from functools import lru_cache

X, Y, A, B, C = [int(x) for x in input().split()]
P = [int(x) for x in input().split()]
Q = [int(x) for x in input().split()]
R = [int(x) for x in input().split()]

P.sort(reverse=True)
Q.sort(reverse=True)
R.sort(reverse=True)

red = P[:X]
green = Q[:Y]
best = sum(red) + sum(green)

for x in R:
    a1, a2 = red, green
    if not a1 and not a2:
        break
    if not a1:
        a1 = a2
    if a1 and a2 and a1[-1] > a2[-1]:
        a1, a2 = a2, a1
    if a1[-1] < x:
        best -= a1.pop()
        best += x
print(best)


Measured memory_bytes: 104676
#include<bits/stdc++.h>
#define x first
#define y second
#define pii pair<LL,LL>
#define getchar getchar_unlocked
#define rev(X) reverse(X+1,X+n+1)
#define mem(a,b) memset(a,b,sizeof(a))
#define Get_y(i) 2ll*(f[i]+s[i])+1ll*i*i-i
#define  For(i,a,b) for(int i=a,i##E=b;i<=i##E;++i)
#define rFor(i,a,b) for(int i=a,i##E=b;i>=i##E;--i)
typedef long long LL;
using namespace std;
const int N=300010;
template<typename T>inline bool chkmin(T &a,const T &b){return a>b?a=b,1:0;}
template<typename T>inline bool chkmax(T &a,const T &b){return a<b?a=b,1:0;}
template<typename T>inline void read(T &x)
{
	x=0;register char ch=getchar();
	while(!isdigit(ch))ch=getchar();
	while( isdigit(ch))x=x*10+ch-'0',ch=getchar();
}
inline void file()
{
#ifdef ztzshiwo
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);
#endif
}
int n,m,top;
LL a[N],f[N],g[N],F[N],s[N],tmp[N];
pii q[N];
inline LL Query(LL i)
{
	while(top>=2&&q[top].y-q[top-1].y<=2ll*i*(q[top].x-q[top-1].x))top--;
	return q[top].x;
}
inline void Push(pii a)
{
	while(top>=2&&(q[top].y-q[top-1].y)*(a.x-q[top-1].x)
				<=(a.y-q[top-1].y)*(q[top].x-q[top-1].x))top--;
	q[++top]=a;
}
inline void Get_s(){For(i,1,n)s[i]=s[i-1]+a[i];}
inline void Get_f(LL *f)
{
	Push(pii(0,0));
	For(i,1,n)
	{
		LL j=Query(i);
		f[i]=max(f[i-1],f[j]+(i-j+1)*(i-j)/2-s[i]+s[j]);
		Push(pii(i,Get_y(i)));
	}
	top=0;
}
inline void Solve(int l,int r)
{
	if(l==r){chkmax(F[l],f[l-1]+g[l+1]+1-a[l]);return;}
	int mid=(l+r)>>1;
	For(i,l,mid)Push(pii(i,Get_y(i)));
	For(i,mid+1,r)
	{
		LL j=Query(i);
		tmp[i]=f[j]+(i-j+1)*(i-j)/2-s[i]+s[j]+g[i+1];
	}
	rFor(i,r,mid+1)
	{
		if(i^r)chkmax(tmp[i],tmp[i+1]);
		chkmax(F[i],tmp[i]);
	}
	top=0;
	Solve(l,mid);Solve(mid+1,r);
}
int main()
{
	int x,y;
	file();
	read(n);
	For(i,1,n)read(a[i]),F[i]=1-a[i];
	Get_s();
	Get_f(f);rev(a);Get_s();
	Get_f(g);rev(a);Get_s();rev(g);
	Solve(0,n);
	swap(f,g);
	rev(f);rev(g);rev(F);rev(a);Get_s();
	Solve(0,n);
	rev(f),rev(g),rev(F);rev(a);Get_s();
	swap(f,g);
	read(m);
	For(i,1,m)
	{
		read(x),read(y);
		printf("%lld\n",max(f[x-1]+g[x+1],F[x]+a[x]-y));
	}
	return 0;
}


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

using namespace std;

const int max_n = 200222, inf = 1000111222;

int n, col[max_n], ans[max_n];
vector<int> all[2], allv[2];
vector<int> g[max_n];

void dfs(int v, int p) {
    allv[col[v]].push_back(v);
    for (int to : g[v]) {
        if (to == p) {
            continue;
        }
        col[to] = col[v] ^ 1;
        dfs(to, v);
    }
}

bool cmp(int a, int b) {
    return a % 3 < b % 3;
}

int main() {
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    scanf("%d", &n);
    for (int i = 1; i < n; ++i) {
        int u, v;
        scanf("%d%d", &u, &v);
        --u;
        --v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    for (int i = 1; i <= n; ++i) {
        all[(i % 3) == 2].push_back(i);
    }
    dfs(0, -1);
    int c = 0;
    if (allv[1].size() > allv[0].size()) {
        c = 1;
    }
    if (allv[c].size() <= all[0].size()) {
        sort(all[0].begin(), all[0].end(), cmp);
        for (int v : allv[c]) {
            ans[v] = all[0].back();
            all[0].pop_back();
        }
        for (int v : allv[c ^ 1]) {
            if (!all[0].empty()) {
                ans[v] = all[0].back();
                all[0].pop_back();
            } else {
                ans[v] = all[1].back();
                all[1].pop_back();
            }
        }
    } else {
        all[0].clear();
        all[1].clear();
        for (int i = 1; i <= n; ++i) {
            all[(i % 3) >= 1].push_back(i);
        }
        for (int v : allv[c ^ 1]) {
            ans[v] = all[0].back();
            all[0].pop_back();
        }
        for (int v : allv[c]) {
            if (!all[0].empty()) {
                ans[v] = all[0].back();
                all[0].pop_back();
            } else {
                ans[v] = all[1].back();
                all[1].pop_back();
            }
        }
    }
    for (int i = 0; i < n; ++i) {
        printf("%d ", ans[i]);
    }
    puts("");
    return 0;
}


Measured memory_bytes: 20860
N , M = map(int, input().split())
mod = 10 ** 9 + 7


def factorial(n):
    ans = 1
    for i in range(2, n + 1):
        ans = ans * i % mod
    return ans


if abs(N - M) >1:
    print(0)
elif N == M:
    print(2 * factorial(N) ** 2 % mod)
else:
    print(factorial(min(M, N)) ** 2 * max(M, N) % mod)

Measured memory_bytes: 3064
# coding: utf-8
import time
import re
import math

def main():
    n=int(input())
    A=list(map(int,input().split()))
    total=0
    m=1
    for a in A:
        m*=a
    m-=1
    for a in range(n):
        mod=A[a]
        total+=m%mod
    print(total)
main()

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

# define REP(i,n) for (int i=0;i<(n);++i)
# define rep(i,a,b) for(int i=a;i<(b);++i)
# define p(s) std::cout << s ;
# define pl(s)  std::cout << s << endl;
# define printIf(j,s1,s2) cout << (j ? s1 : s2) << endl;
# define YES(j) cout << (j ? "YES" : "NO") << endl;
# define Yes(j) std::cout << (j ? "Yes" : "No") << endl;
# define yes(j) std::cout << (j ? "yes" : "no") << endl;
# define all(v) v.begin(),v.end()
# define showVector(v) REP(i,v.size()){p(v[i]);p(" ")} pl("")
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 int ll;
typedef pair<ll,ll> P_ii;
typedef pair<double,double> P_dd;

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

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

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


const int MOD = 1000000007;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;

void addM(long long &a, long long b) {
    a += b;
    if (a >= MOD) a -= MOD;
}

void mulM(long long &a, long long b) {
    a = ((a%MOD)*(b%MOD))%MOD ;
}

const int MAX = 510000;
long long fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit() {
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}

// 二項係数計算
long long COM(int n, int k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}

vector<pair<long long, long long> > prime_factorize(long long n) {
    vector<pair<long long, long long> > res;
    for (long long p = 2; p * p <= n; ++p) {
        if (n % p != 0) continue;
        int num = 0;
        while (n % p == 0) { ++num; n /= p; }
        res.push_back(make_pair(p, num));
    }
    if (n != 1) res.push_back(make_pair(n, 1));
    return res;
}


int main() {
    int N;
    cin >> N;
    
    double ans = 0;
    REP(i, N) {
        double a;
        cin >> a;
        ans += 1.0 / a;
    }

    printf("%.8f\n", 1.0 / ans);


    return 0;
}


Measured memory_bytes: 256
#include<iostream>
#include<string>

using namespace std;
int main() {
	int A;
	int B;
	cin >> A >> B;
	if (A == 1 && B == 2) {
		cout << "3" << endl;
	}
	if (A == 1 && B == 3) {
		cout << "2" << endl;
	}
	if (A == 2 && B == 1) {
		cout << "3" << endl;
	}
	if (A == 2 && B == 3) {
		cout << "1" << endl;
	}
	if (A == 3 && B == 1) {
		cout << "2" << endl;
	}
	if (A == 3 && B == 2) {
		cout << "1" << endl;
	}




}

Measured memory_bytes: 256
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <numeric>
#include <functional>
#include <unordered_set>
#include <unordered_map>
#include <tuple>
#include <climits>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <deque>
#include <complex>
#include <string>
#include <iomanip>
#include <sstream>
#include <bitset>
#include <valarray>
#include <iterator>

using namespace std;

typedef long long ll;

int p, q, a, n;

int Dfs(int sum_p, int sum_q, int sum_a, int cnt, int bf_p) {
    if (cnt > n)
        return 0;
    if (p == sum_p && q == sum_q)
        return 1;

    int res = 0;
    for (int i = bf_p; i * sum_a <= a; ++i) {
        if (q * (i * sum_p + (n - cnt) * sum_q) < p * (i * sum_q))
            break;
        else if (q * (sum_p * i + sum_q) <= p * (sum_q * i)) {
            int x = __gcd(sum_p * i + sum_q, sum_q * i);
            res += Dfs((sum_p * i + sum_q) / x, (sum_q * i) / x, i * sum_a, cnt + 1, i);
        }
    }

    return res;
}

int main()
{
    while (cin >> p >> q >> a >> n) {
        if (p == 0 && q == 0 && a == 0 && n == 0)
            break;

        int x = __gcd(p, q);
        p = p / x;
        q = q / x;
        int res = 0;
        for (int i = 1; i <= a; ++i) {
            if (q <= p * i)
                res += Dfs(1, i, i, 1, i);
        }
        cout << res << endl;
    }
    return 0;
}

Measured memory_bytes: 1160
import java.util.Scanner;

public class Main{
	private static Scanner scan;
	public static void main(String[] args) {
		double a[] = new double[8];
		scan = new Scanner(System.in);
		int n = Integer.parseInt(scan.next());
		for(int i = 0;i < n;i++){
			for(int j = 0;j < 8;j++)a[j] = Double.parseDouble(scan.next());
			double ab = (a[3] - a[1]) /(a[2] - a[0]);
			double cd = (a[7] - a[5]) /(a[6] - a[4]);
			if(ab == cd){
				System.out.println("YES");
			}else{
				System.out.println("NO");
			}
		}
		System.exit(0);
	}

}

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

using namespace std;

int main() {
    int N;
    cin >> N;
    vector <int> p(N);
    int cnt = 0;
    for (int i = 0; i < N; ++i) {
        cin >> p[i];
        if (p[i] != i + 1) {
            cnt++;
        }
    }
    if (cnt <= 2) cout << "YES" << endl;
    else cout << "NO" << endl;
    return 0;
}



Measured memory_bytes: 256