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

int main(void){
    int N; cin >> N;
    vector<int> A(N);
    for(int i=0; i<N; i++){
        int a; cin >> a;
        A[i]=a-(i+1);
    }

    sort(A.begin(), A.end());
    int b=A[(N-1)/2];
    ll ans=0;

    for(int i=0; i<N; i++) ans+=abs(A[i]-b);

    cout << ans << endl;
}


#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
#define ll long long int
#define pb push_back
#define mp make_pair
#define boost ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define forn(i, n) for(int i = 0; i < (int)(n); i++)
#define ford(i, n) for(int i = (int)(n) - 1; i >= 0; i--)
#define F first
#define S second
#define mset(x,v) memset(x, v, sizeof(x))
#define left(x) 2*x
#define right(x) (2*x) + 1
#define ALL(t) (t).begin(),(t).end()
#define ret return 0
#define all(x) x.begin(),x.end()
ll n;
int main()
{
    boost;
           cin>>n;
           ll arr[n+1];
           for(int i=1;i<=n;i++)
           {
                 cin>>arr[i];
                 arr[i]=arr[i]-i-1;
           }
           sort(arr+1,arr+n+1);
           ll med=arr[n/2];
           ll ans=0;
           for(int i=1;i<=n;i++)
           {
                 ans+=abs(med-arr[i]);
           }
           cout<<ans<<endl;
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 300 points

Problem Statement

Snuke has an integer sequence A of length N.

He will freely choose an integer b.
Here, he will get sad if A_i and b+i are far from each other.
More specifically, the sadness of Snuke is calculated as follows:

abs(A_1 - (b+1)) + abs(A_2 - (b+2)) + ... + abs(A_N - (b+N))

Here, abs(x) is a function that returns the absolute value of x.

Find the minimum possible sadness of Snuke.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible sadness of Snuke.

Sample Input 1

5
2 2 3 5 5

Sample Output 1

2

If we choose b=0, the sadness of Snuke would be abs(2-(0+1))+abs(2-(0+2))+abs(3-(0+3))+abs(5-(0+4))+abs(5-(0+5))=2.
Any choice of b does not make the sadness of Snuke less than 2, so the answer is 2.

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

0

Sample Input 3

6
6 5 4 3 2 1

Sample Output 3

18

Sample Input 4

7
1 1 1 1 2 3 4

Sample Output 4

6

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


#include <bits/stdc++.h>

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define CLR(a) memset((a), 0 ,sizeof(a))
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vi> vii;
typedef vector<string> vs;
typedef pair<int, int> pi;
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MKP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())

const int INF = 999999;
const double EPS = 1e-10;
const double PI = acos(-1.0);
const ll MOD = 1000000007;

ll N,sum;
vll A, ans;

int main()
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	cin >> N;
	REP(i, N) {
		ll x;
        cin >> x;
		A.push_back(x);
	}
	REP(i, N) {
		sum = 0;
		REP(j, std::accumulate(A.begin(), A.end(), 0) / A.size()) {
			sum += abs(A[j] - j - 1);
		}
		ans.push_back(sum);
	}

	std::cout << *std::min_element(ans.begin(), ans.end()) << endl;

	return 0;
}


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

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

#define ALL(a)  begin((a)),end((a))
#define RALL(a) (a).rbegin(), (a).rend()
#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, s, e) for (int(i) = (s); (i) < (e); (i)++)
#define FORR(i, s, e) for (int(i) = (s); (i) > (e); (i)--)
//#pragma GCC optimize ("-O3")
#ifdef YANG33
#include "mydebug.hpp"
#else
#define DD(x)
#endif
const int INF = 1e9;                          const LL LINF = 1e16;
const LL MOD = 1000000007;                    const double PI = acos(-1.0);
int DX[8] = { 0, 0, 1, -1, 1, 1, -1, -1 };    int DY[8] = { 1, -1, 0, 0, 1, -1, 1, -1 };

/* -----  __MAKE_TIME__  Problem: __PROBLEM__ / Link: __CONTEST_URL__  ----- */
/* ------問題------

-----問題ここまで----- */
/* -----解説等-----

----解説ここまで---- */
struct Cumusum {
	vector<LL>csum;
	Cumusum(vector<LL>&a) {
		csum.assign((int)a.size(), 0);
		for (int i = 0; i < (int)a.size(); i++) {
			csum[i + 1] = csum[i] + a[i];
		}
	}
	LL query(int l, int r) {
		return csum[r] - csum[l];
	}
};

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

	LL N;
	cin >> N;
	VL a(N);
	FOR(i, 0, N) {
		cin >> a[i];
	}
	Cumusum A(a);
	// [L,R)を絶対値の差が小さくなるように2つに分割する
	auto f = [](Cumusum&A, int Lidx, int Ridx) {
		LL L = Lidx; LL R = Ridx;
		FOR(i, 0, 60) {
			int m1 = (2 * L + R) / 3;
			int m2 = (L + 2 * R) / 3;
			LL dif1 = abs(A.query(Lidx, m1) - A.query(m1, Ridx));
			LL dif2 = abs(A.query(Lidx, m2) - A.query(m2, Ridx));
			if (dif1 < dif2) {
				R = m2;
			}
			else {
				L = m1;
			}
		}
		LL Diff = LINF; int midx = 0;
		FOR(k, 1, R - L) {
			int m = L + k;
			LL diff = abs(A.query(Lidx, m) - A.query(m, Ridx));
			if (Diff > diff) {
				Diff = diff;
				midx = m;
			}
		}
		assert(Lidx < midx&&midx < Ridx);
		return PLL(A.query(Lidx, midx), A.query(midx, Ridx));
	};
	LL ans = LINF;
	FOR(i, 2, N - 1) {
		PLL ab = f(A, 0, i);//[0,i)
		PLL cd = f(A, i, N);
		LL Mx = max({ ab.first,ab.second,cd.first,cd.second });
		LL Mn = min({ ab.first,ab.second,cd.first,cd.second });
		ans = min(ans, Mx - Mn);
	}

	cout << ans << "\n";

	return 0;
}

Score : 600 points

Problem Statement

Snuke has an integer sequence A of length N.

He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E.
The positions of the cuts can be freely chosen.

Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively.
Snuke is happier when the absolute difference of the maximum and the minimum among P,Q,R,S is smaller.
Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.

Constraints

4 \leq N \leq 2 \times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.

Sample Input 1

5
3 2 4 1 2

Sample Output 1

2

If we divide A as B,C,D,E=(3),(2),(4),(1,2), then P=3,Q=2,R=4,S=1+2=3.
Here, the maximum and the minimum among P,Q,R,S are 4 and 2, with the absolute difference of 2.
We cannot make the absolute difference of the maximum and the minimum less than 2, so the answer is 2.

Sample Input 2

10
10 71 84 33 6 47 23 25 52 64

Sample Output 2

36

Sample Input 3

7
1 2 3 1000000000 4 5 6

Sample Output 3

999999994


#include<iostream>
#include<algorithm>
#include<set>
#include<math.h>
#include<vector>
#include<sstream>
#include<queue>
#include<functional>
#include<bitset>
#include<cstdio>
#include<iomanip>
#include<map>
#include<unordered_map>
#include<unordered_set>
#include <string.h>
using ll = long long;

#define rep(i, n) for(ll i = 0; i < (ll)(n); i++)
#define reps(i,x) for(ll i=1;i<=(ll)(x);i++)
#define rrep(i,x) for(ll i=((ll)(x)-1);i>=0;i--)
#define rreps(i,x) for(ll i=(ll)(x);i>0;i--)
#define all(x) (x).begin(),(x).end()
#define m0(x) memset(x,0,sizeof(x))
#define vll vector<ll>
#define vi vector<int>
#define vpll vector<pair<ll,ll>>
#define vpi vector<pair<int,int>>
#define mod 1000000007
using namespace std;
int a[200005];
ll dp[200005];
ll b[4];
int main() {
	int n;
	cin >> n;
	rep(i , n)
		cin >> a[i];
	dp[0] = a[0];
	reps(i, n-1){
		dp[i] = dp[i-1] + a[i];
	}
	ll ans = 1 << 30;
	int lf, rt;
	lf = 0;
	rt = 2;
	for(int i = 2; i < n-1; i++){
		ll lmn = 1 << 30;
		ll rmn = 1 << 30;
		for(int j = lf; j < i - 1; j++){
			if(lmn > abs(dp[j] -abs(dp[i-1] - dp[j]))){
				b[0] = dp[j];
				b[1] = (i-1 == j ? dp[i-1] : dp[i-1] -dp[j]);
				lmn =abs(dp[j] -abs(dp[i-1] - dp[j]));
				lf = j;
			}else{break;}
		}
			if(i == n - 1 && rmn > abs(dp[n-2] - dp[n-3] -( dp[n-1] -dp[n-2]))){
				b[2] = dp[n-2] - dp[n-3];
				b[3] = dp[n-1] - dp[n-2];
			}else{
		for(int j = rt; j < n; j++){
			if(rmn > abs(abs(dp[j] - dp[i-1]) -abs(dp[n-1] - dp[j]))){
				b[2] = dp[j] - dp[i-1];
				b[3] = dp[n-1] - dp[j];
				rmn = abs(abs(dp[j] - dp[i-1]) -abs(dp[n-1] - dp[j]));
				rt  = j;
			}else{break;}
		}
            }
		sort(b, b+4);
		ans = min(ans, b[3] - b[0]);
	}
	cout << ans << endl;
}


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

const double PI = acos(-1);
using ll = long long;
using ull = unsigned long long;
const int inf = 2e9;
const ll INF = 2e18;
const ll MOD = 1e9+7;
typedef pair<int,int> P;

#define REP(i,n) for (int i = 0; i < (n); i++)
#define sz(s) (s).size()
#define pb push_back
#define fi first
#define se second

int n;
ll a[200010];
int pl[200010], pr[200010];

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

  cin >> n;
  REP(i,n) cin >> a[i+1];
  REP(i,n) a[i+1] += a[i];

  int p = 1;
  for (int i = 2; i <= n-2; i++) {
    while (1) {
      if (abs(a[i] - a[p] - a[p]) > abs(a[i] - a[p+1] - a[p+1]) && p+1 < i) {
        p++;
      } else {
        pl[i] = p;
        break;
      }
    }
  }

  p = n;
  for (int i = n-2; i >= 2; i--) {
    while (1) {
      if (abs(a[n] - a[p] - (a[p] - a[i])) > abs(a[n] - a[p-1] - (a[p-1] - a[i])) && p-1 > i) {
        p--;
      } else {
        pr[i] = p;
        break;
      }
    }
  }

  //pl)i)pr)n)
  ll ans = INF;
  for (int i = 2; i <= n-2; i++) {
    ll aa,bb,cc,dd;
    aa = a[pl[i]];
    bb = a[i] - aa;
    cc = a[pr[i]] - a[i];
    dd = a[n] - aa - bb - cc;
    ans = min(ans, max({aa,bb,cc,dd}) - min({aa,bb,cc,dd}));
  }

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


//cwystc <--> 陈威宇是天才  --by cwy
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pi;
const double PI=acos(-1);
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define rep(i,a,b) for (int i=(a);i<=(b);i++)
#define per(i,a,b) for (int i=(a);i>=(b);i--)
#define Rep(i,a,b) for (int i=(a);i<(b);i++)
#define Per(i,a,b) for (int i=(a);i>(b);i--)
#define travel_set(it,a) for (set<int>::iterator (it)=(a).begin();(it)!=(a).end();(it)++)
#define travel_map(it,a) for (map<int>::iterator (it)=(a).begin();(it)!=(a).end();(it)++)
#define travel_vec(it,a) for (vector<int>::iterator (it)=(a).begin();(it)!=(a).end();(it)++)
#define p(x) cout << x << endl;
#define def cout << "find" << endl;
#define what_is(x) cout << #x << " is " << x << endl;
template <class T>T sqr(T x){return x*x;}
template <class T>T alex(T x){return (x>0)?x:-x;}
template <class T>void read(T&x){
	x=0;T f=1;char ch=getchar();
	while ((ch<48||ch>57)&&ch!=45)ch=getchar();
	if (ch==45)f=-1,ch=getchar();
	while (ch>=48&&ch<=57)x=x*10+ch-48,ch=getchar();
	x*=f;
}

//-------------------------------------------------head-------------------------------------------------

#define maxn 1000005
ll a[maxn];int n;
ll min(ll a,ll b,ll c,ll d){
	ll res=a;
	if (b<res)res=b;
	if (c<res)res=c;
	if (d<res)res=d;
	return res;
}
ll max(ll a,ll b,ll c,ll d){
	ll res=a;
	if (b>res)res=b;
	if (c>res)res=c;
	if (d>res)res=d;
	return res;
}
int main(){
	read(n);
	rep(i,1,n)read(a[i]),a[i]+=a[i-1];
	int A,B,C;ll v=a[n]/4;
	rep(i,1,n){
		if (a[i]<=v)A=i;
		if (a[i]<=v*2)B=i;
		if (a[i]<=v*3)C=i;
	}
	ll res=(ll)1e18;
	rep(i,max(1,A-100),min(A+100,n))
	rep(j,max(i+1,B-100),min(B+100,n))
	rep(k,max(j+1,C-100),min(C+100,n-1)){
		ll a1=a[i],a2=a[j]-a[i],a3=a[k]-a[j],a4=a[n]-a[k];
		res=min(res,max(a1,a2,a3,a4)-min(a1,a2,a3,a4));
	}
	printf("%lld\n",res);return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	string s;cin>>s;
  int ret=0;
  for(auto&& u:s)
    if(u=='+')ret++;
  else ret--;
  cout<<ret<<endl;
}

Score : 100 points

Problem Statement

There is always an integer in Takahashi's mind.

Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is + or -. When he eats +, the integer in his mind increases by 1; when he eats -, the integer in his mind decreases by 1.

The symbols Takahashi is going to eat are given to you as a string S. The i-th character in S is the i-th symbol for him to eat.

Find the integer in Takahashi's mind after he eats all the symbols.

Constraints

The length of S is 4.

Each character in S is + or -.

Input

Input is given from Standard Input in the following format:

S

Output

Print the integer in Takahashi's mind after he eats all the symbols.

Sample Input 1

+-++

Sample Output 1

2

Initially, the integer in Takahashi's mind is 0.

The first integer for him to eat is +. After eating it, the integer in his mind becomes 1.

The second integer to eat is -. After eating it, the integer in his mind becomes 0.

The third integer to eat is +. After eating it, the integer in his mind becomes 1.

The fourth integer to eat is +. After eating it, the integer in his mind becomes 2.

Thus, the integer in Takahashi's mind after he eats all the symbols is 2.

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4


#include <cstdio>
#include <cmath>

long long llpow(long long a, long long b){
    long long res = 1;
    for(long long i = 0; i<b; i++){
        res *= 10;
    }

    return res;
}

int main(){
    long long N;
    scanf("%lld", &N);

    long long res = 0;
    long long one = 1;
    long long nine = 9;
    long long ten = 10;
    for(long long i=0; i<nine; i+=one){
        long long hoge = llpow(ten, i);
        if(hoge > N){
            ;
        }else{
            res += (N / hoge) % ten;
        }
    }

    long long zero = 0;
    if(N % res == zero){
        printf("Yes\n");
    }else{
        printf("No\n");
    }

    return 0;
}

Score : 200 points

Problem Statement

Let S(n) denote the sum of the digits in the decimal notation of n.
For example, S(101) = 1 + 0 + 1 = 2.

Given an integer N, determine if S(N) divides N.

Constraints

1 \leq N \leq 10^9

Input

Input is given from Standard Input in the following format:

N

Output

If S(N) divides N, print Yes; if it does not, print No.

Sample Input 1

12

Sample Output 1

Yes

In this input, N=12.
As S(12) = 1 + 2 = 3, S(N) divides N.

Sample Input 2

101

Sample Output 2

No

As S(101) = 1 + 0 + 1 = 2, S(N) does not divide N.

Sample Input 3

999999999

Sample Output 3

Yes


#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<cmath>
using namespace std;
int main()
{
  int N, K;
  cin >> N >> K;
  vector<int> A(N);
  for(int n = 0; n < N; ++n){
    cin >> A[n];
  }

  // K-1ずつ変更する
  cout << (N-1)/(K-1) << endl;
  return 0;

}

Score : 300 points

Problem Statement

There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.

On this sequence, Snuke can perform the following operation:

Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.

Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times.
Find the minimum number of operations required.
It can be proved that, Under the constraints of this problem, this objective is always achievable.

Constraints

2 \leq K \leq N \leq 100000

A_1, A_2, ..., A_N is a permutation of 1, 2, ..., N.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

In the first operation, choose the first, second and third elements. The sequence A becomes 1, 1, 1, 4.

In the second operation, choose the second, third and fourth elements. The sequence A becomes 1, 1, 1, 1.

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4


#include<iostream>
#include<cstdio>
using namespace std;
int n, x, ans;
int main(){
	scanf("%d", &n);
	while(n--){
		scanf("%d", &x);
		while(!(x & 1)){//用位运算节省时间
			ans++;
			x >>= 1;//还是位运算QWQ
		}
	}
	printf("%d\n", ans);//注意 AT 题要换行
	return 0;//完结撒花-v-
}

Score: 300 points

Problem Statement

As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}.

Snuke, an employee, would like to play with this sequence.

Specifically, he would like to repeat the following operation as many times as possible:

For every i satisfying 1 \leq i \leq N, perform one of the following: "divide a_i by 2" and "multiply a_i by 3".
Here, choosing "multiply a_i by 3" for every i is not allowed, and the value of a_i after the operation must be an integer.

At most how many operations can be performed?

Constraints

N is an integer between 1 and 10 \ 000 (inclusive).

a_i is an integer between 1 and 1 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print the maximum number of operations that Snuke can perform.

Sample Input 1

3
5 2 4

Sample Output 1

3

The sequence is initially {5, 2, 4}. Three operations can be performed as follows:

First, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {15, 6, 2}.

Next, multiply a_1 by 3, divide a_2 by 2 and multiply a_3 by 3. The sequence is now {45, 3, 6}.

Finally, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {135, 9, 3}.

Sample Input 2

4
631 577 243 199

Sample Output 2

0

No operation can be performed since all the elements are odd. Thus, the answer is 0.

Sample Input 3

10
2184 2126 1721 1800 1024 2528 3360 1945 1280 1776

Sample Output 3

39


#include<stdio.h>

int main(void){
    int len,an,cnt=0;
   scanf("%d",&len);
   for(int i=0;i<len;i++){
        scanf("%d",&an);
        while(1){
            if(an%2!=0)
                break;
            an/=2;
            cnt++;
        }
    }
    return 0;
}


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

typedef unsigned long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<ll> vll;

#define INF (int)(1e9)

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

#define DEBUG

int main()
{
	int n;
	cin >> n;
	if(n > 1000) cout << "ABD" << endl;
	else cout << "ABC" << endl;
	return 0;
}

Score : 100 points

Problem Statement

Decades have passed since the beginning of AtCoder Beginner Contest.

The contests are labeled as ABC001, ABC002, ... from the first round, but after the 999-th round ABC999, a problem occurred: how the future rounds should be labeled?

In the end, the labels for the rounds from the 1000-th to the 1998-th are decided: ABD001, ABD002, ..., ABD999.

You are given an integer N between 1 and 1998 (inclusive). Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Constraints

1 \leq N \leq 1998

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Sample Input 1

999

Sample Output 1

ABC

The 999-th round of AtCoder Beginner Contest is labeled as ABC999.

Sample Input 2

1000

Sample Output 2

ABD

The 1000-th round of AtCoder Beginner Contest is labeled as ABD001.

Sample Input 3

1481

Sample Output 3

ABD

The 1481-th round of AtCoder Beginner Contest is labeled as ABD482.


#include <iostream>
#include <string>
#include <vector>
#include <numeric>
#include <queue>
#include <unordered_map>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <sstream>
#include <stack>
#include <map>
#include <set>

#define REP(i,a) for(int i = 0;i < (a);++i)
#define FOR(i,a,b) for(int i = (a);i < (b); ++i)
#define ALL(obj) (obj).begin(),(obj).end()
#define SIZE(obj) (int)(obj).size()
#define MAX(list) std::max(list)
#define MIN(list) std::min(list)

template<typename T>
T round_up(const T& a, const T& b) {
    return (a + (b - 1)) / b;
}

using ll = long long;
using namespace std;
ll mod = 1'000'000'007;

const int INF = 1'050'000'000;

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

    vector<int> sums(1000);
    sums[0] = 0;
    REP(i, 999) {
        sums[i + 1] = sums[i] + i + 1;
    }

    REP(i, 1000) {
        if (sums[i] - A == sums[i + 1] - B) {
            cout << sums[i] - A << endl;
            return 0;
        }
    }
    return 0;
}

Score : 200 points

Problem Statement

In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.

It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not covered with snow, and the results are a meters for the west tower, and b meters for the east tower.

Assuming that the depth of snow cover and the altitude are the same everywhere in the village, find the amount of the snow cover.

Assume also that the depth of the snow cover is always at least 1 meter.

Constraints

1 \leq a < b < 499500(=1+2+3+...+999)

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

a b

Output

If the depth of the snow cover is x meters, print x as an integer.

Sample Input 1

8 13

Sample Output 1

2

The heights of the two towers are 10 meters and 15 meters, respectively.
Thus, we can see that the depth of the snow cover is 2 meters.

Sample Input 2

54 65

Sample Output 2

1


#include <iostream>

using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;
    int max = a + b;

    if (a - b > max)
    {
        max = a - b;
    }
    if (a * b > max)
    {
        max = a * b;
    }
    cout << max << endl;
    return 0;
}

Score : 100 points

Problem Statement

You are given two integers A and B.
Find the largest value among A+B, A-B and A \times B.

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest value among A+B, A-B and A \times B.

Sample Input 1

3 1

Sample Output 1

4

3+1=4, 3-1=2 and 3 \times 1=3. The largest among them is 4.

Sample Input 2

4 -2

Sample Output 2

6

The largest is 4 - (-2) = 6.

Sample Input 3

0 0

Sample Output 3

0


#include <cstdio>
#include <algorithm>
#define maxn 300005
using namespace std;

int n, ans = 999999999;
int sum[maxn];
char s[maxn];

int main()
{
	scanf("%d", &n);
	scanf("%s", s);
	for (int i = 1; i <= n; i++)
	{
		if (s[i - 1] == 'E') sum[i] = sum[i - 1] + 1;
		else sum[i] = sum[i - 1];
	}
	for (int i = 1; i <= n; i++)
		ans = min(ans, (i - 1 - sum[i - 1]) + (sum[n] - sum[i]));
	printf("%d", ans);
	return 0;
}

Score : 300 points

Problem Statement

There are N people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string S of length N.
The i-th person from the west is facing east if S_i = E, and west if S_i = W.

You will appoint one of the N people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

2 \leq N \leq 3 \times 10^5

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is 1 in this case.
It is not possible to have 0 people who have to change their directions, so the answer is 1.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3


#include <bits/stdc++.h>

using namespace std;

#define REP(i,m) for(int i=0; i<m; i++)
#define FOR(i,n,m) for(long long i=n; i<m; i++)
#define INF 1000000001
#define INFL (1LL << 60)
#define MOD 1000000007
#define ALL(v) v.begin(),v.end()
#define pb push_back
#define ll long long int
#define P pair<ll, ll>

int main() {
  int n, k, q;
  cin >> n >> k >> q;
  P a[n];
  REP(i, n){
    int x;
    cin >> x;
    a[i] = {x, i};
  }
  sort(a, a+n);
  bool check[n];
  REP(i, n){
    check[i] = ((n-k-q+i+1 <= a[i].second) && (a[i].second <= k+q-i-2));
  }
  bool isok[n-q+1] = { };
  REP(i, n-q+1){
    REP(j, n){
      if(check[j] && !(i <= j && j < i+q)) isok[i] = true;
    }
  }
  int mm[n-q+1];
  REP(i, n-q+1) mm[i] = a[i+q-1].first - a[i].first;
  int ans = INF;
  REP(i, n-q+1){
    if(!isok[i]) ans = min(ans, mm[i]);
  }
  cout << ans << endl;
  return 0;
}

Score : 600 points

Problem Statement

You are given an integer sequence A of length N and an integer K.
You will perform the following operation on this sequence Q times:

Choose a contiguous subsequence of length K, then remove the smallest element among the K elements contained in the chosen subsequence (if there are multiple such elements, choose one of them as you like).

Let X and Y be the values of the largest and smallest element removed in the Q operations. You would like X-Y to be as small as possible.
Find the smallest possible value of X-Y when the Q operations are performed optimally.

Constraints

1 \leq N \leq 2000

1 \leq K \leq N

1 \leq Q \leq N-K+1

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K Q
A_1 A_2 ... A_N

Output

Print the smallest possible value of X-Y.

Sample Input 1

5 3 2
4 3 1 5 2

Sample Output 1

1

In the first operation, whichever contiguous subsequence of length 3 we choose, the minimum element in it is 1.
Thus, the first operation removes A_3=1 and now we have A=(4,3,5,2).
In the second operation, it is optimal to choose (A_2,A_3,A_4)=(3,5,2) as the contiguous subsequence of length 3 and remove A_4=2.
In this case, the largest element removed is 2, and the smallest is 1, so their difference is 2-1=1.

Sample Input 2

10 1 6
1 1 2 3 5 8 13 21 34 55

Sample Output 2

7

Sample Input 3

11 7 5
24979445 861648772 623690081 433933447 476190629 262703497 211047202 971407775 628894325 731963982 822804784

Sample Output 3

451211184


#include <bits/stdc++.h>
using namespace std;
const __int128 maxn = 1e18;
void scan(__int128 &x)
{
    x = 0;
    int f = 1;
    char ch;
    if((ch = getchar()) == '-') f = -f;
    else x = x*10 + ch-'0';
    while((ch = getchar()) >= '0' && ch <= '9')
        x = x*10 + ch-'0';
    x *= f;
}
void _print(__int128 x)
{
    if(x > 9) _print(x/10);
    putchar(x%10 + '0');
}
void print(__int128 x) {
    if(x < 0)
    {
        x = -x;
        putchar('-');
    }
    _print(x);
}
__int128 Abs(__int128 x) {
    return x > 0 ? x : -x;
}
int main() {
    long long a,b,c,k,ans;
    if (k&1) ans = b-a;
    else ans = a-b;
    if (abs(ans) > maxn) printf("Unfair");
    else printf("%d",ans);
    return 0;
}

Score : 300 points

Problem Statement

Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively.
After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get:

Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own integer with the result.

However, if the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Constraints

1 \leq A,B,C \leq 10^9

0 \leq K \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the integer Takahashi will get minus the integer Nakahashi will get, after repeating the following operation K times.
If the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Sample Input 1

1 2 3 1

Sample Output 1

1

After one operation, Takahashi, Nakahashi and Hikuhashi have 5, 4 and 3, respectively. We should print 5-4=1.

Sample Input 2

2 3 2 0

Sample Output 2

-1

Sample Input 3

1000000000 1000000000 1000000000 1000000000000000000

Sample Output 3

0


#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1001010;
int p[MAXN], a[MAXN], n;
int dp[MAXN];
int main(){
    scanf("%d", &n);
    for(int i = 1; i <= n; i ++){
        scanf("%d", &a[i]);
        dp[i] = 1; p[a[i]] = i;
    }
    for(int i = 2; i <= n; i ++){
        if(p[i] > p[i-1])
            dp[i] = dp[i-1] + 1;
    }

    int ans = MAXN;
    for(int i = 1; i <= n; i ++){
        ans = min(ans, n - dp[i]);
    }
    printf("%d", ans);
}

Score : 500 points

Problem Statement

You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N.
You would like to sort this sequence in ascending order by repeating the following operation:

Choose an element in the sequence and move it to the beginning or the end of the sequence.

Find the minimum number of operations required.
It can be proved that it is actually possible to sort the sequence using this operation.

Constraints

1 \leq N \leq 2\times 10^5

(P_1,P_2,...,P_N) is a permutation of (1,2,...,N).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1
:
P_N

Output

Print the minimum number of operations required.

Sample Input 1

4
1
3
2
4

Sample Output 1

2

For example, the sequence can be sorted in ascending order as follows:

Move 2 to the beginning. The sequence is now (2,1,3,4).

Move 1 to the beginning. The sequence is now (1,2,3,4).

Sample Input 2

6
3
2
5
1
4
6

Sample Output 2

4

Sample Input 3

8
6
3
1
2
7
4
8
5

Sample Output 3

5


#include<iostream>
#include<cmath>
using namespace std;

int main() {
    int N;
    cin>>N;
    long A[N];
    for(int i=0;i<N;++i){
        cin>>A[i];
    }
    bool check = true;
    if(A[0]!=0)check = false;
    for(int i=1;i<N;++i){
        if(abs(A[i]-A[i-1])>1)check = false;
    }
    long ans = A[N-1];
    if(check){
        for(int i=N-1;i>=1;--i){
            if(A[i]-A[i-1]!=1)ans += A[i-1];
        }
    }
    else ans = -1;
    cout<<ans<<endl;
}

Score : 700 points

Problem Statement

There is a sequence X of length N, where every element is initially 0. Let X_i denote the i-th element of X.

You are given a sequence A of length N. The i-th element of A is A_i. Determine if we can make X equal to A by repeating the operation below. If we can, find the minimum number of operations required.

Choose an integer i such that 1\leq i\leq N-1. Replace the value of X_{i+1} with the value of X_i plus 1.

Constraints

1 \leq N \leq 2 \times 10^5

0 \leq A_i \leq 10^9(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

If we can make X equal to A by repeating the operation, print the minimum number of operations required. If we cannot, print -1.

Sample Input 1

4
0
1
1
2

Sample Output 1

3

We can make X equal to A as follows:

Choose i=2. X becomes (0,0,1,0).

Choose i=1. X becomes (0,1,1,0).

Choose i=3. X becomes (0,1,1,2).

Sample Input 2

3
1
2
1

Sample Output 2

-1

Sample Input 3

9
0
1
1
0
1
2
2
1
2

Sample Output 3

8


#include "bits/stdc++.h"
using namespace std;
#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
typedef long long ll;

int main(int argc, char* argv[]){
    int X, ans;
    cin >> X;

    for(int i = 0; i*i <= X; i++){
        ans = i*i;
    }
    cout << ans << endl;
}

Score : 200 points

Problem Statement

You are given a positive integer X.
Find the largest perfect power that is at most X.
Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.

Constraints

1 ≤ X ≤ 1000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the largest perfect power that is at most X.

Sample Input 1

10

Sample Output 1

9

There are four perfect powers that are at most 10: 1, 4, 8 and 9.
We should print the largest among them, 9.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

999

Sample Output 3

961


#include <iostream>
#include <cmath>
#define ll long long int
using namespace std;

int main(int argc, char const* argv[])
{
	int x;
	cin >> x;
	if(x == 1){
			cout << 1 << endl;
			return 0;
	}
  	int max = 1;
	int y = 8;
	while(y < x)y = y * 2;
	if(y / 2 > max && y / 2 <= x)max = y /2;
	for(int i = 3; i < sqrt(x); i+=2){
			int z = i*i*i;
			while(z < x)z = z*i;
      		if(z /i > x)continue;
			if(z/i > max)max = z/i;
	}
	cout << max << endl;
	return 0;
}


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

int main()
{
	string S;
	int K;

	vector < string > vec;

	cin >> S >> K;

	for ( int i = 0; i < S.size(); i++ ) {
		for ( int j = 1; i + j <= S.size() && j <= K; j++ ) {
			vec.push_back(S.substr(i, j));
		}
	}
	sort(begin(vec), end(vec));
	vec.erase(unique(begin(vec), end(vec)), end(vec));

	cout << vec[K - 1] << endl;

	return (0);
}

Score : 300 points

Problem Statement

You are given a string s.
Among the different substrings of s, print the K-th lexicographically smallest one.

A substring of s is a string obtained by taking out a non-empty contiguous part in s.
For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z and an empty string are not.
Also, we say that substrings are different when they are different as strings.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

1 ≤ |s| ≤ 5000

s consists of lowercase English letters.

1 ≤ K ≤ 5

s has at least K different substrings.

Partial Score

200 points will be awarded as a partial score for passing the test set satisfying |s| ≤ 50.

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.

Sample Input 1

aba
4

Sample Output 1

b

s has five substrings: a, b, ab, ba and aba.
Among them, we should print the fourth smallest one, b.
Note that we do not count a twice.

Sample Input 2

atcoderandatcodeer
5

Sample Output 2

andat

Sample Input 3

z
1

Sample Output 3

z


#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <queue>
#include <stack>
#include <cstdlib>
#include <map>
#include <iomanip>
#include <set>
#include <stdio.h>
#include <ctype.h>
#include <random>
#include <string.h>
#include <cmath>
#include <unordered_map>
#include <cstdio>
using namespace std;
#define pie 3.141592653589793238462643383279
#define int long long
#define P pair<int,int>
#define all(vec) vec.begin(),vec.end()

int gcd(int x, int y) {
	if (y == 0)return x;
	return gcd(y, x%y);
}
int lcm(int x, int y) {
	return x / gcd(x, y)*y;
}
int kai(int x, int y, int m) {
	int res = 1;
	for (int i = x - y + 1; i <= x; i++) {
		res *= i; res %= m;
	}
	return res;
}
int mod_pow(int x, int y, int m) {
	int res = 1;
	while (y > 0) {
		if (y & 1) {
			res = res * x % m;
		}
		x = x * x % m;
		y >>= 1;
	}
	return res;
}

int comb(int x, int y, int m) {
	if (y > x)return 0;
	return kai(x, y, m) * mod_pow(kai(y, y, m), m - 2, m) % m;
}

int n;
P x[4010];
int a[2010], b[2010];
int cnt1[2010][2010], cnt2[2010][2010];
bool bl1[2010], bl2[2010];
int d[4010][2010];

signed main() {
	cin >> n;
	for (int i = 1; i <= 2 * n; i++) {
		char c; int p; cin >> c >> p;
		if (c == 'W')a[p] = i, x[i] = make_pair(p, 0);
		else b[p] = i, x[i] = make_pair(p, 1);
	}
	for (int i = 2 * n; i >= 1; i--) {
		if (x[i].second == 0) {
			int cnt = 0;
			for (int j = 1; j < x[i].first; j++)if (bl1[j])cnt++;
			for (int j = 0; j <= n; j++) {
				if (bl2[j])cnt++;
				cnt1[x[i].first][j] = cnt;
			}
			bl1[x[i].first] = true;
		}
		else {
			int cnt = 0;
			for (int j = 1; j < x[i].first; j++)if (bl2[j])cnt++;
			for (int j = 0; j <= n; j++) {
				if (bl1[j])cnt++;
				cnt2[x[i].first][j] = cnt;
			}
			bl2[x[i].first] = true;
		}
	}
	for (int i = 0; i <= 2 * n; i++)for (int j = 0; j <= n; j++)d[i][j] = 1000000000;
	d[0][0] = 0;
	for (int i = 1; i <= 2 * n; i++) {
		for (int j = 0; j <= min(i - 1, n); j++)d[i][j] = min(d[i][j], d[i - 1][j] + cnt2[i - j][j]);
		for (int j = 1; j <= min(i, n); j++)d[i][j] = min(d[i][j], d[i - 1][j - 1] + cnt1[j][i - j]);
	}
	cout << d[2 * n][n] << endl;
}

Score : 600 points

Problem Statement

There are 2N balls, N white and N black, arranged in a row. The integers from 1 through N are written on the white balls, one on each ball, and they are also written on the black balls, one on each ball.
The integer written on the i-th ball from the left (1 ≤ i ≤ 2N) is a_i, and the color of this ball is represented by a letter c_i.
c_i = W represents the ball is white; c_i = B represents the ball is black.

Takahashi the human wants to achieve the following objective:

For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the white ball with i written on it is to the left of the white ball with j written on it.

For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the black ball with i written on it is to the left of the black ball with j written on it.

In order to achieve this, he can perform the following operation:

Swap two adjacent balls.

Find the minimum number of operations required to achieve the objective.

Constraints

1 ≤ N ≤ 2000

1 ≤ a_i ≤ N

c_i = W or c_i = B.

If i ≠ j, (a_i,c_i) ≠ (a_j,c_j).

Input

Input is given from Standard Input in the following format:

N
c_1 a_1
c_2 a_2
:
c_{2N} a_{2N}

Output

Print the minimum number of operations required to achieve the objective.

Sample Input 1

3
B 1
W 2
B 3
W 1
W 3
B 2

Sample Output 1

4

The objective can be achieved in four operations, for example, as follows:

Swap the black 3 and white 1.

Swap the white 1 and white 2.

Swap the black 3 and white 3.

Swap the black 3 and black 2.

Sample Input 2

4
B 4
W 4
B 3
W 3
B 2
W 2
B 1
W 1

Sample Output 2

18

Sample Input 3

9
W 3
B 1
B 4
W 1
B 5
W 9
W 2
B 6
W 5
B 3
W 8
B 9
W 7
B 2
B 8
W 4
W 6
B 7

Sample Output 3

41


#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

#define REP(i,n) for(int i=0;i<n;++i)
#define SORT(name) sort(name.begin(), name.end())
#define ZERO(p) memset(p, 0, sizeof(p))
#define MINUS(p) memset(p, -1, sizeof(p))
#if 1
#  define DBG(fmt, ...) printf(fmt, ##__VA_ARGS__)
#else
#  define DBG(fmt, ...)
#endif

const ll LLINF = (1LL<<60);
const int INF = (1LL<<30);
const int MOD = 1000000007;
#define MAX_N 2010
#define MAX_2N 4010

ll N;
char C[MAX_N] = {};
ll A[MAX_N] = {};

// 1-indexed であることに注意
template<typename T>
class BITree {
    public:
        BITree(int n) : m_N(n + 1) { m_Tree.assign(m_N, 0); }
        // [1, i] の合計値を返す (log m_N)
        // 閉区間であることに注意
        T Sum(int i) {
            if(i < 1 || i >= m_N) { return 0; }
            T s = 0;
            while(i > 0) { s += m_Tree[i]; i -= i & -i; }
            return s;
        }
        // [i, j] の合計値を返す (log m_N)
        // i < j
        // 閉区間であることに注意
        T Sum(int i, int j) {
            if(i > j) { return 0; }
            return Sum(j) - Sum(i-1);
        }
        // i 番目の要素(1-indexed)に x を足して更新 O(log m_N)
        void Add(int i, T x){ while(i < m_N) { m_Tree[i] += x; i += i & -i; } }
    private:
        int m_N;            // 要素数
        vector<T> m_Tree;   // BIT 本体
};

// 順列 p の転倒数を返す (転倒数：順番を維持したままペアをとったとき、左の数字の方が大きいペアの数)
// O (N log N) (N: 順列の最大値)
template<typename T>
T GetInversionCnt(const vector<T>& p) {
    T ret = 0;
    T max_val = 0;
    for(auto& val : p) { max_val = max(max_val, val); }
    BITree<T> bit(max_val);    // 以左に現れた数を BIT で管理
    for(int i = 0; i < p.size(); ++i) {
        ret += bit.Sum(p[i] + 1, max_val);  // 自分より大きいものを数える
        bit.Add(p[i], 1);   // 現れた数を更新
    }
    return ret;
}

// 2 つの順列の転倒距離を求める
// 転倒距離：同じサイズ N の順列 X と Y で順番が入れ替わっている数字のペアの数
// X か Y のどちらかが (1, 2, 3 .., N) なら、転倒距離はもう一方の転倒数
// O(N log N)
template<typename T>
T GetInversionDist(const vector<T>& v1, const vector<T>& v2) {
    assert(v1.size() == v2.size());
    vector<T> val_to_ind, comp;
    val_to_ind.assign(v1.size() + 1, 0);
    for(int i = 0; i < v1.size(); ++i) {
        val_to_ind[v1[i]] = i + 1;
    }
    for(int i = 0; i < v2.size(); ++i) {
        comp.push_back(val_to_ind[v2[i]]);
    }
    return GetInversionCnt(comp);
}

// b とかぶらない数にする
static inline ll change_w(ll w) { return w + N; }

enum CostType { CostB = 0, CostW };

// B を [1,i] , W を [1,j] 個既に置いているときに黒の i+1 を置いた時の転倒数
ll cost(ll i, ll j, ll type) {
#if 0
    vector<ll> v1, v2;
    // [1,i], [1,j] の置き方は合わせる
    for(ll b = 1; b <= i; ++b) {
        v1.push_back(b);
        v2.push_back(b);
    }
    for(ll w = 1; w <= j; ++w) {
        v1.push_back(change_w(w));
        v2.push_back(change_w(w));
    }
    if(type == CostB) { v1.push_back(i+1); }
    else { v1.push_back(change_w(j+1)); }

    // 残りを置いていく
    REP(ind, 2 * N) {
        if(C[ind] == 'B') {
            if(type == CostB) {
                if(A[ind] == i + 1) { v2.push_back(A[ind]); }
                else if(A[ind] > i + 1) { v1.push_back(A[ind]); v2.push_back(A[ind]); }
            } else {
                if(A[ind] > i) { v1.push_back(A[ind]); v2.push_back(A[ind]); }
            }
        } else {
            if(type == CostB) {
                if(A[ind] > j) { v1.push_back(change_w(A[ind])); v2.push_back(change_w(A[ind])); }
            } else {
                if(A[ind] == j + 1) { v2.push_back(change_w(A[ind])); }
                else if(A[ind] > j + 1) { v1.push_back(change_w(A[ind])); v2.push_back(change_w(A[ind])); }
            }
        }
    }
    ll ret = GetInversionDist(v1, v2);
#else

    // 現在の i+1/j+1 の位置 から左にある i と j より大きいものの数
    ll ret = 0;
    ll cur = 0;
    for(cur = 0; cur < 2 * N; ++cur) {
        if((type == CostB && C[cur] == 'B' && A[cur] == i+1) ||
           (type == CostW && C[cur] == 'W' && A[cur] == j+1)) {
            break;
        }
    }
    BITree<ll> bit_B(N), bit_W(N);    // 以左に現れた数を BIT で管理
    for(ll ind = 0; ind < cur; ++ind) {
        // 現れた数を更新
        if(C[ind] == 'B') { bit_B.Add(A[ind], 1); }
        else { bit_W.Add(A[ind], 1); }

    }
    if(type == CostB) {
        ret += bit_B.Sum(i+2, N);
        ret += bit_W.Sum(j+1, N);
    }
    else {
        ret += bit_B.Sum(i+1, N);
        ret += bit_W.Sum(j+2, N);
    }
#endif
    //DBG("i: %lld j: %lld type: %c ret: %lld\n", i, j, (type == CostB) ? 'B' : 'W', ret);
    return ret;
}

ll dp[MAX_N][MAX_N] = {};

// B を [1,i] 個, W を [1,j] 個置いた時の最小転倒数
ll dfs(ll i, ll j) {
    if(i <= 0 && j <= 0) {
        dp[0][0] = 0;
        return 0;
    }
    if(dp[i][j] != -1) { return dp[i][j]; }
    ll cand1 = INF, cand2 = INF;
    if(i > 0) { cand1 = dfs(i-1, j) + cost(i-1, j, CostB); }
    if(j > 0) { cand2 = dfs(i, j-1) + cost(i, j-1, CostW); }
    dp[i][j] = min(cand1, cand2);
    return dp[i][j];
}

signed main()
{
    cin >> N;
    REP(i, 2 * N) { cin >> C[i] >> A[i]; }
    MINUS(dp);
    printf("%lld\n", dfs(N, N));
    return 0;
}


#include <bits/stdc++.h>
#define int long long

using namespace std;

const int MaxN = 1e5 + 15;

int n;
vector <int> v[MaxN];
string s;

int cnt[MaxN];

int dp[MaxN];
int dp1[MaxN];
int dp2[MaxN];

int all;
int bw;

void dfs(int x, int p = 0)
{
    ++all;

    vector <int> dps;

    bool OK = false;

    for(int to : v[x])
        if(to != p)
            if(cnt[to] > 0)
            {
                dfs(to, x);

                dps.push_back(dp1[to]);

                int cur = 1 + dp1[to] - (s[x] == 'B' ? 1 : -1);

                if(!p)
                    --cur;

                dp1[x] = max(dp1[x], cur);
                OK = true;

                dp[x] = max(dp[x], dp[to]);
            }

    if(!OK)
    {
        dp[x] = 0;
    }else
        if(dps.size() > 1)
    {
        sort(dps.begin(), dps.end());
        dp2[x] = dps.back() + dps[dps.size() - 2];
    }

    dp[x] = max(max(dp[x], dp1[x]), dp2[x]);

    if(!p)
        OK = false;

    if(OK && s[x] == 'W')
        ++bw;

    --dp[x];
}

main()
{
//    freopen("output.txt", "r", stdin);

    ios_base :: sync_with_stdio(false);
    cin.tie(NULL);

    cin >> n;

    for(int i = 1; i < n; ++i)
    {
        int x, y;
        cin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);

        ++cnt[x];
        ++cnt[y];
    }

    cin >> s;
    s = "#" + s;

    set<int> ss;

    for(int i = 1; i <= n; ++i)
    {
        if(cnt[i] == 1 && s[i] == 'B')
            ss.insert(i);
    }

    while(!ss.empty())
    {
        int x = (*ss.begin());
        ss.erase(ss.begin());

        cnt[x] = -1;

        for(int to : v[x])
        {
            --cnt[to];
            if(cnt[to] == 1 && s[to] == 'B')
                ss.insert(to);
        }
    }

    int root = 0;

    for(int i = 1; i <= n; ++i)
        if(cnt[i] == 1)
            root = i;

    if(!root)
    {
        return cout << 0 << '\n', 0;
    }

    dfs(root);

    //cout << root << ' ' << all << ' ' << bw << ' ' << dp[root] << '\n';

    cout << 2 * (all - 1) + bw - dp[root] << '\n';

    return 0;
}
/**
1212
WBBW
*/

Score : 800 points

Problem Statement

There is a tree with N vertices numbered 1 through N.
The i-th edge connects Vertex x_i and y_i.
Each vertex is painted white or black.
The initial color of Vertex i is represented by a letter c_i.
c_i = W represents the vertex is white; c_i = B represents the vertex is black.

A cat will walk along this tree.
More specifically, she performs one of the following in one second repeatedly:

Choose a vertex that is adjacent to the vertex where she is currently, and move to that vertex. Then, invert the color of the destination vertex.

Invert the color of the vertex where she is currently.

The cat's objective is to paint all the vertices black. She may start and end performing actions at any vertex.
At least how many seconds does it takes for the cat to achieve her objective?

Constraints

1 ≤ N ≤ 10^5

1 ≤ x_i,y_i ≤ N (1 ≤ i ≤ N-1)

The given graph is a tree.

c_i = W or c_i = B.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_{N-1} y_{N-1}
c_1c_2..c_N

Output

Print the minimum number of seconds required to achieve the objective.

Sample Input 1

5
1 2
2 3
2 4
4 5
WBBWW

Sample Output 1

5

The objective can be achieved in five seconds, for example, as follows:

Start at Vertex 1. Change the color of Vertex 1 to black.

Move to Vertex 2, then change the color of Vertex 2 to white.

Change the color of Vertex 2 to black.

Move to Vertex 4, then change the color of Vertex 4 to black.

Move to Vertex 5, then change the color of Vertex 5 to black.

Sample Input 2

6
3 1
4 5
2 6
6 1
3 4
WWBWBB

Sample Output 2

7

Sample Input 3

1
B

Sample Output 3

0

Sample Input 4

20
2 19
5 13
6 4
15 6
12 19
13 19
3 11
8 3
3 20
16 13
7 14
3 17
7 8
10 20
11 9
8 18
8 2
10 1
6 13
WBWBWBBWWWBBWWBBBBBW

Sample Output 4

21


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
  int n;
  cin >> n;
  vector<ll> a(n);
  for(int i=0; i<n; i++){
    cin >> a[i];
  }
  map<ll, ll> s;
  vector<ll> l(n+1);
  s[l[0]]++;
  for(int i=0; i<n; i++){
    l[i+1] = l[i] + a[i];
    s[l[i+1]]++;
  }
  ll ans = 0;
  for(auto p : s){
    ll num = p.second;
    ans += (ll)num*(num-1)/2;
  }
  cout << ans << endl;
}

Score : 200 points

Problem Statement

We have an integer sequence A, whose length is N.

Find the number of the non-empty contiguous subsequences of A whose sums are 0.
Note that we are counting the ways to take out subsequences.
That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.

Constraints

1 \leq N \leq 2 \times 10^5

-10^9 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Find the number of the non-empty contiguous subsequences of A whose sum is 0.

Sample Input 1

6
1 3 -4 2 2 -2

Sample Output 1

3

There are three contiguous subsequences whose sums are 0: (1,3,-4), (-4,2,2) and (2,-2).

Sample Input 2

7
1 -1 1 -1 1 -1 1

Sample Output 2

12

In this case, some subsequences that have the same contents but are taken from different positions are counted individually.
For example, three occurrences of (1, -1) are counted.

Sample Input 3

5
1 -2 3 -4 5

Sample Output 3

0

There are no contiguous subsequences whose sums are 0.


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

template<class T> void vin(vector<T>& v, int n) {
    v.resize(n);
    for (int i = 0; i < n; ++i) {
        cin >> v[i];
    }
}

ll sum[301010];

int main() {
    int n;
    cin >> n;
    vector<ll> a(n);
    rep(i, n) cin >> a[i];
    rep(i, n) {
        sum[i] += a[i];
        if (i) sum[i] += sum[i-1];
    }
    map<ll, ll> mp;
    rep(i, n) {
        mp[sum[i]]++;
        //cout << sum[i] << " ";
    }
    ll ans = mp[0];
    for (auto tmp : mp) {
        if (tmp.second >= 2) {
            ans += tmp.second * (tmp.second - 1) / 2;
        }
    }
    cout << ans << endl;
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <array>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <utility>
#include <functional>

using namespace std;
using lli = long long int;
template<class T, class U> void init_n(vector<T>& v, size_t n, U x)
{ v = vector<T>(n, x); }
template<class T> void init_n(vector<T>& v, size_t n) { init_n(v, n, T()); }
template<class T> void read_n(vector<T>& v, size_t n)
{ v = vector<T>(n); for (lli i=0; i<n; ++i) cin >> v[i]; }
template<class T, class U> void read_n(vector<pair<T, U>>& v, size_t n)
{ v = vector<pair<T, U>>(n);
  for (lli i=0; i<n; ++i) cin >> v[i].first >> v[i].second; }
template<class T> T gabs(const T& x) { return max(x, -x); }
#define abs gabs

lli n;
vector<string> s;
int main() {
  cin >> n;
  read_n(s, n);
  lli ans = 0;
  for (lli d=0; d<n; ++d) {
    bool ok = true;
    for (lli j=0; j<n; ++j) {
      for (lli i=0; i<n; ++i) {
	if (s[j][i] != s[i][j]) {
	  ok = false;
	  goto out;
	}
      }
    }
out:
    if (ok) ans += n;
    auto t = s.back();
    s.pop_back();
    s.insert(begin(s), t);
  }
  cout << ans << endl;
  return 0;
}

Score : 500 points

Problem Statement

Snuke has two boards, each divided into a grid with N rows and N columns.
For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).

There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i,j}. On the second board, nothing is written yet.

Snuke will write letters on the second board, as follows:

First, choose two integers A and B ( 0 \leq A, B < N ).

Write one letter in each square on the second board.
Specifically, write the letter written in Square ( i+A, j+B ) on the first board into Square (i,j) on the second board.
Here, the k-th row is also represented as the (N+k)-th row, and the k-th column is also represented as the (N+k)-th column.

After this operation, the second board is called a good board when, for every i and j ( 1 \leq i, j \leq N ), the letter in Square (i,j) and the letter in Square (j,i) are equal.

Find the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Constraints

1 \leq N \leq 300

S_{i,j} ( 1 \leq i, j \leq N ) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}S_{1,2}..S_{1,N}
S_{2,1}S_{2,2}..S_{2,N}
:
S_{N,1}S_{N,2}..S_{N,N}

Output

Print the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Sample Input 1

2
ab
ca

Sample Output 1

2

For each pair of A and B, the second board will look as shown below:

The second board is a good board when (A,B) = (0,1) or (A,B) = (1,0), thus the answer is 2.

Sample Input 2

4
aaaa
aaaa
aaaa
aaaa

Sample Output 2

16

Every possible choice of A and B makes the second board good.

Sample Input 3

5
abcde
fghij
klmno
pqrst
uvwxy

Sample Output 3

0

No possible choice of A and B makes the second board good.


#include <bits/stdc++.h>
using namespace std;
#define db(x) cerr << #x << "=" << x << endl
#define db2(x, y) cerr << #x << "=" << x << "," << #y << "=" << y << endl
#define db3(x, y, z) cerr << #x << "=" << x << "," << #y << "=" << y << "," << #z << "=" << z << endl
typedef long long ll;
typedef long double ld;
const int MAXN = 200005;
int par[MAXN], P[MAXN], V[MAXN];
ll num0[MAXN], num1[MAXN], val[MAXN];
int root(int a) {
	if (par[a] == a) return a;
	return par[a] = root(par[a]);
}
struct cmp {
	bool operator()(int a, int b) {
		ll va = num0[a] * num1[b], vb = num0[b] * num1[a];
		if (va != vb) return va > vb;
		return a < b;
	}
};
int main() {
	int N;
	scanf("%d", &N);
	for (int i = 2; i <= N; ++i) scanf("%d", &P[i]);
	for (int i = 1; i <= N; ++i) scanf("%d", &V[i]);
	for (int i = 1; i <= N; ++i) {
		par[i] = i;
		if (V[i] == 1) ++num1[i];
		else ++num0[i];
	}
	set<int, cmp> S;
	for (int i = 2; i <= N; ++i) {
		S.insert(i);
	}
	while (!S.empty()) {
		int x = *S.begin();
		S.erase(S.begin());
		int y = root(P[x]);
		S.erase(y);
		par[x] = y;
		val[y] += val[x] + num1[y] * num0[x];
		num0[y] += num0[x];
		num1[y] += num1[x];
		if (y != 1) S.insert(y);
	}
	printf("%lld\n", val[1]);
}

Score : 1700 points

Problem Statement

Snuke has a rooted tree with N vertices, numbered 1 through N.
Vertex 1 is the root of the tree, and the parent of Vertex i ( 2\leq i \leq N ) is Vertex P_i ( P_i < i ).
There is a number, 0 or 1, written on each vertex. The number written on Vertex i is V_i.

Snuke would like to arrange the vertices of this tree in a horizontal row.
Here, for every vertex, there should be no ancestor of that vertex to the right of that vertex.

After arranging the vertices, let X be the sequence obtained by reading the numbers written on the vertices from left to right in the arrangement.
Snuke would like to minimize the inversion number of X.
Find the minimum possible inversion number of X.

Notes

The inversion number of a sequence Z whose length N is the number of pairs of integers i and j ( 1 \leq i < j \leq N ) such that Z_i > Z_j.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq P_i < i ( 2 \leq i \leq N )

0 \leq V_i \leq 1 ( 1 \leq i \leq N )

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_2 P_3 ... P_N
V_1 V_2 ... V_N

Output

Print the minimum possible inversion number of X.

Sample Input 1

6
1 1 2 3 3
0 1 1 0 0 0

Sample Output 1

4

When the vertices are arranged in the order 1, 3, 5, 6, 2, 4, X will be (0, 1, 0, 0, 1, 0), whose inversion number is 4.
It is impossible to have fewer inversions, so the answer is 4.

Sample Input 2

1

0

Sample Output 2

0

X = (0), whose inversion number is 0.

Sample Input 3

15
1 2 3 2 5 6 2 2 9 10 1 12 13 12
1 1 1 0 1 1 0 0 1 0 0 1 1 0 0

Sample Output 3

31


#include <bits/stdc++.h>

#if DEBUG
template <typename T>
void debug(const T& value) {
  std::cerr << value;
}
template <typename T, typename... Ts>
void debug(const T& value, const Ts&... args) {
  std::cerr << value << ", ";
  debug(args...);
}
#define dbg(...)                        \
  do {                                  \
    cerr << #__VA_ARGS__ << ": ";       \
    debug(__VA_ARGS__);                 \
    cerr << " (L" << __LINE__ << ")\n"; \
  } while (0)
#else
#define dbg(...)
#endif

void read_from_cin() {}
template <typename T, typename... Ts>
void read_from_cin(T& value, Ts&... args) {
  std::cin >> value;
  read_from_cin(args...);
}
#define rd(type, ...) \
  type __VA_ARGS__;   \
  read_from_cin(__VA_ARGS__);

template <typename T>
void write_to_cout(const T& value) {
  std::cout << value << '\n';
}
template <typename T, typename... Ts>
void write_to_cout(const T& value, const Ts&... args) {
  std::cout << value << ' ';
  write_to_cout(args...);
}
#define wt(...) write_to_cout(__VA_ARGS__);

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

using ll = long long;

template <typename T>
using V = std::vector<T>;
template <typename T>
using VV = V<V<T>>;

using namespace std;

int main() {
  rd(string, s);
  wt(700 + count(all(s), 'o') * 100);
}

Score : 100 points

Problem Statement

In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).

A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is three characters long, and if the first character in S is o, it means the ramen should be topped with boiled egg; if that character is x, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in S mean the presence or absence of sliced pork and green onions on top of the ramen.

Write a program that, when S is given, prints the price of the corresponding bowl of ramen.

Constraints

S is a string of length 3.

Each character in S is o or x.

Input

Input is given from Standard Input in the following format:

S

Output

Print the price of the bowl of ramen corresponding to S.

Sample Input 1

oxo

Sample Output 1

900

The price of a ramen topped with two kinds of toppings, boiled egg and green onions, is 700 + 100 \times 2 = 900 yen.

Sample Input 2

ooo

Sample Output 2

1000

The price of a ramen topped with all three kinds of toppings is 700 + 100 \times 3 = 1000 yen.

Sample Input 3

xxx

Sample Output 3

700

The price of a ramen without any toppings is 700 yen.


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

string S;

int main(){
  int ans=700;

  cin >> S;
  for(int i=0; i<3; i++){
    if(S[i]=='o') ans += 100;
  }
  cout << ans << endl;
}


#include <iostream>
#include <cmath>

using namespace std;

int main() {
	int N, X;

	cin >> N >> X;

	int rem = X, minimum = 100000, ans = 0;
	for (int i = 0; i < N; i++) {
		int tmp;
		cin >> tmp;
		rem -= tmp;
		ans++;
		minimum = min(minimum, tmp);
	}

	ans += rem / minimum;

	cout << ans << endl;

	return 0;
}

Score : 200 points

Problem Statement

Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts.

Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition:

For each of the N kinds of doughnuts, make at least one doughnut of that kind.

At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Also, under the constraints of this problem, it is always possible to obey the condition.

Constraints

2 ≤ N ≤ 100

1 ≤ m_i ≤ 1000

m_1 + m_2 + ... + m_N ≤ X ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
m_1
m_2
:
m_N

Output

Print the maximum number of doughnuts that can be made under the condition.

Sample Input 1

3 1000
120
100
140

Sample Output 1

9

She has 1000 grams of Moto and can make three kinds of doughnuts. If she makes one doughnut for each of the three kinds, she consumes 120 + 100 + 140 = 360 grams of Moto. From the 640 grams of Moto that remains here, she can make additional six Doughnuts 2. This is how she can made a total of nine doughnuts, which is the maximum.

Sample Input 2

4 360
90
90
90
90

Sample Output 2

4

Making one doughnut for each of the four kinds consumes all of her Moto.

Sample Input 3

5 3000
150
130
150
130
110

Sample Output 3

26


#include <iostream>

using namespace std;

int main()
{
	int a,b,c,x,y;
	long long t=0;
	cin>>a>>b>>c>>x>>y;

	if (a + b > 2 * c)
	{
		if (x < y)
		{
			t += 2 * x * c;
			if ((y-x) * b > (y-x)*2*c)
			{
				t += 2 * (y-x) * c;
			}
			else t += (y-x)*b;
		}
		else
		{
			t += 2 * y * c;
			if ((x-y) * a > (x-y)*2*c)
			{
				t += 2 * (x-y) * c;
			}
			else t += (x-y)*a;
		}
	}
	else
	{
		t += a*x + b*y;
	}
	cout << t << "\n";
	return 0;
}

Score : 300 points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy 200000 AB-pizzas and rearrange them into 100000 A-pizzas and 100000 B-pizzas. We will have 10000 more A-pizzas than necessary, but that is fine.


#include <bits/stdc++.h>
#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 rep2(i,j,n) for(int j=i;j<n;j++)
#define rep3(i,j,n) for(int j=i;j<=n;j++)
#define rrep(i,n) for(int i=n-1;i>=0;i--)
#define sp(n) cout << fixed << setprecision(n)
typedef long long ll;
using namespace std;
int main(void){
    ll n,c;cin>>n>>c;
    vector<ll> x(n),v(n),a(n),b(n),d(n),e(n);
    rep(i,n) cin>>x[i]>>v[i];
    ll tmp=0;
    rep(i,n){
        if(i==0){
            tmp+=v[i];
            a[i]=max(tmp-x[i],(ll)0);
            d[i]=(a[i]==tmp-x[i])? x[i]:0;
        }
        else{
            tmp+=v[i];
            a[i]=max(a[i-1],tmp-x[i]);
            d[i]=(a[i]==tmp-x[i])? x[i]:d[i-1];
        }
    }
    reverse(x.begin(),x.end());
    reverse(v.begin(),v.end());
    tmp=0;
    rep(i,n){
        x[i]=c-x[i];
        if(i==0){
            tmp+=v[i];
            b[i]=max(tmp-x[i],(ll)0);
            e[i]=(b[i]==tmp-x[i])? x[i]:0;
        }
        else{
            tmp+=v[i];
            b[i]=max(b[i-1],tmp-x[i]);
            e[i]=(b[i]==tmp-x[i])? x[i]:e[i-1];
        }
    }

    reverse(b.begin(),b.end());
    reverse(e.begin(),e.end());
    //rep(i,n) cout<<d[i]<<" "<<e[i]<<endl;
    ll res=0;
    rep(i,n){
        //cout<<i<<endl;
        if(i==n-1){
            ll now=a[i];
            res=max(res,now);
        }
        else{
            ll left=a[i],right=b[i+1];
            //cout<<left<<" "<<right<<endl;
            ll now=right+left;
            now-=min(d[i],e[i+1]);
            res=max(res,now);
        }
        if(i==0){
            ll now=b[i];
            res=max(res,now);
        }
        else{
            ll left=a[i-1],right=b[i];
            //cout<<left<<" "<<right<<endl;
            ll now=right+left;
            now-=min(d[i-1],e[i]);
            res=max(res,now);
        }
    }
    cout<<res<<endl;
}

Score : 500 points

Problem Statement

"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.

Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.

Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.

Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

1 ≤ x_1 < x_2 < ... < x_N < C

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

300 points will be awarded for passing the test set satisfying N ≤ 100.

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 8 kilocalories, thus he can take in 192 kilocalories on balance, which is the largest possible value.

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

Even though the only sushi is so far that it does not fit into a 32-bit integer, its nutritive value is low, thus he should immediately leave without doing anything.

Sample Input 4

15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000

Sample Output 4

6500000000

All these sample inputs above are included in the test set for the partial score.


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    int A, B, C, X, Y;
    cin >> A >> B >> C >> X >> Y;
    int ans = 0;
    for (int c = 0; c <= max(X, Y); ++c)
    {
        int price = 2 * c * C;
        if (X - c > 0)
        {
            price += (X - c) * A;
        }
        if (Y - c > 0)
        {
            price += (Y - c) * B;
        }
        if (ans == 0)
        {
            ans = price;
        }
        else
        {
            ans = min(price, ans);
        }
    }
    cout << ans << endl;
}


#include <iostream>
#include <algorithm>

#define ll long long int

using namespace std;

ll x[100005];
ll v[100005];
ll n, c;

int main() {
  cin >> n >> c;
  for (int i = 0; i < n; i++) {
    cin >> x[i] >> v[i];
  }
  ll ans = 0;
  ll cals = 0;
  for (int i = 0; i < n; i++) {
    cals += v[i];
    ans = max(ans, cals - x[i]);
  }
  cals = 0;
  for (int i = n - 1; i >= 0; i--) {
    cals += v[i];
    ans = max(ans, cals - (c - x[i]));
  }

  for (int i = 0; i < n; i++) {
    for (int j = n - 1; j > i; j--) {
      ll cals = 0;
      for (int k = 0; k <= i; k++) {
	cals += v[k];
      }
      for (int k = n - 1; k >= j; k--) {
	cals += v[k];
      }
      ll dist = min(2 * x[i] + c - x[j], 2 * (c - x[j]) + x[i]);
      ans = max(ans, cals - dist);
    }
  }
  cout << ans;
}


#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
using namespace std;
using ll = long long;

int main(int argc, const char * argv[]) {
    int n;
    cin >> n;
    vector<pair<int, ll>> v(n);

    ll x;
    pair<ll, int> p;
    for (int i = 0; i < n; i++) {
        cin >> x;
        p .first = x;
        p.second = i;
        v[i] = p;
    }
    sort(v.begin(), v.end());
    int a[n];
    for (int i = 0; i < n; i++) {
        a[v[i].second] = i;
    }
    for (int i = 0; i < n; i++) {
        if (a[i] < n / 2) {
            cout << v[(n+1)/2+1-1].first << endl;
        }else{
            cout << v[(n+1)/2-1].first << endl;
        }
    }
    return 0;
}

Score : 300 points

Problem Statement

When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.

You are given N numbers X_1, X_2, ..., X_N, where N is an even number.
For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..., X_{i-1}, X_{i+1}, ..., X_N be B_i.

Find B_i for each i = 1, 2, ..., N.

Constraints

2 \leq N \leq 200000

N is even.

1 \leq X_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print N lines.
The i-th line should contain B_i.

Sample Input 1

4
2 4 4 3

Sample Output 1

4
3
3
4

Since the median of X_2, X_3, X_4 is 4, B_1 = 4.

Since the median of X_1, X_3, X_4 is 3, B_2 = 3.

Since the median of X_1, X_2, X_4 is 3, B_3 = 3.

Since the median of X_1, X_2, X_3 is 4, B_4 = 4.

Sample Input 2

2
1 2

Sample Output 2

2
1

Sample Input 3

6
5 5 4 4 3 3

Sample Output 3

4
4
4
4
4
4


#include<iostream>
#include<set>
using namespace std;

typedef long long ll;

int n;
set<int> A;

int main() {
    cin >> n;
    for(int i = 0; i < n; i++) {
        int a;
        cin >> a;
        A.insert(a);
    }

    int mx = *A.rbegin();
    A.erase(mx);
    auto iter = A.lower_bound(mx/2);
    if(iter == A.begin()) {
        cout << mx << " " << *iter << endl;
        return 0;
    }
    if(iter == A.end()) {
        cout << mx << " " << *(--iter) << endl;
        return 0;
    }
    int r = *iter;
    int l = *(--iter);
    int ans = (mx - l < r - mx) ? l : r;

    cout << l << " " << r << endl;

    cout << mx << " " << ans << endl;

    return 0;
}

Score : 400 points

Problem Statement

Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order.
From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized.
If there are multiple pairs that maximize the value, any of them is accepted.

Constraints

2 \leq n \leq 10^5

0 \leq a_i \leq 10^9

a_1,a_2,...,a_n are pairwise distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print a_i and a_j that you selected, with a space in between.

Sample Input 1

5
6 9 4 2 11

Sample Output 1

11 6

\rm{comb}(a_i,a_j) for each possible selection is as follows:

\rm{comb}(4,2)=6

\rm{comb}(6,2)=15

\rm{comb}(6,4)=15

\rm{comb}(9,2)=36

\rm{comb}(9,4)=126

\rm{comb}(9,6)=84

\rm{comb}(11,2)=55

\rm{comb}(11,4)=330

\rm{comb}(11,6)=462

\rm{comb}(11,9)=55

Thus, we should print 11 and 6.

Sample Input 2

2
100 0

Sample Output 2

100 0


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <functional>
#include <string>
#include <sstream>
#include <complex>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>

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

#define pi 3.141592653589793)
#define mod 1000000007

int n, a[100001];
int ans = 1000000000;
int num;

void solve() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}
	sort(a, a + n);
	int left, right;

	left = a[n - 1];
	for (int i = 0; i < n-1; i++) {
		if (ans >= abs(left / 2 - a[i])) {
			ans = abs(left / 2 - a[i]);
			num = i;
		}
	}
	right = a[num];
	cout << left << " " <<right << endl;

}

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


#include<stdio.h>
#include<iostream>
using namespace std;

int A,B,K;
int main (){

    cin >> A >> B >> K;
    int x,y;
    if(B - K < 0) x = A+K;
    else x = B - K;
    for(int i=A; i<A+K; i++) {
        y = i;
        cout << y << endl;
        if(i == B ) return 0;
    }
    for(int i=x+1; i<=B; i++) {
        if( y == i ) ;
        else cout << i << endl;
    }
    return 0;
}

Score : 200 points

Problem Statement

Print all the integers that satisfies the following in ascending order:

Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.

Constraints

1 \leq A \leq B \leq 10^9

1 \leq K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print all the integers that satisfies the condition above in ascending order.

Sample Input 1

3 8 2

Sample Output 1

3
4
7
8

3 is the first smallest integer among the integers between 3 and 8.

4 is the second smallest integer among the integers between 3 and 8.

7 is the second largest integer among the integers between 3 and 8.

8 is the first largest integer among the integers between 3 and 8.

Sample Input 2

4 8 3

Sample Output 2

4
5
6
7
8

Sample Input 3

2 9 100

Sample Output 3

2
3
4
5
6
7
8
9


#define _GLIBCXX_DEBUG//TLEの原因になるので注意！！！！！！！！！！！
#include<cmath>
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
vector<int> arr;
stack<int> st;
queue<int> qu;
queue<pair<int,int> > qu2;
priority_queue<int> pq;
#define rep(i,n) for(int i=0; i<(int)(n); i++)
#define rep2(i,n) for(int i=1; i<=(int)(n); i++)
#define mins(x,y) x=min(x,y)
#define maxs(x,y) x=max(x,y)
typedef set<int> set_t;
typedef set<string> set_g;
typedef complex<double> xy_t;
static const int NIL = -1;
static const int INF = 1000000007;
#define mp make_pair

/*int P[10010];
void init(int n){//Union-find
    for(int i=0;i<n;++i)P[i]=i;
}
int root(int a) {
    if(P[a]==a)return a;
    return (P[a]=root(P[a]));
}
bool is_same_set(int a,int b){
    return root(a) == root(b);//代表元を求める
}
void unite(int a,int b){
    P[root(a)]=root(b);
}//対set,グラフ？
//セグメント木？？
*/

double dot_product(xy_t a, xy_t b) { return (conj(a)*b).real(); }//内積
double cross_product(xy_t a, xy_t b) { return (conj(a)*b).imag(); }//外積
xy_t projection(xy_t p, xy_t b) { return b*dot_product(p,b)/norm(b); }//投影
//対図形

#define mod 1000000007
/*ll f[2001];
//int n,k とかしておく

ll pw(ll x, ll y){//euclidの互除法より
    ll a= 1;
    while(y){
        if(y&1){//奇数なら
            a = a*x%mod;
        }
        x = x*x%mod;
        y /= 2;
    }
    return a;
}

ll modinv(ll x){//逆元を求める
    return pw(x, mod - 2 );
}

ll comb(int n,int r){
    if(n<r){
        return 0;
    }
    return f[n] * modinv(f[r])%mod*modinv(f[n-r])%mod;
}//対combination//ただしfは用意してね
*/

//cerrはコメントアウトしなくても通る

int main(){
    vector<int> a(3);
    cin >> a[0]>> a[1]>> a[2];
    sort(a.begin(),a.end(),greater<int>());
    int ans=0;
    int l=(a[0]-a[2])/2;
    a[2]+=2*l;
    int r=(a[0]-a[1])/2;
    a[1]+=2*r;
    ans+=l+r;
    if(a[0]==a[1]&&a[0]==a[2]){
        cout<<ans<<endl;
    }else if(a[0]==a[1]&&a[0]!=a[2]){
        cout<<ans+2<<endl;
    }else if(a[0]!=a[1]&&a[1]==a[2]){
        cout<<ans+1<<endl;
    }else if(a[0]!=a[1]&&a[0]==a[2]){
        cout<<ans+2<<endl;
    }else{
        cerr<<'?'<<endl;
    }
    return 0;
}

Score : 300 points

Problem Statement

You are given three integers A, B and C. Find the minimum number of operations required to make A, B and C all equal by repeatedly performing the following two kinds of operations in any order:

Choose two among A, B and C, then increase both by 1.

Choose one among A, B and C, then increase it by 2.

It can be proved that we can always make A, B and C all equal by repeatedly performing these operations.

Constraints

0 \leq A,B,C \leq 50

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the minimum number of operations required to make A, B and C all equal.

Sample Input 1

2 5 4

Sample Output 1

2

We can make A, B and C all equal by the following operations:

Increase A and C by 1. Now, A, B, C are 3, 5, 5, respectively.

Increase A by 2. Now, A, B, C are 5, 5, 5, respectively.

Sample Input 2

2 6 3

Sample Output 2

5

Sample Input 3

31 41 5

Sample Output 3

23


#include <stdio.h>
int main (void){
  int a,b,c,i,j,count;
  scanf("%d %d %d",&a,&b,&c);
  count = 0;
  if (a == b && b == c)
    printf("%d\n",count);
  if (a > b && b > c){
    for (i = 0; i < a - b; i++)
      count++;
  }
  else if (a > b && a > c && c > b){
    j = a - c;
    for (i = 0; i < j; i++){
      count++;
      c++;
      b++;
    }
  }
  else if (b > c && c > a){
    j = b - c;
    for (i = 0; i < j; i++){
      count++;
      c++;
      a++;
    }
  }
  else if (b > c && b > a && a > c){
    j = b - a;
    for (i = 0; i < j; i++){
      count++;
      a++;
      c++;
    }
  }
  else if (c > a && a > b){
    j = c - a;
    for (i = 0; i < j; i++){
      count++;
      a++;
      b++;
    }
  }
  else if (c > a && c > b && b > a){
    j = c - b;
    for (i = 0; i < j; i++){
      count++;
      b++;
      a++;
    }
  }
  if (a == b && b > c){
    j = b - c;
    for (i = 0; i < j; i++){
      count++;
      c += 2;
      if (b == c){
	printf("%d\n",count);
	break;
      }
      else if (b < c){
	count++;
	printf("%d\n",count);
	break;
      }
    }
  }
  else if (a == b && b < c){
    for (i = 0; i < c - b; i++){
      count++;
      printf("%d\n",count);
    }
  }
  else if (b == c && a < b){
    j = b - a;
    for (i = 0; i < j; i++){
      count++;
      a += 2;
      if (a == b){
	printf("%d\n",count);
	break;
      }
      else if (a > b){
	count++;
	printf("%d\n",count);
	break;
      }
    }
  }
  else if (b == c && a > b){
    for (i = 0; i < b - a; i++){
      count++;
      printf("%d\n",count);
      break;
    }
  }
  else if (a == c && c > b){
    j = b - c;
    for (i = 0; i < j; i++){
      count++;
      b += 2;
      if (c == b){
	printf("%d\n",count);
	break;
      }
      else if (c < b){
	count++;
	printf("%d\n",count);
	break;
      }
    }
  }
  else if (a == c && b > c){
    for (i = 0; i < b - c; i++){
      count++;
      printf("%d\n",count);
      break;
    }
  }
  return (0);
}


#include <iostream>
#include <vector>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <cstdio>
#include <bitset>
#include <queue>
#include <deque>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <functional>
#include <stack>
#include <cmath>
#include <string>

using namespace std;

#define REP(i, N) for (int i = 0; i < (int)N; i++)
#define FOR(i, a, b) for (int i = a; i < (int)b; i++)
#define ALL(x) (x).begin(), (x).end()
#define INF (1 << 30)
#define LLINF (1LL << 62)
#define DEBUG(...) debug(__LINE__, ":" __VA_ARGS__)

constexpr int MOD = 1000000007;
using ll = long long;
using Pii = pair<int, int>;
using Pll = pair<ll, ll>;

inline int popcount(ll x) { return __builtin_popcountll(x); }
inline int div2num(ll x) { return __builtin_ctzll(x); }
inline bool bit(ll x, int b) { return (x >> b) & 1; }

template <class T>
string to_string(T s);
template <class S, class T>
string to_string(pair<S, T> p);
string to_string(string s) { return s; }
string to_string(const char s[]) { return to_string(string(s)); }

template <class T>
string to_string(T v) {
  if (v.empty()) return "{}";
  string ret = "{";
  for (auto x : v) ret += to_string(x) + ",";
  ret.back() = '}';
  return ret;
}

template <class S, class T>
string to_string(pair<S, T> p) {
  return "{" + to_string(p.first) + ":" + to_string(p.second) + "}";
}
void debug() { cerr << endl; }

template <class Head, class... Tail>
void debug(Head head, Tail... tail) {
  cerr << to_string(head) << " ";
  debug(tail...);
}

struct IO {
#ifdef _WIN32
  inline char getchar_unlocked() { return getchar(); }
  inline void putchar_unlocked(char c) { putchar(c); }
#endif
  std::string separator = " ";
  template <class T>
  inline void read(T &x) {
    char c;
    do {
      c = getchar_unlocked();
    } while (c != '-' && (c < '0' || '9' < c));
    bool minus = 0;
    if (c == '-') {
      minus = 1;
      c = getchar_unlocked();
    }
    x = 0;
    while ('0' <= c && c <= '9') {
      x *= 10;
      x += c - '0';
      c = getchar_unlocked();
    }
    if (minus) x = -x;
  }
  inline void read(std::string &x) {
    char c;
    do {
      c = getchar_unlocked();
    } while (c == ' ' || c == '\n');
    x.clear();
    do {
      x += c;
      c = getchar_unlocked();
    } while (c != ' ' && c != '\n' && c != EOF);
  }
  template <class T>
  inline void read(std::vector<T> &v) {
    for (auto &x : v) read(x);
  }
  template <class S, class T>
  inline void read(std::pair<S, T> &p) {
    read(p.first);
    read(p.second);
  }
  template <class Head, class... Tail>
  inline void read(Head &head, Tail &... tail) {
    read(head);
    read(tail...);
  }
  template <class T>
  inline void write(T x) {
    char buf[32];
    int p = 0;
    if (x < 0) {
      x = -x;
      putchar_unlocked('-');
    }
    if (x == 0) putchar_unlocked('0');
    while (x > 0) {
      buf[p++] = (x % 10) + '0';
      x /= 10;
    }
    while (p) {
      putchar_unlocked(buf[--p]);
    }
  }
  inline void write(std::string x) {
    for (char c : x) putchar_unlocked(c);
  }
  inline void write(const char s[]) {
    for (int i = 0; s[i] != 0; ++i) putchar_unlocked(s[i]);
  }
  template <class T>
  inline void write(std::vector<T> v) {
    if (v.empty()) return;
    for (auto itr = v.begin(); itr + 1 != v.end(); ++itr) {
      write(*itr);
      write(separator);
    }
    write(v.back());
  }
  template <class Head, class... Tail>
  inline void write(Head head, Tail... tail) {
    write(head);
    write(separator);
    write(tail...);
  }
  template <class Head, class... Tail>
  inline void writeln(Head head, Tail... tail) {
    write(head, tail...);
    write("\n");
  }
  void set_separator(std::string s) { separator = s; }
} io;

struct Prime {
  int n;
  vector<int> table;
  vector<int> primes;
  Prime(int _n = 100000) {
    n = _n + 1;
    table.resize(n, -1);
    table[0] = 0;
    table[1] = -1;
    for (int i = 2; i * i < n; ++i) {
      if (table[i] == -1) {
        for (int j = i * i; j < n; j += i) {
          table[j] = i;
        }
      }
    }
  }
  void enumerate_primes() {
    primes.clear();
    for (int i = 2; i < n; ++i) {
      if (table[i] == -1) primes.push_back(i);
    }
  }
  vector<pair<long long, int>> prime_factor(long long x) {
    map<long long, int> mp;
    long long div = 2;
    int p = 0;
    while (n <= x && div * div <= x) {
      if (x % div == 0) {
        mp[div]++;
        x /= div;
      } else {
        if (p + 1 < primes.size()) {
          div = primes[++p];
        } else {
          div++;
        }
      }
    }
    if (x < n) {
      while (table[x] != -1) {
        mp[table[x]]++;
        x /= table[x];
      }
    }
    if (x > 1) mp[x]++;
    vector<pair<long long, int>> ret;
    for (auto p : mp) ret.push_back(p);
    return ret;
  }
};

template <int MOD = 1000000007>
struct Math {
  vector<long long> fact, factinv, inv;
  Math(int n = 100000) {
    fact.resize(n + 1);
    factinv.resize(n + 1);
    inv.resize(n + 1);
    fact[0] = fact[1] = 1;
    factinv[0] = factinv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i <= n; ++i) {
      fact[i] = fact[i - 1] * i % MOD;
      inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;
      factinv[i] = factinv[i - 1] * inv[i] % MOD;
    }
  }
  long long C(int n, int r) {
    if (n < r || n < 0 || r < 0) {
      return 0;
    } else {
      return fact[n] * (factinv[r] * factinv[n - r] % MOD) % MOD;
    }
  }
  long long P(int n, int r) {
    if (n < r || n < 0 || r < 0) {
      return 0;
    } else {
      return fact[n] * factinv[n - r] % MOD;
    }
  }
  long long H(int n, int r) { return C(n + r - 1, r); }
};

struct UnionFind {
  vector<int> data;
  vector<vector<int>> groups;
  UnionFind(int n) : data(n, -1) {}
  int root(int v) { return data[v] < 0 ? v : data[v] = root(data[v]); }
  bool unite(int u, int v) {
    if ((u = root(u)) == (v = root(v))) {
      return 1;
    } else {
      if (-data[u] < -data[v]) swap(u, v);
      data[u] += data[v];
      data[v] = u;
      return 0;
    }
  }
  int size(int v) { return -data[root(v)]; }
  void make_groups() {
    map<int, vector<int>> mp;
    for (int i = 0; i < data.size(); ++i) mp[root(i)].push_back(i);
    groups.clear();
    for (auto p : mp) groups.push_back(p.second);
  }
};

namespace phc {
long long modpow(long long a, long long n) {
  long long res = 1;
  while (n > 0) {
    if (n & 1) res = res * a % MOD;
    a = a * a % MOD;
    n >>= 1;
  }
  return res;
}
long long modinv(long long a) {
  long long b = MOD, u = 1, v = 0;
  while (b) {
    long long t = a / b;
    a -= t * b;
    swap(a, b);
    u -= t * v;
    swap(u, v);
  }
  u %= MOD;
  if (u < 0) u += MOD;
  return u;
}
long long gcd(long long a, long long b) { return b != 0 ? gcd(b, a % b) : a; }
long long lcm(long long a, long long b) { return a * b / gcd(a, b); }
}  // namespace phc

template <int mod>
struct ModInt {
  int x;

  ModInt() : x(0) {}

  ModInt(int64_t y) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}

  ModInt &operator+=(const ModInt &p) {
    if ((x += p.x) >= mod) x -= mod;
    return *this;
  }

  ModInt &operator-=(const ModInt &p) {
    if ((x += mod - p.x) >= mod) x -= mod;
    return *this;
  }

  ModInt &operator*=(const ModInt &p) {
    x = (int)(1LL * x * p.x % mod);
    return *this;
  }

  ModInt &operator/=(const ModInt &p) {
    *this *= p.inverse();
    return *this;
  }

  ModInt operator-() const { return ModInt(-x); }

  ModInt operator+(const ModInt &p) const { return ModInt(*this) += p; }

  ModInt operator-(const ModInt &p) const { return ModInt(*this) -= p; }

  ModInt operator*(const ModInt &p) const { return ModInt(*this) *= p; }

  ModInt operator/(const ModInt &p) const { return ModInt(*this) /= p; }

  bool operator==(const ModInt &p) const { return x == p.x; }

  bool operator!=(const ModInt &p) const { return x != p.x; }

  ModInt inverse() const {
    int a = x, b = mod, u = 1, v = 0, t;
    while (b > 0) {
      t = a / b;
      swap(a -= t * b, b);
      swap(u -= t * v, v);
    }
    return ModInt(u);
  }

  ModInt pow(int64_t n) const {
    ModInt ret(1), mul(x);
    while (n > 0) {
      if (n & 1) ret *= mul;
      mul *= mul;
      n >>= 1;
    }
    return ret;
  }

  friend ostream &operator<<(ostream &os, const ModInt &p) { return os << p.x; }

  friend istream &operator>>(istream &is, ModInt &a) {
    int64_t t;
    is >> t;
    a = ModInt<mod>(t);
    return (is);
  }

  static int get_mod() { return mod; }
};

using modint = ModInt<MOD>;

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

int main() {
  int Q;
  io.read(Q);
  while (Q--) {
    ll A, B;
    io.read(A, B);
    if (A > B) swap(A, B);
    ll ans = A - 1;
    ll sq = sqrtl(A * B + 1);
    ans += sq - (sq * sq == A * B);
    ans += max(0LL, (A * B / sq) - A - 1 - ((A * B) % sq == 0 ? 1 : 0));
    io.writeln(ans);
  }
  return 0;
}

Score : 700 points

Problem Statement

10^{10^{10}} participants, including Takahashi, competed in two programming contests.
In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th.

The score of a participant is the product of his/her ranks in the two contests.

Process the following Q queries:

In the i-th query, you are given two positive integers A_i and B_i. Assuming that Takahashi was ranked A_i-th in the first contest and B_i-th in the second contest, find the maximum possible number of participants whose scores are smaller than Takahashi's.

Constraints

1 \leq Q \leq 100

1\leq A_i,B_i\leq 10^9(1\leq i\leq Q)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

Q
A_1 B_1
:
A_Q B_Q

Output

For each query, print the maximum possible number of participants whose scores are smaller than Takahashi's.

Sample Input 1

8
1 4
10 5
3 3
4 11
8 9
22 40
8 36
314159265 358979323

Sample Output 1

1
12
4
11
14
57
31
671644785

Let us denote a participant who was ranked x-th in the first contest and y-th in the second contest as (x,y).

In the first query, (2,1) is a possible candidate of a participant whose score is smaller than Takahashi's. There are never two or more participants whose scores are smaller than Takahashi's, so we should print 1.


#include <bits/stdc++.h>
#define mod 1000000007
#define pb push_back
#define ll long long
#define mp make_pair
using namespace std;
int main(){
	ll q;
	cin>>q;
	for(int i=0;i<q;i++){
		ll a,b;
		cin>>a>>b;
		if(a==b){
			cout<<a+b-2<<endl;
		}
		else{
			if(a>b){
				ll x = a;
				a = b;
				b = x;
			}
			if(b-a==1){
				cout<<a+b-2<<endl;
			}
			double tag = (a*b-1.0)*4.0;
			tag = sqrt(tag);
			ll itag = (ll)floor(tag);
			cout<<itag-2<<endl;
		}
	}
	return 0;
}


#include "bits/stdc++.h"
using namespace std;
#define fi first
#define se second
#define ll long long
#define dbg(v) cerr<<#v<<" = "<<v<<'\n'
#define vi vector<int>
#define vl vector <ll>
#define pii pair<int,int>
#define mp make_pair
#define db long double
#define pb push_back
#define all(s) s.begin(),s.end()
template < class T > T smin(T &a,T b) {if (a > b) a = b;return a;}
template < class T > T smax(T &a,T b) {if (a < b) a = b;return a;}
int main(void)
{
    int q;
    cin>>q;
    while (q --) {
    	ll a,b;
    	cin>>a>>b;
    	ll n = a * b;
    	ll sq = sqrt(n - 1);
    	while (sq * sq <= n - 1) ++sq;
    	ll ans = sq + (n - 1) / (sq + 1);
    	--ans;
    	cout << ans << '\n';
    }
    return 0;
}


#include <iostream>
#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
ll graph[55][55][55];

int main()
{
    ll N;
    cin>>N;
    ll a[N],b[N];
    vector<ll> c[N];
    for(ll i=0; i<N; i++){
        cin>>a[i];
        c[i].push_back(a[i]);
    }
    for(ll i=0; i<N; i++){
        cin>>b[i];
    }

    for(ll i=0; i<55; i++){
        for(ll j=0; j<55; j++){
            graph[i][i][j] = 1;
        }
    }

    for(ll k=1; k<55; k++){
        for(ll i=0; i<55; i++){
            for(ll j=0; j<55; j++){
                if(graph[i%k][j][k-1]==1 || graph[i][j][k-1]==1)
                    graph[i][j][k] = 1;
            }
        }
    }

    for(ll i=0; i<N; i++){
        if(graph[a[i]][b[i]][50]==0){
            cout<<-1<<endl;
            return 0;
        }
    }

    ll ans = 0;
    for(ll k=50; k>0; k--){
        bool check = true;
        for(ll i=0; i<N; i++){
            bool test = false;
            for(ll j=0; j<c[i].size(); j++){
                if(graph[c[i][j]][b[i]][k-1]==1){
                    test = true;
                }
            }
            if(!test)
                check = false;

        }
        if(!check){
            ans+= (1ll<<k);
            for(ll i=0; i<N; i++){
                vector<ll> carry;
                ll poss[55];
                for(ll j=0; j<55; j++)
                    poss[j] = 0;
                for(ll j=0; j<c[i].size(); j++){
                    poss[c[i][j]] = 1;
                    poss[c[i][j]%k] = 1;
                }
                for(ll j=0; j<55; j++){
                    if(poss[j]==1)
                        carry.push_back(j);
                }
                c[i] = carry;
            }

        }

    }
    cout<<ans<<endl;

    return 0;
}

Score : 700 points

Problem Statement

Aoki is playing with a sequence of numbers a_{1}, a_{2}, ..., a_{N}. Every second, he performs the following operation :

Choose a positive integer k. For each element of the sequence v, Aoki may choose to replace v with its remainder when divided by k, or do nothing with v. The cost of this operation is 2^{k} (regardless of how many elements he changes).

Aoki wants to turn the sequence into b_{1}, b_{2}, ..., b_{N} (the order of the elements is important). Determine if it is possible for Aoki to perform this task and if yes, find the minimum cost required.

Constraints

1 \leq N \leq 50

0 \leq a_{i}, b_{i} \leq 50

All values in the input are integers.

Input

Input is given from Standard Input in the following format:

N
a_{1} a_{2} ... a_{N}
b_{1} b_{2} ... b_{N}

Output

Print the minimum cost required to turn the original sequence into b_{1}, b_{2}, ..., b_{N}. If the task is impossible, output -1 instead.

Sample Input 1

3
19 10 14
0 3 4

Sample Output 1

160

Here's a possible sequence of operations :

Choose k = 7. Replace 19 with 5, 10 with 3 and do nothing to 14. The sequence is now 5, 3, 14.

Choose k = 5. Replace 5 with 0, do nothing to 3 and replace 14 with 4. The sequence is now 0, 3, 4.

The total cost is 2^{7} + 2^{5} = 160.

Sample Input 2

3
19 15 14
0 0 0

Sample Output 2

2

Aoki can just choose k = 1 and turn everything into 0. The cost is 2^{1} = 2.

Sample Input 3

2
8 13
5 13

Sample Output 3

-1

The task is impossible because we can never turn 8 into 5 using the given operation.

Sample Input 4

4
2 0 1 8
2 0 1 8

Sample Output 4

0

Aoki doesn't need to do anything here. The cost is 0.

Sample Input 5

1
50
13

Sample Output 5

137438953472

Beware of overflow issues.


#include<iostream>
using namespace std;
int main(){
	int a,b,c,d;
	cin>>a>>b>>c>>d;
	if(a>b&&c>d){
		cout<<b+d<<endl;
	}
	else if(a<=b&&c>=d){
		cout<<a+d<<endl;
	}
	else if(a>=b&&c<=d){
		cout<<b+c<<endl;
	}
	else{
		cout<<a+c<<endl;
	}
	return 0;
}

Score : 100 points

Problem Statement

You planned a trip using trains and buses.
The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket.
Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.

Find the minimum total fare when the optimal choices are made for trains and buses.

Constraints

1 \leq A \leq 1 000

1 \leq B \leq 1 000

1 \leq C \leq 1 000

1 \leq D \leq 1 000

All input values are integers.

Input

Input is given from Standard Input in the following format:

A
B
C
D

Output

Print the minimum total fare.

Sample Input 1

600
300
220
420

Sample Output 1

520

The train fare will be 600 yen if you buy ordinary tickets, and 300 yen if you buy an unlimited ticket.
Thus, the optimal choice for trains is to buy an unlimited ticket for 300 yen.
On the other hand, the optimal choice for buses is to buy ordinary tickets for 220 yen.

Therefore, the minimum total fare is 300 + 220 = 520 yen.

Sample Input 2

555
555
400
200

Sample Output 2

755

Sample Input 3

549
817
715
603

Sample Output 3

1152