akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <climits>
#include <cfloat>
using namespace std;

int main()
{
    for(;;){
        int n, m;
        cin >> n >> m;
        if(n == 0)
            return 0;

        vector<int> p(n);
        for(int i=0; i<n; ++i)
            cin >> p[i];

        vector<int> num = p;
        num.push_back(0);
        for(int i=0; i<n; ++i){
            for(int j=0; j<=i; ++j){
                num.push_back(p[i] + p[j]);
            }
        }
        sort(num.begin(), num.end());

        int ret = 0;
        unsigned j = num.size() - 1;
        for(unsigned i=0; i<num.size(); ++i){
            if(num[i] > m)
                break;
            while(num[i] + num[j] > m)
                -- j;
            ret = max(ret, num[i] + num[j]);
        }
        cout << ret << endl;
    }
}

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

using namespace std;

int main() {
    cin.tie(nullptr); ios::sync_with_stdio(false);

    int N; cin>>N;
    vector<pair<long, long>> AB(N);
    for (size_t i = 0; i < N; i++) {
        cin>>AB[i].first >> AB[i].second;
    }
    sort(AB.begin(), AB.end(), [](auto l, auto r) {return l.second < r.second;});

    long time = 0;
    bool ans = true;
    for (size_t i = 0; i < N; i++) {
        time += AB[i].first;
        if (time > AB[i].second) {
            ans = false;
            break;
        }
    }
    cout << (ans ? "Yes" : "No") << endl;

    return 0;
}


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

typedef long long ll;

int main()
{
    ll N;
    cin >> N;
    string S;
    vector<ll> c(5, 0);
    for(int i=0;i<N;i++){
        cin >> S;
        if(S[0]=='M') c[0]++;
        if(S[0]=='A') c[1]++;
        if(S[0]=='R') c[2]++;
        if(S[0]=='C') c[3]++;
        if(S[0]=='H') c[4]++;
    }
    ll res = 0;
    res += c[0] * c[1] * c[2];
    res += c[0] * c[1] * c[3];
    res += c[0] * c[1] * c[4];
    res += c[0] * c[2] * c[3];
    res += c[0] * c[2] * c[4];
    res += c[0] * c[3] * c[4];
    res += c[1] * c[2] * c[3];
    res += c[1] * c[2] * c[4];
    res += c[1] * c[3] * c[4];
    res += c[2] * c[3] * c[4];
    cout << res << endl;

    return 0;
}

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

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

	vector<int> a(n);
	for(int i=0;i<n;i++)
		cin >> a[i];
	sort(a.begin(), a.end());
	int t=0;
	vector<int> kasane(n);
	for(int i = 0; i < n; i++) {
		if(a[i] != a[t])
			t=i;
		kasane[t]++;
	}
	
	int one=0,two=0;
	
	for(int i =0; i< n; i++)
	{
		if(kasane[i]>=3)
			kasane[i] = (bool)(kasane[i] % 2) ? 1 : 2;
		if(kasane[i] == 1)
			one++;
		else if(kasane[i] == 2)
			two++;
	}
	cout << (((two % 2) == 0)? one + two: one + two - 1) << endl;
}


Measured memory_bytes: 1152
import std.algorithm, std.conv, std.range, std.stdio, std.string;

void main()
{
  auto n = readln.chomp.to!size_t;
  auto a = new long[][](n);

  foreach (i; 0..n) a[i] = readln.split.to!(long[]);

  auto t = 0L;
  foreach (i; 0..n)
    foreach (j; 0..n)
      t += a[i][j];

  auto dist = a.map!(i => i.dup).array;

  foreach (k; 0..n)
    foreach (i; 0..n)
      foreach (j; 0..n)
        if (dist[i][j] > dist[i][k] + dist[k][j])
          dist[i][j] = dist[i][k] + dist[k][j];

  foreach (i; 0..n)
    if (dist[i] != a[i]) {
      writeln(-1);
      return;
    }

  auto v = new bool[][](n, n);

  foreach (k; 0..n)
    foreach (i; 0..n)
      foreach (j; 0..n)
        if (i != k && j != k && !v[i][j] && a[i][j] == a[i][k] + a[k][j]) {
          t -= a[i][j];
          v[i][j] = true;
        }

  writeln(t/2);
}


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

typedef long long ll;
string S;
int Q;

vector<vector<int> > cc;
int dp(int l, int a) {
    if(l == S.size()) return 1e9;
    int &ret = cc[l][a];
    if(ret != -1) return ret;

    if(S[l] - 'a' == a) return ret = l + 1;
    if(S[l] - 'a' < a) {
        if(dp(l, a - 1) == 1e9) return ret = 1e9;
        else return ret = dp(dp(l, a - 1), a - 1);
    }
    else {
        if(dp(l, 26) == 1e9) return ret = 1e9;
        else return ret = dp(dp(l, 26), a);
    }
}
vector<vector<int> > db;

int main() {
    std::ios::sync_with_stdio(false);
    cin>>S>>Q;

    cc = vector<vector<int> >(S.size(), vector<int>(27, -1));
    db = vector<vector<int> >(S.size(), vector<int>(20, 1e9));
    for(int i = S.size() - 1; i >= 0; i--) {
        db[i][0] = dp(i, 26);
        for(int j = 1; j < 20; j++) {
            int t = db[i][j - 1];
            if(t == S.size() || t == 1e9) break;
            db[i][j] = db[t][j - 1];
        }
    }
    while(Q--) {
        int l, r; cin>>l>>r;
        l--;

        int p = l;
        for(int i = 20; i--;) {
            if(p != S.size() && db[p][i] <= r) {
                p = db[p][i];
            }
        }
        if(p == r) printf("Yes\n");
        else printf("No\n");
    }
}


Measured memory_bytes: 139804
import java.util.Scanner;
import java.util.Stack;

public class Main {
	Scanner sc = new Scanner(System.in);

	void run() {
		char[] s = sc.next().toCharArray();
		Stack<Character> st = new Stack<>();
		int cnt = 0;
		for (int i = 0; i < s.length; i++) {
			if (s[i] == 'T') {
				if (st.isEmpty()) cnt++;
				else st.pop();
			} else {
				st.push('S');
			}
		}
		cnt += st.size();
		System.out.println(cnt);
	}

	public static void main(String[] args) {
		new Main().run();
	}
}

Measured memory_bytes: 16084
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace _20170409_AOJ
{
    class Program
    {
        static void Main(string[] args)
        {
            string w = Console.ReadLine().ToUpper();
            int count = 0;
            bool eot = false;

            for (; !eot;)
            {
                string line = Console.ReadLine();
                if (line.Contains("END_OF_TEXT"))
                {
                    line = line.Substring(0, line.IndexOf("END_OF_TEXT"));
                    eot = true;
                }

                string[] sArr = line.ToUpper().Split(' ');
                foreach (var v in sArr)
                {
                    if (v == w)
                    {
                        count++;
                    }
                }
            }

            Console.WriteLine(count);

            Console.ReadLine();
        }
    }
}

Measured memory_bytes: 9656
#N,Kの取得
N,K = list(map(int,input().split()))

#[(a_1,b_1),(a_2,b_2),...]の形でリストを作成
numList = []
for a,b in [ map(int,input().split()) for _ in range(N) ]:
	numList.append((a,b))

#作成したリストを、aの大きさで昇順ソート
numList = sorted(numList,key=lambda x:x[0])

#小さい順に要素数bを足していき、Kを超えた段階で出力、終了
count = 0
for a,b in numList:
	count += b
	if count>=K:
		print(a)
		quit()

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

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

int s;

void solve() {
  int rc[9];
  rep(i,9) cin>>rc[i];
  rep(i,9) s-=rc[i];
  cout<<s<<endl;
}

int main (int argc, char const* argv[]) {
  while (cin>>s, s) {
    solve();
  }
  return 0;
}

Measured memory_bytes: 0
#include <stdint.h>

#include <algorithm>
#include <bitset>
#include <functional>
#include <iostream>
#include <string>
#include <vector>

bool IsEqualExceptQuestion(const char *s, const char *t) {
  while (*t && (*s == '?' || *s == *t)) {
    s++;
    t++;
  }
  return *t == 0;
}

bool MatchFromRight(std::string &s, const std::string &t) {
  if (s.size() < t.size()) return false;
  for (int i = s.size() - t.size(); i >= 0; i--) {
    if (!IsEqualExceptQuestion(&s.c_str()[i], t.c_str())) continue;
    for(int k = 0; k < t.size(); k++){
      s[i + k] = t[k]; 
    }
    return true;
  }
  return false;
}

bool Solve(std::string &s, const std::string &t) {
  if (!MatchFromRight(s, t)) return false;
  for(int i = 0; i < s.size(); i++){
    if(s[i] != '?') continue;
    s[i] = 'a';
  }
  return true;
}

int main(int argc, char *argv[]) {
  std::string s, t;
  std::cin >> s >> t;
  if(!Solve(s, t)){
    std::cout << "UNRESTORABLE" << std::endl;
  } else {
    std::cout << s << std::endl;
  }

  return 0;
}


Measured memory_bytes: 256
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7


def gcd(a,b):
    while b:
        a,b = b,a%b
    return a


def gcdlist(l):
    a = l[0]
    for i in range(1,len(l)):
        a = gcd(a,l[i])
    return a

def fctr1(n): 
    f = []
    c = 0
    for i in range(2,int(n**0.5)+2):
        while n%i == 0:
            c += 1
            n = n//i
        if c !=0:
            f.append([i,c])
            c = 0
    if n != 1:
        f.append([n,1])
    return f

n = int(readline())
a = list(map(int,readline().split()))
a.sort()
check = [True]*(10**6+5)
p1 = True
for ai in a:
    if not p1:
        break
    dlist = fctr1(ai)
    for d,c in dlist:
        if check[d]:
            check[d] = False
        else:
            p1 = False
            break

if p1:
    print("pairwise coprime")
else:
    p2 = gcdlist(a)
    if p2 == 1:
        print("setwise coprime")
    else:
        print("not coprime")




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

int main() {
  int N, K;
  string S; cin >> N >> S >> K;
  
  for (int i = 0; i<N;i++) {
    if (S[K-1] != S[i]) S[i] = '*';
  }
  cout << S << endl;
}

Measured memory_bytes: 256
local a, b = io.read("*n", "*n")
local s1, s2 = "", ""
for i = 1, a do
  s1 = s1 .. tostring(b)
end
for i = 1, b do
  s2 = s2 .. tostring(a)
end
print(s1 < s2 and s1 or s2)


Measured memory_bytes: 256
import java.awt.geom.Point2D;
import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class Main {
	Scanner sc = new Scanner(System.in);

	public static void main(String[] args) {
		new Main();
	}

	public Main() {
		new AOJ().doIt();
	}
	class AOJ{
		void doIt(){
			int TEAMS[] = new int[101];
			ArrayList<ArrayList<Integer>> POINTS = new ArrayList<ArrayList<Integer>>();
			for(int i = 0;i < 31;i++)POINTS.add(new ArrayList<Integer>());
			int RANK = 0;
			
			while(true){
				String str[] = sc.next().split(",");
				int team = Integer.parseInt(str[0]);
				int point = Integer.parseInt(str[1]);
				if(team + point == 0)break;
				ArrayList<Integer> array = POINTS.get(point);
				array.add(team);
				POINTS.set(point,array);
			}
			
			for(int i = 30;i >= 0;i--){
				if(POINTS.get(i).size() > 0){
					RANK++;
					ArrayList<Integer> array = POINTS.get(i);
//					System.out.println(RANK+": "+i+" "+array.toString());
					for(int j = 0;j < array.size();j++){
						TEAMS[array.get(j)] = RANK;
					}
				}
			}
			
			while(sc.hasNext()){
				int Q = sc.nextInt();
				System.out.println(TEAMS[Q]);
			}
		}
	}
}

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

int main() {
    string s, t; cin >> s >> t;
    rep(i, s.size()) {
        if (s[i] != t[i]) {
            puts("No");
            return 0;
        }
    }
//    if (t[t.size()-1] == 'z') {
        puts("Yes");
//    }
//    else puts("No");
}

Measured memory_bytes: 3596
n=int(input())
v = [int(i) for i in input().split()] 
c = [int(i) for i in input().split()] 

#print(n,v,c)
ans=0
for i in range(n):
  if v[i]-c[i] > 0:
    ans+=v[i]-c[i]
print(ans)

Measured memory_bytes: 3060
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;

bool check(vector<int> &a,vector<int> &b)
{
	if(a.size()!=b.size())return true;
	for(int i=0;i<a.size();i++)if(a[i]!=b[i])return true;
	return false;
}

int main()
{
	int n;
	while(cin>>n&&n)
	{
		vector<int> a,b;
		for(int i=0;i<n;i++)
		{
			int x;
			cin>>x;
			a.push_back(x);
		}
		int ans;
		for(ans=-1;check(a,b);ans++)
		{
			b.clear();
			for(int i=0;i<a.size();i++)
			{
				b.push_back(count(a.begin(),a.end(),a[i]));
			}
			swap(a,b);
		}
		cout<<ans<<endl;
		for(int i=0;i<a.size();i++)
		{
			cout<<(i==0?"":" ")<<a[i];
		}
		cout<<endl;
	}
}

Measured memory_bytes: 3092
#include<stdio.h>

int main(void){
    int a,b,c;
    scanf("%d%d%d",&a,&b,&c);
    if(a>=b && b>=c){
        printf("%d %d %d\n",c,b,a);
    }
    else if(a>=c && c>=b){
        printf("%d %d %d\n",b,c,a);
    }
    else if(b>=a && a>=c){
        printf("%d %d %d\n",c,a,b);
    }
    else if(b>=c && c>=a){
        printf("%d %d %d\n",a,c,b);
    }
    else if(c>=a && a>=b){
        printf("%d %d %d\n",b,a,c);
    }
    else{
        printf("%d %d %d\n",a,b,c);   
    }
    return 0;
}


Measured memory_bytes: 2104
from sys import stdin
N = stdin.readline().rstrip()
An = [int(x) for x in stdin.readline().rstrip().split()]
W = 1
if any([A == 0 for A in An]):
    print(0)
    exit()
for A in An:
    W = W * A
    if 1000000000000000000 < W:
        print(-1)
        exit()
print(W)

Measured memory_bytes: 21620
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
#include <functional>
#define INF 1<<30
#define MAX_V 16

using namespace std;
typedef pair<int,int> P;
class data{
public:
	int cost,v,bit;
	data(){}
	data(int vv,int bb,int cc){
		cost=cc;
		v=vv;
		bit=bb;
	}
	bool operator<(const data &d)const{
		return cost>d.cost;
	}
};
int n,m;
vector<int> G[MAX_V];
int s[MAX_V];
int dp[MAX_V][1<<MAX_V];
int pv[MAX_V][1<<MAX_V],pbit[MAX_V][1<<MAX_V];
bool flag;
int dijk(int x){
	if(!(x & 1))return -1;
	for(int i=0;i<n;i++){
		for(int j=0;j<(1<<n);j++){
			dp[i][j]=INF;
			pv[i][j]=-1;
			pbit[i][j]=-1;
		}
	}
	priority_queue<data> que;
	que.push(data(0,x,0));
	dp[0][x]=0;
	while(que.size()){
		data q=que.top();
		que.pop();
		if(q.cost>dp[q.v][q.bit])continue;
		if(q.v==n-1 && q.bit==1<<(n-1))return q.cost;
		if(q.v==n-1)flag=true;
		for(int i=0;i<G[q.v].size();i++){
			int t=G[q.v][i];
			if(dp[t][q.bit]>q.cost+1 && (q.bit>>t & 1)){
				dp[t][q.bit]=q.cost+1;
				pv[t][q.bit]=q.v;
				pbit[t][q.bit]=q.bit;
				que.push(data(t,q.bit,q.cost+1));
			}
		}
		for(int i=0;i<n;i++){
			if(i==q.v)continue;
			if(pv[q.v][q.bit]==q.v && abs(q.bit-pbit[q.v][q.bit])>(1<<i))continue;
			if(s[q.v]>>i & 1){
				int nbit=q.bit^(1<<i);
				if(dp[q.v][nbit]>q.cost+1){
					dp[q.v][nbit]=q.cost+1;
					pv[q.v][nbit]=q.v;
					pbit[q.v][nbit]=q.bit;
					que.push(data(q.v,nbit,q.cost+1));
				}
			}
		}
	}
	return -1;
}

int main(void){
	while(1){
		scanf("%d%d",&n,&m);
		if(n+m==0)break;
		for(int i=0;i<m;i++){
			int f,t;
			scanf("%d%d",&f,&t);
			f--;
			t--;
			G[f].push_back(t);
			G[t].push_back(f);
		}
		int st=0;
		for(int i=0;i<n;i++){
			int a;
			scanf("%d",&a);
			st+=a<<i;
		}
		for(int i=0;i<n;i++){
			int a;
			scanf("%d",&a);
			for(int j=0;j<a;j++){
				int b;
				scanf("%d",&b);
				b--;
				s[i]|=1<<b;
			}
		}
		flag=false;
		int res=dijk(st);
		if(res==-1){
			if(!flag)printf("Help me!\n");
			else printf("You can not switch off all lights.\n");
		}else{
			printf("You can go home in %d steps.\n",res);
			vector<P> vec;
			int v=n-1,bit=1<<(n-1);
			while(v!=-1){
				vec.push_back(P(v,bit));
				int nv=pv[v][bit];
				int nbit=pbit[v][bit];
				v=nv;
				bit=nbit;
			}
			reverse(vec.begin(),vec.end());
			for(int i=0;i<(int)vec.size()-1;i++){
				if(vec[i].first!=vec[i+1].first)printf("Move to room %d.\n",vec[i+1].first+1);
				else{
					int a=abs(vec[i].second-vec[i+1].second);
					int cnt=1;
					while(a>1){
						a/=2;
						cnt++;
					}
					printf("Switch %s room %d.\n",vec[i].second>vec[i+1].second?"off":"on",cnt);
				}
			}
		}
		memset(s,0,sizeof(s));
		for(int i=0;i<n;i++){
			G[i].clear();
		}
	}
	return 0;
}

Measured memory_bytes: 12544
n = gets.to_i
A = gets.split.map(&:to_i)
q = gets.to_i
M = gets.split.map(&:to_i)

=begin
# Exhaustive search
test0 = -> (i, m) do
  return true if m == 0
  return false if i == n
  test0.(i+1, m - A[i]) || test0.(i+1, m)
end
M.each do |m|
  puts(test0.(0, m) ? 'yes' : 'no')
end
=end

# DP
dp = Array.new(n+1){Hash.new(nil)}
test = -> (i, m) do
  if dp[i][m].nil?
    dp[i][m] = (if m == 0
      true
    elsif i == n
      false
    else
      test.(i+1, m - A[i]) || test.(i+1, m)
    end)
  else
    dp[i][m]
  end
end
M.each do |m|
  puts(test.(0, m) ? 'yes' : 'no')
end



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

char s1[2000];
char s2[2000];

int LCS(int,int);

int main(){
  int sumstring;
  int i,j,k;
  scanf("%d",&sumstring);

  for(i = 0; i < sumstring; i++){
    scanf("%s",s1);
    scanf("%s",s2);
    printf("%d\n",LCS(strlen(s1),strlen(s2)));
  }

  return 0;
}

int LCS(int length1, int length2){

  int i,j,x;
  int answer[1001][1001];

  x = 0;

  for(i = 0; i < length1; i++){
    answer[i][0] = 0;
  }

  for(i = 0; i < length2; i++){
    answer[0][i] = 0;
  }
  for(i = 0; i < length1; i++){
    for(j = 0; j < length2; j++){
      if(s1[i]==s2[j] && s1[i]!=' ' && s2[i] != ' '){
        if(i == 0 || j == 0){
          answer[i][j] = 1;
        }
        else{
          answer[i][j] = answer[i-1][j-1]+1  ;
        }
      }

      else{
        if(i == 0 && j != 0){
          answer[i][j] = answer[0][j-1];
        }
        else if(i !=0 && j == 0){
          answer[i][j] = answer[i-1][0];
        }
        else if(i == 0 && j == 0){
          answer[0][0] = 0;
        }
        else if(i != 0 && answer[i-1][j] > answer[i][j-1]){
          answer[i][j] = answer[i-1][j];
        }
        else if(answer[i-1][j] <= answer[i][j-1]){
          answer[i][j] = answer[i][j-1];
        }
      }
    }
  }
  return answer[length1-1][length2-1];
}



Measured memory_bytes: 5684
// 1_jsc2019q_a
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>

using namespace std;
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define SZ(x) ((int)(x).size())
#define INF (1e16)
#define MOD (1000000007)
typedef long long ll;

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int m, d;
    cin >> m >> d;

    int cnt = 0;
    for(int i = 1; i <= m; i++){
        for(int j = 1; j <= d; j++){
            int a = j / 10;
            int b = j % 10;

            if(a >= 2 && b >= 2 && a * b == i) cnt++;
        }
    }
    cout << cnt << endl;
    return 0;
}


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

//ライブラリ始まり

//定数

//円周率
const double PI = 3.1415926535897932384;

//天井
const int INF = 1000000000; // = 10^9
const ll LINF = 1000000000000000; // = 10^15

//ABC文字列
const string ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZABC";
const string abc = "abcdefghijklmnopqrstuvwxyzabc";

//よくあるmodくん
const ll MOD = 1000000007; // = 10^9 + 7

//データ構造

//Union_Find木
struct UnionFind {
  vector<int> UF; // UF.at(i) : iの親の番号
  UnionFind(int N) : UF(N) { // 最初は全てが根であるとして初期化
    for(int i = 0; i < N; i++) {
      UF.at(i) = i;
    }
  }
  int root(int x) { // データxが属する木の根を再帰で得る：root(x) = {xの木の根}
    if (UF.at(x) == x) {
      return x;
    }
    return UF.at(x) = root(UF.at(x));
  }
  void unite(int x, int y) { // xとyの木を併合
    int rx = root(x); // xの根をrx
    int ry = root(y); // yの根をry
    if (rx == ry) {
      return; // xとyの根が同じ(=同じ木にある)時はそのまま
    }
    UF.at(rx) = ry; // xとyの根が同じでない(=同じ木にない)時：xの根rxをyの根ryにつける
  }
  bool same(int x, int y) { // 2つのデータx, yが属する木が同じならtrueを返す
    int rx = root(x);
    int ry = root(y);
    return rx == ry;
  }
};

//関数

//ctoi
int ctoi(char c){
  if (c == '0') {
    return 0;
  }
  if (c == '1') {
    return 1;
  } 
  if (c == '2') {
    return 2;
  } 
  if (c == '3') {
    return 3;
  }
  if (c == '4') {
    return 4;
  } 
  if (c == '5') {
    return 5;
  } 
  if (c == '6') {
    return 6;
  }
  if (c == '7') {
    return 7;
  } 
  if (c == '8') {
    return 8;
  } 
  if (c == '9') {
    return 9;
  }
  return -1;  
}

//素数判定
bool PN(int x) {
  if (x <= 1) {
    return false; // 1や0,-1は素数ではない
  }
  if (x == 2) {
    return true; // √2 + 1 > 2 なので下でやると 2 ％ 2 = 0 となり判定できない
  }
  for (int i = 2; i < sqrt(x) + 1; i++) {
    if (x % i == 0) {
      return false; // 割れたら素数じゃない
    }
  }
  return true;
}

//ライブラリ終わり

int main() {
  int N;
  cin >> N;
  vector<int> A(N);
  for (int i = 0; i < N; i++) {
    cin >> A.at(i);
  }
  ll ans = LINF;
  for (int i = -100; i <= 100; i++) {
    ll M = 0;
    for (int j = 0; j < N; j++) {
      M += (i - A.at(j)) * (i - A.at(j));
    }
    ans = min(ans, M);
  }
  cout << ans << endl;
}

Measured memory_bytes: 3708
#!python3

import sys
sys.setrecursionlimit(10 ** 6)


class Node:

    def __init__(self, num):
        self.num = num
        self.v = 1
        self.parent = 0
        self.deep = None


def LI():
    return list(map(int, input().split()))

# input
N = int(input())
AB = [LI() for _ in range(N - 1)]

# link
link = [[] for _ in range(N + 1)]
for a, b in AB:
    link[a].append(b)
    link[b].append(a)

# nodes
nodes = [Node(i) for i in range(N + 1)]


def create_tree(parent):
    for child in link[parent.num]:
        if child == parent.parent:
            continue
        node = nodes[child]
        node.parent = parent.num
        node.deep = parent.deep + 1
        create_tree(node)
        parent.v += node.v


def main():
    nodes[1].deep = 1
    create_tree(nodes[1])

    x = (nodes[N].deep - nodes[1].deep - 1) // 2
    v = nodes[N]
    for _ in range(x):
        v = nodes[v.parent]
    
    snuke = v.v
    fennec = N - snuke
    ans = "Fennec" if fennec > snuke else "Snuke"
    print(ans)


if __name__ == "__main__":
    main()


Measured memory_bytes: 155972
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.NoSuchElementException;

public class Main {

	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int N = sc.nextInt();
		double[] A = new double[N];
		for (int i = 0; i < N; i++)
			A[i] = sc.nextInt();
		int[] B = new int[N];
		for (int i = 0; i < N; i++)
			B[i] = sc.nextInt();
		double[] C = new double[N];
		for (int i = 0; i < N; i++)
			C[i] = sc.nextInt();
		Arrays.sort(A);
		Arrays.sort(C);

		long ans = 0;
		for (int i = 0; i < N; i++) {
			long AB = 0;
			long BC = 0;
			AB = -Arrays.binarySearch(A, B[i] - 0.1) - 1;
			BC = N - (-Arrays.binarySearch(C, B[i] + 0.1) - 1);
			ans += AB * BC;
		}
		System.out.println(ans);

	}

	//以下、自作ライブラリ

	//最大公約数
	public static long gcd(long a, long b) {
		if (a < b)
			return gcd(b, a);
		long c = 0;
		c = a % b;
		if (c == 0)
			return b;
		return gcd(b, c);
	}

	//最小公倍数
	public static long lcm(long m, long n) {
		return m * n / gcd(m, n);
	}

	//素数判定
	public static boolean isPrime(int n) {
		if (n < 2)
			return false;
		if (n == 2)
			return true;
		if (n % 2 == 0)
			return false;

		for (int i = 3; i * i <= n; i += 2) {
			if (n % i == 0)
				return false;
		}
		return true;
	}
}

//以下、高速スキャナークラス
class FastScanner {
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;

	private boolean hasNextByte() {
		if (ptr < buflen) {
			return true;
		} else {
			ptr = 0;
			try {
				buflen = in.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (buflen <= 0) {
				return false;
			}
		}
		return true;
	}

	private int readByte() {
		if (hasNextByte())
			return buffer[ptr++];
		else
			return -1;
	}

	private static boolean isPrintableChar(int c) {
		return 33 <= c && c <= 126;
	}

	public boolean hasNext() {
		while (hasNextByte() && !isPrintableChar(buffer[ptr]))
			ptr++;
		return hasNextByte();
	}

	public String next() {
		if (!hasNext())
			throw new NoSuchElementException();
		StringBuilder sb = new StringBuilder();
		int b = readByte();
		while (isPrintableChar(b)) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	public long nextLong() {
		if (!hasNext())
			throw new NoSuchElementException();
		long n = 0;
		boolean minus = false;
		int b = readByte();
		if (b == '-') {
			minus = true;
			b = readByte();
		}
		if (b < '0' || '9' < b) {
			throw new NumberFormatException();
		}
		while (true) {
			if ('0' <= b && b <= '9') {
				n *= 10;
				n += b - '0';
			} else if (b == -1 || !isPrintableChar(b)) {
				return minus ? -n : n;
			} else {
				throw new NumberFormatException();
			}
			b = readByte();
		}
	}

	public int nextInt() {
		long nl = nextLong();
		if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
			throw new NumberFormatException();
		return (int) nl;
	}

	public double nextDouble() {
		return Double.parseDouble(next());
	}
}


Measured memory_bytes: 37688
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
	int n;
	cin>>n;
	for(int l=0;l<n;l++){
		int num[2][9],a[2][9],geitu,jacky;
		double winrate1=0,winrate2=0;
		for(int j=0;j<2;j++){
			for(int k=0;k<9;k++)cin>>a[j][k];
		}
		for(int z=0;z<9;z++){
			num[0][0]=0;
			num[1][0]=0;
			if(a[0][0]>a[1][z])num[0][0]=(a[0][0]+a[1][z]);
			else num[1][0]=(a[0][0]+a[1][z]);
			for(int b=0;b<9;b++){
				if(b==z)continue;
				num[0][1]=0;
				num[1][1]=0;
				if(a[0][1]>a[1][b])num[0][1]=(a[0][1]+a[1][b]);
				else num[1][1]=(a[0][1]+a[1][b]);
				for(int c=0;c<9;c++){
					if(c==z||c==b)continue;
					num[0][2]=0;
					num[1][2]=0;
					if(a[0][2]>a[1][c])num[0][2]=(a[0][2]+a[1][c]);
					else num[1][2]=(a[0][2]+a[1][c]);
					for(int d=0;d<9;d++){
						if(d==z||d==b||d==c)continue;
						num[0][3]=0;
						num[1][3]=0;
						if(a[0][3]>a[1][d])num[0][3]=(a[0][3]+a[1][d]);
						else num[1][3]=(a[0][3]+a[1][d]);
						for(int e=0;e<9;e++){
							if(e==z||e==b||e==c||e==d)continue;
							num[0][4]=0;
							num[1][4]=0;
							if(a[0][4]>a[1][e])num[0][4]=(a[0][4]+a[1][e]);
							else num[1][4]=(a[0][4]+a[1][e]);
							for(int f=0;f<9;f++){
								if(f==z||f==b||f==c||f==d||f==e)continue;
								num[0][5]=0;
								num[1][5]=0;
								if(a[0][5]>a[1][f])num[0][5]=(a[0][5]+a[1][f]);
								else num[1][5]=(a[0][5]+a[1][f]);
								for(int g=0;g<9;g++){
									if(g==z||g==b||g==c||g==d||g==e||g==f)continue;
									num[0][6]=0;
									num[1][6]=0;
									if(a[0][6]>a[1][g])num[0][6]=(a[0][6]+a[1][g]);
									else num[1][6]=(a[0][6]+a[1][g]);
									for(int h=0;h<9;h++){
										if(h==z||h==b||h==c||h==d||h==e||h==f||h==g)continue;
										num[0][7]=0;
										num[1][7]=0;
										if(a[0][7]>a[1][h])num[0][7]=(a[0][7]+a[1][h]);
										else num[1][7]=(a[0][7]+a[1][h]);
										for(int i=0;i<9;i++){
											if(i==z||i==b||i==c||i==d||i==e||i==f||i==g||i==h)continue;
											num[0][8]=0;
											num[1][8]=0;
											if(a[0][8]>a[1][i])num[0][8]=(a[0][8]+a[1][i]);
											else num[1][8]=(a[0][8]+a[1][i]);
											geitu=0;
											jacky=0;
											for(int m=0;m<9;m++){
												geitu+=num[0][m];
												jacky+=num[1][m];
											}
											if(geitu>jacky)winrate1++;
											else if(geitu<jacky)winrate2++;
										}
									}
								}
							}
						}
					}
				}
			}
		}
		double ans,ans2;
		ans=winrate1/362880;
		ans*=100000;
		ans+=0.5;
		ans=int(ans);
		ans/=100000;
		ans2=winrate2/362880;
		ans2*=100000;
		ans2+=0.5;
		ans2=int(ans2);
		ans2/=100000;
		cout<<ans<<" "<<ans2<<"\n";
	}
	return 0;
}

Measured memory_bytes: 3212
moji=input()
times=int(input())

sento=[]
sippo=[]
plus=[sento,sippo]
dictionary={"sento":0,"sippo":1}

hantenkaisuu=0

for i in range(times):
    command=input().split()
    
    #反転の命令
    if command[0]=="1":
        hantenkaisuu+=1
        dictionary["sento"]=(dictionary["sento"]+1)%2
        dictionary["sippo"]=(dictionary["sippo"]+1)%2
        
    #追加の命令
    else:
        if command[1]=="1":
            plus[dictionary["sento"]].append(command[2])
        else:
            plus[dictionary["sippo"]].append(command[2])
           
    
            
    
    
if hantenkaisuu%2==0:
    sento=sento[::-1]
    sento="".join(sento)
    sippo="".join(sippo)
    print(sento+moji+sippo)
else:
    sippo=sippo[::-1]
    sento="".join(sento)
    sippo="".join(sippo)
    moji=moji[::-1]
    print(sippo+moji+sento)

        
        

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

string A,B,C;


int start(const string &A,int p){
	if( A.size() <= p ) return 0;
	if( A[p] != '?' ) return A[p] - '0';
	if( A.size() == p+1 ) return 1;
	return 0;
}
int end(const string &A,int p){
	if( A.size() <= p ) return 0;
	if( A[p] != '?' ) return A[p] - '0';
	return 9;
}

int dp[52][2];
int dfs(int p,int carry){
	if( dp[p][carry] != -1 ) return dp[p][carry];
	if( p == max({A.size(),B.size(),C.size()}) ){
		return carry == 0;
	}
	int ans = 0;
	for(int i = start(A,p) ; i <= end(A,p) ; i++){
		for(int j = start(B,p) ; j <= end(B,p) ; j++){
			for(int k = start(C,p) ; k <= end(C,p) ; k++){
				if( (i + j + carry) % 10 == k ){
					ans += dfs(p+1,(i + j + carry) >= 10);
					if( ans >= 1000000007 )
						ans -= 1000000007;
				}
			}
		}
	}
	return dp[p][carry] = ans;
}
int main(){
	while(cin >> A >> B >> C){
		memset(dp,-1,sizeof(dp));
		reverse(A.begin(),A.end());
		reverse(B.begin(),B.end());
		reverse(C.begin(),C.end());
		cout << dfs(0,0) << endl;
	}
	
	
}

Measured memory_bytes: 3160
N = int(input())
S = input()
num = [0 for _ in range(N)]

for i in range(1, N):
  if S[i] == 'E':
    num[0] += 1

for i in range(1, N):
  diff = 0
  if S[i-1] == 'W':
    diff += 1
  if S[i] == 'E':
    diff -= 1
  num[i] = num[i-1] + diff
  
print(min(num))

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

int main(){
  string s;
  cin >> s;
  int cnt = 0;
  rep(i, s.size()) {
    if(s[i] == 'S')
    {
      cnt++;
    }
  }

  if(cnt==0)
  {
    cout << 3 << endl;
    return 0;
  }
  else if (cnt == 1)
  {
    if(s[1]=='S')
    {
      cout << 1 << endl;
    }else
    {
      cout << 2 << endl;
    }
    return 0;
  }else if(cnt == 2)
  {
    cout << 1 << endl;
    return 0;
  }else
  {
    cout << 0 << endl;
  }

    return 0;
}

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

using VI = vector<int>;
using VVI = vector<VI>;
using PII = pair<int, int>;
using LL = long long;
using VL = vector<LL>;
using VVL = vector<VL>;
using PLL = pair<LL, LL>;
using VS = vector<string>;

#define ALL(a)  begin((a)),end((a))
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define EB emplace_back
#define MP make_pair
#define SZ(a) int((a).size())
#define SORT(c) sort(ALL((c)))
#define RSORT(c) sort(RALL((c)))
#define UNIQ(c) (c).erase(unique(ALL((c))), end((c)))

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

#define FF first
#define SS second

#define DUMP(x) cout<<#x<<":"<<(x)<<endl
template<class S, class T>
istream& operator>>(istream& is, pair<S,T>& p){
  return is >> p.FF >> p.SS;
}
template<class T>
istream& operator>>(istream& is, vector<T>& xs){
  for(auto& x: xs)
	is >> x;
  return is;
}
template<class S, class T>
ostream& operator<<(ostream& os, const pair<S,T>& p){
  return os << p.FF << " " << p.SS;
}
template<class T>
ostream& operator<<(ostream& os, const vector<T>& xs){
  for(unsigned int i=0;i<xs.size();++i)
	os << (i?" ":"") << xs[i];
  return os;
}
template<class T>
void maxi(T& x, T y){
  if(x < y) x = y;
}
template<class T>
void mini(T& x, T y){
  if(x > y) x = y;
}


const double EPS = 1e-10;
const double PI  = acos(-1.0);
const LL MOD = 1e9+7;

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

  int N;
  cin >> N;
  VVI xs(2, VI(N));
  cin >> xs;

  int y0 = 0, y1 = 0;
  for(int x=0;x<N;++x){
	y0 += xs[0][x];
	y1 = max(y1, y0) + xs[1][x];
  }

  cout << max(y0, y1) << endl;
  
  return 0;
}


Measured memory_bytes: 256
#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#pragma warning(disable:4996)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <functional>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <list>
#include <set>
#include <iomanip> 
#include <ctime>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;

const int INF = 1001001001;
const int MAX_M = 100000;
const double PI = 3.14159265358979323846;
int dp[5005][5005];



int main(int argc, char *args[]) {
	double a, b, x;
	cin >> a >> b >> x;
	double h = 2.0 * x / a / b;
	double V = a * a * b;
	if (h > a) {
		x = V - x;
		h = 2.0 * x / a / a;
		double ans = atan2(h, a) * 180.0000 / PI;
		cout << setprecision(10) << ans << endl;
	}
	else {
		double theta = atan2(h, b) * 180.0000 / PI;
		double ans = 90.000000 - theta;
		cout << setprecision(10) << ans << endl;

	}
	
}

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

using namespace std;

using ll = long long;
using ld = long double;

const double PI = 3.1415926535897932384626433832795;
const ll MOD = 1000000007;

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

int gcd(int x, int y) { return y ? gcd(y, x % y) : x; }
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
int lcm(int x, int y) { return x / gcd(x, y) * y; }
ll lcm(ll x, ll y) { return x / gcd(x, y) * y; }

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

	string s;
	cin >> s;

	if (s == "Sunny") {
		cout << "Cloudy" << endl;
	} else if (s == "Cloudy") {
		cout << "Rainy" << endl;
	} else if (s == "Rainy") {
		cout << "Sunny" << endl;
	}
	return 0;
}


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


using namespace std;
typedef long long ll;
#define REP(i,n) for(int i=0; i<int(n); i++)
#define FOR(i,m,n) for(int i=int(m); i<int(n); i++)
#define ALL(obj) (obj).begin(),(obj).end()
#define VI vector<int>
#define VLL vector<long long>
#define VVI vector<vector<int>>
#define VVLL vector<vector<long long>>
#define VC vector<char>
#define VS vector<string>
#define VVC vector<vector<char>>
#define VB vector<bool>
#define VVB vector<vector<bool>>
#define fore(i,a) for(auto &i:a)

typedef pair <int, int> P;
template<class T> bool chmax(T &a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> bool chmin(T &a, T b) { if (a > b) { a = b; return true; } return false; }
const int  INF = 1 << 29;
const ll INFL = 1LL << 60;
const ll mod = 1000000007;



ll n, m, l;

vector<pair<int, int>> v[305];

int ans[305][305];

template<typename T> using min_priority_queue = priority_queue<T, vector<T>, greater<T>>;


int vis[305];
void dijkstra(int s, vector<vector<pair<int, int>>> &E, vector<vector<ll>> &D) {
	REP(i, n) D[s][i] = INFL;
	REP(i, n) vis[i] = 0;

	min_priority_queue<pair<ll, pair<ll, int>>> que;

	D[s][s] = 0;
	que.push({ 0, {0,s } });

	while (!que.empty()) {
		auto q = que.top();
		que.pop();

		ll cst = q.second.first;
		int cu = q.second.second;

		if (vis[cu]) continue;
		vis[cu] = 1;

		fore(p, E[cu]) {
			ll cst2 = cst + p.second;
			int cnt = q.first;
			if (cst2 > l) {
				cst2 = p.second;
				cnt++;
			}
			int to = p.first;
			if (D[s][to] > cnt||(D[s][to]==cnt&&cst2<ans[s][to])) {
				D[s][to] = cnt;
				D[to][s] = cnt;
				ans[s][to] = cst2;
				ans[to][s] = cst2;
				que.push({ cnt,{cst2,to} });
			}
			//if (chmin(D[s][to], cst2)) que.push({ D[s][to], to });
		}
	}
}


int main() {

	cin >> n >> m >> l;

	vector<vector<pair<int, int>>> c(n);

	VVLL da(305, VLL(305));

	REP(i, m) {
		int a, b, cc;
		cin >> a >> b >> cc;
		a--;
		b--;
		if (cc > l)continue;
		c[a].push_back({ b,cc });
		c[b].push_back({ a,cc });
	}


	REP(i, n) {
		dijkstra(i, c, da);
	}

	REP(i, 305)REP(j, 305) {
		ans[i][j] = INF;
	}

	/*
	cout << "=================" << endl;

	REP(i, n) {
		REP(j, n) {
			cout << da[i][j] << ' ';
		}
		cout << endl;
	}


	cout << "=================" << endl;
	*/

	int q;
	cin >> q;
	REP(i, q) {
		int a, b;
		cin >> a >> b;
		a--; b--;
		//cout << "=============";
		if (da[a][b] == INFL)cout << -1 << endl;
		else cout << da[a][b] << endl;
	}

	
}



Measured memory_bytes: 2816
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
	ll n;
	cin>>n;
	ll ans=1e18;
	for(ll i=1;i*i<=n;i++){
		if(n%i!=0)continue;
		ll j=n/i;
		 ans=min(ans,i+j-2);
	}
	cout<<ans<<endl;
}

Measured memory_bytes: 256
#include <stdio.h>
#include <stdlib.h>
#define ll long long
#define rep(i,l,r)for(ll i=(l);i<(r);i++)
#define max(p,q)((p)>(q)?(p):(q))

//遅延セグ木ここから

//↓ここを変える
typedef struct sayouso{ll p,q;}sayouso;
typedef struct atai{ll a,index;}atai;
//↑ここを変える
typedef struct node{sayouso T;atai x;}node;

node lsegN[1<<18],*lseg;
ll lsegNUM,lsegk;

//↓ここから変える
sayouso id={0,0};
atai xx(atai x,atai y){// <--計算不要
	atai ret={0,0};
	return ret;
}
atai Tx(sayouso T,atai x){
	atai ret;
	ret.a=T.p*x.index+x.a+T.q;
	ret.index=x.index;
	return ret;
}
sayouso TT(sayouso S,sayouso T){
	sayouso ret;
	ret.p=S.p+T.p;
	ret.q=S.q+T.q;
	return ret;
}
sayouso fT(sayouso T,ll k){
	sayouso ret;
	ret.p=T.p;
	ret.q=T.q<<k;
	return ret;
}
//↑ここまで変える

void lseguse(ll n){
	lsegNUM=n;
	lseg=lsegN+lsegNUM;
	lsegk=0;while(n/=2)lsegk++;
}
void lseginit(){
	for(ll i=lsegNUM-1;i>0;i--)lsegN[i].x=xx(lsegN[2*i].x,lsegN[2*i+1].x);
	rep(i,1,2*lsegNUM)lsegN[i].T=id;
}
void lsegupdatesub(ll l,ll r,sayouso T,ll i,ll cl,ll cr,ll ck){
	//disjointなとき
	if(cr<=l||r<=cl)return;
	//完全に含むとき
	if(l<=cl&&cr<=r){
		lsegN[i].T=TT(T,lsegN[i].T);
		return;
	}
	//どちらでもないとき
	//遅延伝播
	lsegN[2*i  ].T=TT(lsegN[i].T,lsegN[2*i  ].T);
	lsegN[2*i+1].T=TT(lsegN[i].T,lsegN[2*i+1].T);
	//再帰的に更新
	ll cm=(cl+cr)/2;
	lsegupdatesub(l,r,T,2*i  ,cl,cm,ck-1);
	lsegupdatesub(l,r,T,2*i+1,cm,cr,ck-1);
	//自身のnodeを更新
	lsegN[i].x=xx(Tx(fT(lsegN[2*i].T,ck-1),lsegN[2*i].x),Tx(fT(lsegN[2*i+1].T,ck-1),lsegN[2*i+1].x));
	lsegN[i].T=id;
}
void lsegupdate(ll l,ll r,sayouso T){lsegupdatesub(l,r,T,1,0,lsegNUM,lsegk);}
atai lsegcalcsub(ll l,ll r,ll i,ll cl,ll cr,ll ck){
	//完全に含むとき
	if(l<=cl&&cr<=r)return Tx(fT(lsegN[i].T,ck),lsegN[i].x);

	ll cm=(cl+cr)/2;
	//遅延伝播(変更はないので配るだけで良い)
	lsegN[2*i  ].T=TT(lsegN[i].T,lsegN[2*i  ].T);
	lsegN[2*i+1].T=TT(lsegN[i].T,lsegN[2*i+1].T);
	lsegN[i].x=Tx(fT(lsegN[i].T,ck),lsegN[i].x);
	lsegN[i].T=id;

	//左側だけ
	if(r<=cm)return lsegcalcsub(l,r,2*i  ,cl,cm,ck-1);
	//右側だけ
	if(cm<=l)return lsegcalcsub(l,r,2*i+1,cm,cr,ck-1);
	//両方
	return xx(lsegcalcsub(l,r,2*i,cl,cm,ck-1),lsegcalcsub(l,r,2*i+1,cm,cr,ck-1));
}
atai lsegcalc(ll l,ll r){return lsegcalcsub(l,r,1,0,lsegNUM,lsegk);}

//遅延セグ木ここまで

int a[100010];
int main(){
	int n,m;
	scanf("%d%d",&n,&m);
 
	rep(i,1,n+1)scanf("%d",a+i);
	
 	lseguse(1<<17);
	rep(i,1,m+1)lseg[i].x.index=i;
	
	rep(i,1,n){
		//a[i],a[i+1]に操作
		int l=a[i],r=a[i+1];
		if(r<l)r+=m;
		if(r-l<=1)continue;
		if(r>m){
			sayouso T;
			T.p=1;
			T.q=-a[i]-1;
			lsegupdate(l+2,m+1,T);
			T.q+=m;
			lsegupdate(1,r-m+1,T);
		}else{
			sayouso T;
			T.p=1;
			T.q=-a[i]-1;
			lsegupdate(l+2,r+1,T);
		}
//	rep(i,1,m+1)printf("%d ",lsegcalc(i,i+1).a);puts("");
	}
	
	ll otoku=0;
	rep(i,1,m+1){
		ll t=lsegcalc(i,i+1).a;
		otoku=max(otoku,t);
	}
	
	ll sum=0;
	rep(i,1,n)sum+=(a[i+1]-a[i]+m)%m;
	
	printf("%lld\n",sum-otoku);
	return 0;
}

Measured memory_bytes: 8320
// CODE by Kazhybay Askar

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <bits/stdc++.h>

using namespace std;
using namespace __gnu_pbds;

/*
find_by_order(k);
order_of_key(k);
ordered_set(int) s;
*/

/*
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
rng();
shuffle(permutation.begin(), permutation.end(), rng);
*/

/*
#pragma comment(linker, "/stack:200000000")
#pragma GCC    optimize("Ofast")
#pragma GCC    target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
*/

#define F      first
#define S      second
#define pb     push_back
#define pf     push_front
#define ppb    pop_back
#define ppf    pop_front
#define Speed  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
#define sz     size()
#define all(x) x.begin(),x.end()
#define cont   continue
#define r0     return 0
#define nl     '\n'
#define ordered_set(T) tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>

typedef unsigned long long ull;
typedef long long ll;
typedef long double   ld;
typedef pair<ll,ll>   pll;
typedef pair<int,int> pii;
typedef pair<char,char> pcc;

const int MAXN  = 5e5  + 7;
const int MOD   = 1e9  + 7;
const int INF   = 1e9  + 7;
const ll  MINF  = 1e18 + 7;
const int EPS   = 1e-6;
const int dx[]  = {0, 0, 1, -1, -1, -1, 1, 1};
const int dy[]  = {1, -1, 0, 0, -1, 1, -1, 1};
const double pi = acos(-1.0);

ll n,a[MAXN];

void solve(){
    ll m,ans=0;
    cin>>n>>m;
    for(int i=1;i<=m;i++){
        cin>>a[i];
        ans+=a[i];
    }
    if(n-ans<0)cout<<-1;
    else cout<<n-ans;
}



int main(){
    //freopen("A.in","r",stdin);
    //freopen("A.out","w",stdout);
    Speed;
    ll T=1;
    //cin>>T;
    while(T--){
        solve();
    }
    r0;
}


Measured memory_bytes: 3692
//#include <tourist>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> p;
const int INF = 1e9;
const ll LINF = ll(1e18) + 1;
const int MOD = 1000000007;
const int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0};
const int Dx[8] = {0, 1, 1, 1, 0, -1, -1, -1}, Dy[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
#define yes cout << "Yes" << endl
#define YES cout << "YES" << endl
#define no cout << "No" << endl
#define NO cout << "NO" << endl
#define rep(i, n) for (int i = 0; i < n; i++)
#define ALL(v) v.begin(), v.end()
#define debug(v)          \
    cout << #v << ":";    \
    for (auto x : v)      \
    {                     \
        cout << x << ' '; \
    }                     \
    cout << endl;
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;
}
//cout<<fixed<<setprecision(15);有効数字15桁
//-std=c++14
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
int n, m;
vector<int> a;

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> n>>m;
    int temp=max(0,n*(n-1)/2);
    int temp1=max(0,m*(m-1)/2);
    cout << temp+temp1 << "\n";
}


Measured memory_bytes: 256
#include <iostream>
#include <array>
#include <algorithm>
#include <vector>
#include <bitset>
#include <set>
#include <unordered_set>
#include <cmath>
#include <complex>
#include <deque>
#include <iterator>
#include <numeric>
#include <map>
#include <unordered_map>
#include <queue>
#include <stack>
#include <string>
#include <tuple>
#include <utility>
#include <limits>
#include <iomanip>
#include <functional>
#include <cassert>
using namespace std;

using ll=long long;
template<class T> using V = vector<T>;
template<class T, class U> using P = pair<T, U>;
using vll = V<ll>;
using vvll = V<vll>;
#define rep(i, k, n) for (ll i=k; i<(ll)n; ++i)
#define REP(i, n) rep(i, 0, n)
#define ALL(v) v.begin(),v.end()
template < class T > inline bool chmax(T& a, T b) {if (a < b) { a=b; return true; } return false; }
template < class T > inline bool chmin(T& a, T b) {if (a > b) { a=b; return true; } return false; }
#define DEBUG_VLL(vec) REP(sz, vec.size()) std::cerr<<vec[sz]<<(sz==vec.size()-1?'\n':' ');

const long long MOD = 1000000007;
const long long HIGHINF = (long long)1e18;
const int INF = (int)1e9;

ll powmod(ll m, ll p) {
    if (p == 0) return 1;
    ll tmp = powmod(m, p / 2);
    if (p & 1) return (tmp * tmp % MOD) * m % MOD;
    else return tmp * tmp % MOD;
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n; cin >> n;
    vll c(n);
    for (int i = 0; i < n; i++) cin >> c[i];
    sort(ALL(c));
    reverse(ALL(c));
    ll ans = powmod(2, n - 1) * c[0] % MOD;
    for (int i = 1; i < n; i++) {
        ll right = ((i * powmod(2, i - 1) % MOD) + powmod(2, i)) % MOD;
        ll left = powmod(2, n - i - 1);
        ans += (right * left % MOD) * c[i] % MOD;
        if (ans >= MOD) ans -= MOD;
    }

    cout << ans * powmod(2, n) % MOD << '\n';
    return 0;
}


Measured memory_bytes: 1792
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>

#define rep(inc, bgn, end) for (int inc = bgn; inc < end; ++inc)
#define repe(inc, bgn, end) for (int inc = bgn; inc <= end; ++inc)

using ll = long long;
using namespace std;

int main() {
    int n;
    cin >> n;
    cout << n / 2 + n % 2 << endl;
    return 0;
}


Measured memory_bytes: 256
#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 allR(x) (x).rbegin(), (x).rend()
using ll = long long;
using P = pair<int, int>;
const int INF (1<<30);
//素因数分解　secondには指数を記録
//素因数分解　secondには指数を記録
//push_back だとres.push_back(pair<ll, int>(i, 0)); のように一回pairを作り、
//それをコピーするので少し遅い
vector<pair<ll, int>> factorize(ll n) {
  vector<pair<ll, int>> res;

  for (ll i = 2; i*i <= n; i++) {
    if (n%i != 0) continue;
    res.emplace_back(i, 0);
    while (n%i == 0) {
      n /= i;
      res.back().second++;
    }
  }

  if (n != 1) res.emplace_back(n, 1);

  return res;
}



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

  if (N == 1LL) {
    cout << 0 << endl;
    return 0;
  } 

  auto f = factorize(N);

  ll ans = 0LL;
  for (auto x : f) {
    int now = x.second;
    for (int i = 1; i < 10000; i++) {
      now -= i;
      if (now < 0) break;
      ans++;
    }
  }


  cout << ans << endl;

  return 0;
}


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

#define clr(i, j)     memset(i, j, sizeof(i))
#define pb            push_back
#define m            make_pair
typedef long long     ll;
map<char,int>mp;
int arr[1000+1][1000+1];int arr2[1000+1][1000+1];
int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};
int main()
{
 int arr[3];for(int i=0;i<3;i++){
 cin>>arr[i];
 }int ans=0;
sort(arr,arr+3);
int t=arr[1]-arr[0];

        int l=t/2;
        ans+=l;
       if(t%2){ans+=2;}




int g=0;g+=arr[2]-arr[1];
cout<<ans+g;
    }


Measured memory_bytes: 256