#include <algorithm>
#include <climits>
#include <cmath>
#include <deque>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <regex>
#include <unordered_map>
#include <vector>

const int mod = 1e9 + 7;
const int kmax = 510000;
const int last_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

long long fact[kmax], fact_inv[kmax], inv[kmax];

void init_comb()
{
    fact[0] = fact[1] = 1;
    fact_inv[0] = fact_inv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < kmax; i++) {
        fact[i] = fact[i - 1] * i % mod;
        inv[i] = mod - inv[mod % i] * (mod / i) % mod;
        fact_inv[i] = fact_inv[i - 1] * inv[i] % mod;
    }
}

long long comb(int n, int r)
{
    if (n < r) {
        return 0;
    }

    if (n < 0 || r < 0) {
        return 0;
    }

    return fact[n] * (fact_inv[r] * fact_inv[n - r] % mod) % mod;
}

template <typename T, T N>
class UnionFind {
    T parent_[N];
    T rank_[N];
    T size_[N];

public:
    UnionFind();
    T Root(T idx);
    bool IsSame(T x, T y);
    void Unite(T x, T y);
    T GetSize(T idx);
};

template <typename T, T N>
UnionFind<T, N>::UnionFind()
{
    for (T i = 0; i < N; i++) {
        parent_[i] = i;
        rank_[i] = 0;
        size_[i] = 1;
    }
}

template <typename T, T N>
T UnionFind<T, N>::Root(T idx)
{
    return parent_[idx] == idx ? idx : parent_[idx] = Root(parent_[idx]);
}

template <typename T, T N>
bool UnionFind<T, N>::IsSame(T x, T y)
{
    return Root(x) == Root(y);
}

template <typename T, T N>
void UnionFind<T, N>::Unite(T x, T y)
{
    x = Root(x);
    y = Root(y);
    if (x == y) {
        return;
    }

    if (rank_[x] < rank_[y]) {
        parent_[x] = y;
        size_[y] += size_[x];
    } else {
        parent_[y] = x;
        size_[x] += size_[y];
        if (rank_[x] == rank_[y]) {
            rank_[x]++;
        }
    }
}

template <typename T, T N>
T UnionFind<T, N>::GetSize(T idx)
{
    return size_[Root(idx)];
}

long long pow_mod(long long n, long long p, long long m)
{
    if (p == 0) {
        return 1;
    }

    if (p % 2 == 0) {
        long long t = pow_mod(n, p / 2, m);
        return t * t % m;
    }
    return n * pow_mod(n, p - 1, m) % mod;
}

long long nCr_mod(long long n, long long r)
{
    long long x = 1;
    for (long long i = n - r + 1; i <= n; i++) {
        x *= i;
        x %= mod;
    }

    long long a = 1;
    for (long long i = 1; i <= r; i++) {
        a *= i;
        a %= mod;
    }

    long long y = pow_mod(a, mod - 2, mod) % mod;

    return x * y % mod;
}

bool is_prime(long long n)
{
    if (n == 1) {
        return false;
    }

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

    return true;
}

bool is_leap(long long y)
{
    return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
}

void next_day(long long& y, long long& m, long long& d)
{
    d++;

    if (d > last_days[m - 1] + (m == 2 && is_leap(y) ? 1 : 0)) {
        d = 1;
        m++;
    }

    if (m > 12) {
        y++;
        m = 1;
    }
}

long long fib(long long n)
{
    long long a = 0, b = 1;
    for (int i = 0; i < n; i++) {
        long long t = a;
        a = b;
        b = a + t;
    }

    return a;
}

std::vector<size_t> argsort(const std::vector<long long>& v)
{
    std::vector<size_t> indices(v.size());
    std::iota(indices.begin(), indices.end(), 0);

    std::sort(indices.begin(), indices.end(), [&v](size_t i, size_t j) { return v[i] < v[j]; });

    for (auto i = 0LU; i < indices.size(); i++) {
        indices[i]++;
    }

    return indices;
}

int main()
{
    long long n, m;
    std::cin >> n >> m;

    std::vector<long long> p(m), y(m);

    for (int i = 0; i < m; i++) {
        std::cin >> p[i] >> y[i];
        p[i]--;
    }

    std::vector<std::vector<long long>> nums(n);

    for (int i = 0; i < m; i++) {
        nums[p[i]].push_back(y[i]);
    }

    for (int i = 0; i < n; i++) {
        std::reverse(nums[i].begin(), nums[i].end());
    }

    std::vector<std::vector<size_t>> args(n);
    for (int i = 0; i < n; i++) {
        args[i] = argsort(nums[i]);
        std::reverse(args[i].begin(), args[i].end());
    }

    std::vector<long long> indexes(n, 0);
    for (int i = 0; i < m; i++) {
        printf("%06Ld%06ld\n", p[i] + 1, args[p[i]][indexes[p[i]]++]);
    }
}


#include <bits/stdc++.h>
#define int long long
#define mod (int)(1e9+7)
#define inf (int)(3e18+7)
#define rep(i,n) for(int i=0;i<n;i++)
#define REP(i,n) for(int i=1;i<n;i++)
#define P pair<int,int>
#define all(v) v.begin(),v.end()
#define mkp make_pair
#define mkt make_tuple
#define prique(T) priority_queue<T,vector<T>,greater<T>>
#define vecunique(vec) sort(vec.begin(), vec.end());decltype(vec)::iterator result = std::unique(vec.begin(), vec.end());vec.erase(result, vec.end())
using namespace std;

bool prime(int x) {
	for (int i = 2; i * i <= x; i++) {
		if (x % i == 0)return false;
	}
	return x > 1;
}
int gcd(int x, int y) {
	if (y == 0)return x;
	return gcd(y, x % y);
}
int lcm(int x, int y) {
	return x * y / gcd(x, y);
}
int kai(int x) {
	if (x == 0)return 1;
	return kai(x - 1) * x % mod;
}
int mod_pow(int x, int y, int mod_) {
	int res = 1;
	while (y > 0) {
		if (y & 1) {
			res = res * x % mod_;
		}
		x = x * x % mod_;
		y >>= 1;
	}
	return res;
}
int comb(int x, int y) {
	return kai(x)* mod_pow(kai(x - y), mod - 2, mod) % mod * mod_pow(kai(y), mod - 2, mod) % mod;
}
/*--------Library Zone!--------*/

int h, w, k;
int dp[114][19];
signed main() {
	cin >> h >> w >> k;
	dp[0][0] = 1;
	rep(i, h) {
		rep(j, w) {
			dp[i][j] %= mod;
			rep(k, 1 << (w - 1)) {
				rep(l, w - 2) {
					if ((k >> l) & 1 && (k >> (l + 1) & 1))goto ng;
				}
				if (j && (k >> (j - 1)) & 1)dp[i + 1][j - 1] += dp[i][j];
				else if ((k >> j) & 1)dp[i + 1][j + 1] += dp[i][j];
				else dp[i + 1][j] += dp[i][j];
			ng:;
			}
		}
	}
	cout << dp[h][k - 1] % mod << endl;
}

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

Score: 400 points

Problem Statement

Amidakuji is a traditional method of lottery in Japan.

To make an amidakuji, we first draw W parallel vertical lines, and then draw horizontal lines that connect them. The length of each vertical line is H+1 [cm], and the endpoints of the horizontal lines must be at 1, 2, 3, ..., or H [cm] from the top of a vertical line.

A valid amidakuji is an amidakuji that satisfies the following conditions:

No two horizontal lines share an endpoint.

The two endpoints of each horizontal lines must be at the same height.

A horizontal line must connect adjacent vertical lines.

Find the number of the valid amidakuji that satisfy the following condition, modulo 1\ 000\ 000\ 007: if we trace the path from the top of the leftmost vertical line to the bottom, always following horizontal lines when we encounter them, we reach the bottom of the K-th vertical line from the left.

For example, in the following amidakuji, we will reach the bottom of the fourth vertical line from the left.

Constraints

H is an integer between 1 and 100 (inclusive).

W is an integer between 1 and 8 (inclusive).

K is an integer between 1 and W (inclusive).

Input

Input is given from Standard Input in the following format:

H W K

Output

Print the number of the amidakuji that satisfy the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

1 3 2

Sample Output 1

1

Only the following one amidakuji satisfies the condition:

Sample Input 2

1 3 1

Sample Output 2

2

Only the following two amidakuji satisfy the condition:

Sample Input 3

2 3 3

Sample Output 3

1

Only the following one amidakuji satisfies the condition:

Sample Input 4

2 3 1

Sample Output 4

5

Only the following five amidakuji satisfy the condition:

Sample Input 5

7 1 1

Sample Output 5

1

As there is only one vertical line, we cannot draw any horizontal lines. Thus, there is only one amidakuji that satisfies the condition: the amidakuji with no horizontal lines.

Sample Input 6

15 8 5

Sample Output 6

437760187

Be sure to print the answer modulo 1\ 000\ 000\ 007.

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<iostream>
#include<iomanip>
#include<cstdio>
#include<string>
#include<cstring>
#include<climits>
#include<algorithm>
#include<vector>
#include<cmath>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<deque>
#include<tuple>
#include<list>
#include<unordered_map>
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define vii vector<int>
#define vll vector<ll>
#define lb lower_bound
#define pb push_back
#define mp make_pair
#define rep(i,n) for(ll i=0;i<n;i++)
#define rep2(i,a,b) for(ll i=a;i<b;i++)
#define repr(i,n) for(ll i=n-1;i>=0;i--)
#define all(x) x.begin(),x.end()
#define INF (1 << 30) - 1
#define LLINF (1LL << 61) - 1
// #define int ll
using namespace std;
const int MOD = 1000000007;
const int MAX = 510000;

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    ll n,a[100010],ans=0;
    deque<ll> deq;
    cin>>n;
    rep(i,n){
        cin>>a[i];
    }
    sort(a,a+n);
    rep(i,n-1){
        if(i%4==0){
            deq.push_back(a[n-(i/2+1)]);
        }
        else if(i%4==1){
            deq.push_front(a[i/2]);
        }
        else if(i%4==2){
            deq.push_back(a[i/2]);
        }
        else{
            deq.push_front(a[n-(i/2+1)]);
        }
    }
    rep(i,n-2){
        ans+=abs(deq.at(i)-deq.at(i+1));
    }
    ans+=max(abs(deq.at(0)-a[n/2-(1-n%2)]),abs(deq.at(n-2)-a[n/2-(1-n%2)]));
    cout<<ans<<endl;
    return 0;
}

Score : 400 points

Problem Statement

You are given N integers; the i-th of them is A_i.
Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like.

Constraints

2 \leq N \leq 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_N

Output

Print the maximum possible sum of the absolute differences between the adjacent elements after arranging the given integers in a row in any order you like.

Sample Input 1

5
6
8
1
2
3

Sample Output 1

21

When the integers are arranged as 3,8,1,6,2, the sum of the absolute differences between the adjacent elements is |3 - 8| + |8 - 1| + |1 - 6| + |6 - 2| = 21. This is the maximum possible sum.

Sample Input 2

6
3
1
4
1
5
9

Sample Output 2

25

Sample Input 3

3
5
5
1

Sample Output 3

8


#include <bits/stdc++.h>
#define rep(i, a, b) for(int i = int(a); i < int(b); i++)
#define rer(i, a, b) for(int i = int(a) - 1; i >= int(b); i--)
#define sz(v) (int)(v).size()
#define pb push_back
#define sc second
#define fr first
#define sor(v) sort(v.begin(),v.end())
#define rev(s) reverse(s.begin(),s.end())
#define lb(vec,a) lower_bound(vec.begin(),vec.end(),a)
#define ub(vec,a) upper_bound(vec.begin(),vec.end(),a)
#define uniq(vec) vec.erase(unique(vec.begin(),vec.end()),vec.end())
using namespace std;
typedef long long int ll;
typedef pair <int, int> P;

const ll MOD=1000000007;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    ll N;
    cin>>N;
    vector<ll> A;
    rep(i,0,N){
        ll a;
        cin>>a;
        A.pb(a);
    }
    sor(A);
    ll res1=0,res2=0;
    if(N%2){
        rep(i,N/2+1,N){
            res1+=2*A[i];
        }
        rep(i,0,N/2-1){
            res1-=2*A[i];
        }
        res1-=A[N/2-1]+A[N/2];
        rep(i,0,N/2){
            res2-=2*A[i];
        }
        rep(i,N/2,N){
            res2+=2*A[i];
        }
        res2-=A[N/2]+A[N/2+1];
    }
    else{
        rep(i,N/2,N){
            res1+=2*A[i];
        }
        rep(i,0,N/2){
            res1-=2*A[i];
        }
        res1+=-A[N/2]+A[N/2-1];
    }
    cout <<max(res1,res2)<<"\n";
}


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

struct node
{
	 int c;
	 int num;

};
struct node a[100005],b[100005];

bool cmp(node a,node b)
{
	 return a.c>b.c;
}
int main()
{for(int i=0;i<100005;i++)
{
	a[i].c=0;
	a[i].num=i;
	b[i].c=0;
	b[i].num=i;
}
	 int n;
	 cin>>n;
	  int jd=0,od=0,jx=1000000000,ox=1000000000;
	 vector<int>j,o;
	 int jmax=0,jmaxn=0,omax=0,omaxn=0;
	 for(int i=1;i<=n;i++)
	 {int t;
	 cin>>t;

	 	if(i&1)
	 	{
	 	    j.push_back(t);
	 	    jd=max(jd,t);
	 	    jx=min(jx,t);
	 	    a[t].c++;

	 	    if(a[t].c>jmax)
	 	    {
	 	    	jmax=a[t].c;
	 	    	jmaxn=t;
			 }
		 }
		 else
		 {
		 	o.push_back(t);
		 	od=max(od,t);
		 	ox=min(ox,t);
		 	b[t].c++;
		 	if(b[t].c>omax)
	 	    {
	 	    	omax=b[t].c;
	 	    	omaxn=t;
			 }
		 }

	 }
	 if(jd==od&&jx==ox&&jd==jx)
	    {
	    	cout<<j.size()<<endl;
	    	return 0;
		}
	 sort(a,a+100005,cmp);
	 	 sort(b,b+100005,cmp);

	/* jd=max_element(j.begin(),j.end());
	  od=max_element(o.begin(),o.end());
	   jx=min_element(j.begin(),j.end());
	    ox=min_element(o.begin(),o.end());*/

	    int jc=0,oc=0;
	    if(jmaxn==omaxn)
	    {
	    	jmaxn=a[1].num;
		}
	    for(int i=0;i<j.size();i++)
	    {
	    	if(jmaxn!=j[i])
	    	{
	    		jc++;
	    		j[i]=jmaxn;
			}
		}

		  for(int i=0;i<o.size();i++)
	    {
	    	if(omaxn!=o[i])
	    	{
	    		oc++;
	    		o[i]=omaxn;
			}
		}
		cout<<jc+oc<<endl;
}

Score : 200 points

Problem Statement

Kurohashi has never participated in AtCoder Beginner Contest (ABC).

The next ABC to be held is ABC N (the N-th ABC ever held).
Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.

What is the earliest ABC where Kurohashi can make his debut?

Constraints

100 \leq N \leq 999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If the earliest ABC where Kurohashi can make his debut is ABC n, print n.

Sample Input 1

111

Sample Output 1

111

The next ABC to be held is ABC 111, where Kurohashi can make his debut.

Sample Input 2

112

Sample Output 2

222

The next ABC to be held is ABC 112, which means Kurohashi can no longer participate in ABC 111.
Among the ABCs where Kurohashi can make his debut, the earliest one is ABC 222.

Sample Input 3

750

Sample Output 3

777


//==================== default starts ====================//
#include <bits/stdc++.h>

using namespace std;

#define fread(x)        freopen(x,"r",stdin)
#define fwrite(x)       freopen (x,"w",stdout)

#define min3(a,b,c)     min(a,min(b,c))
#define max3(a,b,c)     max(a,max(b,c))
#define min4(a,b,c,d)   min(a,min(b,min(c,d)))
#define max4(a,b,c,d)   max(a,max(b,max(c,d)))
#define SQR(a)          ((a)*(a))
#define MEMSET(a,x)     memset(a,x,sizeof(a))
#define ABS(x)          ((x)<0?-(x):(x))

#define white           1
#define grey            2
#define black           3

#define ll              long long
#define pb              push_back
#define pf              push_front
#define INF             9e18
#define PI              acos(-1.0)
#define pii             pair<int,int>
#define pll             pair<ll, ll>

#define all(v)          v.begin(), v.end()

#define fastread        ios_base::sync_with_stdio(0);cin.tie(nullptr);
int on(int N,int pos){return N=N | (1<<pos);}
int off(int N,int pos){return N= N & ~(1<<pos);}
bool check(int N,int pos){return (bool)(N & (1<<pos));}
//==================== default ends ====================//
int arr[] = {111,222,333,444,555,666,777,888,999};
int find_num(int n){
	int mid = 9/2, start = 0, ed = 9;
	while(ed-start > 1){
		mid=(start+ed)>>1;
		if(arr[mid] > n){
			ed = mid;
		}else if(arr[mid] < n){
			start = mid;
		}else{
			return arr[mid];
		}
	}
	if(arr[start]==n)return arr[start];
	else return arr[start+1];
}
int main(){
	fastread
	int n;
	cin>>n;
	cout<<find_num(n)<<endl;
}


#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <ctype.h>
#include <map>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <cctype>
#include <queue>
#include <set>
#include <list>
#define PI 3.141592653
#define rep(i,a,n) for(int i=a;i<(int)n;++i)
#define SZ(x) ((int)(x).size())	//size() unsigned -> int
#define DescSort(a) sort(a.begin(),a.end(),std::greater<int>())

using namespace std;
typedef long long ll;
const ll INF=1e9+7;

int main(void) {
	int n;
	vector<int> e(1e5 + 5, 0), o(1e5 + 5, 0);
	cin >> n;
	rep(i, 0, n) {
		int input;
		cin >> input;
		if (i % 2) {
			o[input]++;
		}
		else {
			e[input]++;
		}
	}
	int o_max_idx, e_max_idx;
	o_max_idx = distance(o.begin(), max_element(o.begin(), o.end()));
	e_max_idx = distance(e.begin(), max_element(e.begin(), e.end()));
	int ans = n - o[o_max_idx] - e[e_max_idx];
	if (o_max_idx == e_max_idx){
		int o_max_tmp = o[o_max_idx];
		int e_max_tmp = e[e_max_idx];
		o[o_max_idx] = 0;e[e_max_idx] = 0;
		int o_2_max_idx = distance(o.begin(), max_element(o.begin(), o.end()));
		int e_2_max_idx = distance(e.begin(), max_element(e.begin(), e.end()));
		ans = n - max(e[e_2_max_idx]+o_max_tmp, e_2_max_idx+o[o_max_tmp]);
	}
	cout << ans << endl;

	return 0;
}

Score : 300 points

Problem Statement

A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:

For each i = 1,2,..., n-2, a_i = a_{i+2}.

Exactly two different numbers appear in the sequence.

You are given a sequence v_1,v_2,...,v_n whose length is even.
We would like to make this sequence /\/\/\/ by replacing some of its elements.
Find the minimum number of elements that needs to be replaced.

Constraints

2 \leq n \leq 10^5

n is even.

1 \leq v_i \leq 10^5

v_i is an integer.

Input

Input is given from Standard Input in the following format:

n
v_1 v_2 ... v_n

Output

Print the minimum number of elements that needs to be replaced.

Sample Input 1

4
3 1 3 2

Sample Output 1

1

The sequence 3,1,3,2 is not /\/\/\/, but we can make it /\/\/\/ by replacing one of its elements: for example, replace the fourth element to make it 3,1,3,1.

Sample Input 2

6
105 119 105 119 105 119

Sample Output 2

0

The sequence 105,119,105,119,105,119 is /\/\/\/.

Sample Input 3

4
1 1 1 1

Sample Output 3

2

The elements of the sequence 1,1,1,1 are all the same, so it is not /\/\/\/.


#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <cstring>

using namespace std;
// ascending order
#define vsort(v) sort(v.begin(), v.end())
// descending order
#define vsort_r(v) sort(v.begin(), v.end(), greater<ll>())
#define vunique(v) unique(v.begin(), v.end())
#define mp make_pair
#define ts(x) to_string(x)
#define rep(i, a, b) for(ll i = (ll)a; i < (ll)b; i++)
#define repm(i, a, b) for(ll i = (ll)a; i > (ll)b; i--)
#define bit(a) bitset<8>(a)
#define des_priority_queue priority_queue<ll, vector<ll>, greater<ll> >
#define all(v) (v).begin(), (v).end()
typedef long long ll;
typedef pair<ll, ll> P;
const ll INF = 1e18;

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	ll n;
	cin >> n;
	map<ll, ll> even;
	map<ll, ll> odd;
	vector<ll> tmp_v;
	rep(i, 0, n) {
		ll v;
		cin >> v;
		if(i % 2 == 0) even[v]++;
		else odd[v]++;
		tmp_v.push_back(v);
	}

	ll e1 = -1;
	ll e2 = -1;
	ll max_e1 = -1;
	ll max_e2 = -1;
	ll o1 = -1;
	ll o2 = -1;
	ll max_o1 = -1;
	ll max_o2 = -1;

	for(map<ll, ll>::iterator it = even.begin(); it != even.end(); it++) {
		if(max_e1 < it->second) {
			if(e2 != -1) {
				max_e2 = max_e1;
				e2 = e1;
			}
			e1 = it->first;
			max_e1 = it->second;
			continue;
		}

		if(e2 != it->first and max_e2 < it->second) {
			e2 = it->first;
			max_e2 = it->second;
		}
	}

	for(map<ll, ll>::iterator it = odd.begin(); it != odd.end(); it++) {
		if(max_o1 < it->second) {
			if(o2 != -1) {
				max_o2 = max_o1;
				o2 = o1;
			}
			o1 = it->first;
			max_o1 = it->second;
			continue;
		}

		if(o2 != it->first and max_o2 < it->second) {
			o2 = it->first;
			max_o2 = it->second;
		}
	}

	ll rsl1 = 0;
	ll rsl2 = 0;
	if(e1 != o1) {
		rep(i, 0, n) {
			if(i % 2 == 0) {
				if(e1 != tmp_v[i]) rsl1++;
			} else {
				if(o1 != tmp_v[i]) rsl1++;
			}
		}
		cout << rsl1 << endl;
	} else {
		rep(i, 0, n) {
			if(i % 2 == 0) {
				if(e1 != tmp_v[i]) rsl1++;
			} else {
				if(o2 != tmp_v[i]) rsl1++;
			}
		}
		rep(i, 0, n) {
			if(i % 2 == 0) {
				if(e2 != tmp_v[i]) rsl2++;
			} else {
				if(o1 != tmp_v[i]) rsl2++;
			}
		}
		ll rsl = min(rsl1, rsl2);
		cout << rsl << endl;
	}
}


#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5+10;
int n, a[N], b[N], c[2], d[N];
char s[N];
int Abs(int x){return x > 0 ? x : -x;}
int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d%d", &a[i], &b[i]);
		++c[(a[i] + b[i]) & 1];
    }
    if (c[0] != n && c[1] != n)
    {
    	puts("-1");
		return 0;
    }
    printf("%d\n", 31 + (c[0] != 0));
	for (int i = 0; i <= 30; i++)
		printf("%d ", 1 << i);
	if (c[0])
		printf("1 ");
	putchar(10);
	for (int i = 1; i <= n; i++)
	{
		int x = a[i], y = b[i];
		if (c[0])
			--x, s[31] = 'R';
		int f = 0;
        for (int i = 30; i >= 0; i--)
        {
            if (Abs(x) < Abs(y))
            	swap(x, y), f ^= 1;
			if (x > 0)
				x -= 1 << i, s[i] = "RU"[f];
			else
				x += 1 << i, s[i] = "LD"[f];
		}
		puts(s);
    }
}

Score : 600 points

Problem Statement

Snuke is introducing a robot arm with the following properties to his factory:

The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i.

For each section, its mode can be specified individually. There are four modes: L, R, D and U. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint i will be determined as follows (we denote its coordinates as (x_i, y_i)):

(x_0, y_0) = (0, 0).

If the mode of Section i is L, (x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1}).

If the mode of Section i is R, (x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1}).

If the mode of Section i is D, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i}).

If the mode of Section i is U, (x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i}).

Snuke would like to introduce a robot arm so that the position of Joint m can be matched with all of the N points (X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N) by properly specifying the modes of the sections.
Is this possible?
If so, find such a robot arm and how to bring Joint m to each point (X_j, Y_j).

Constraints

All values in input are integers.

1 \leq N \leq 1000

-10^9 \leq X_i \leq 10^9

-10^9 \leq Y_i \leq 10^9

Partial Score

In the test cases worth 300 points, -10 \leq X_i \leq 10 and -10 \leq Y_i \leq 10 hold.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1
X_2 Y_2
:
X_N Y_N

Output

If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print -1.

m
d_1 d_2 ... d_m
w_1
w_2
:
w_N

m and d_i are the configurations of the robot arm. Refer to the problem statement for what each of them means.
Here, 1 \leq m \leq 40 and 1 \leq d_i \leq 10^{12} must hold. Also, m and d_i must all be integers.

w_j is a string of length m that represents the way to bring Joint m of the robot arm to point (X_j, Y_j).
The i-th character of w_j should be one of the letters L, R, D and U, representing the mode of Section i.

Sample Input 1

3
-1 0
0 3
2 -1

Sample Output 1

2
1 2
RL
UU
DR

In the given way to bring Joint m of the robot arm to each (X_j, Y_j), the positions of the joints will be as follows:

To (X_1, Y_1) = (-1, 0): First, the position of Joint 0 is (x_0, y_0) = (0, 0). As the mode of Section 1 is R, the position of Joint 1 is (x_1, y_1) = (1, 0). Then, as the mode of Section 2 is L, the position of Joint 2 is (x_2, y_2) = (-1, 0).

To (X_2, Y_2) = (0, 3): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, 1), (x_2, y_2) = (0, 3).

To (X_3, Y_3) = (2, -1): (x_0, y_0) = (0, 0), (x_1, y_1) = (0, -1), (x_2, y_2) = (2, -1).

Sample Input 2

5
0 0
1 0
2 0
3 0
4 0

Sample Output 2

-1

Sample Input 3

2
1 1
1 1

Sample Output 3

2
1 1
RU
UR

There may be duplicated points among (X_j, Y_j).

Sample Input 4

3
-7 -3
7 3
-3 -7

Sample Output 4

5
3 1 4 1 5
LRDUL
RDULR
DULRD


#include <bits/stdc++.h>
using namespace std;
char s[200003],s1[200003];
int ss[30],ss1[30];
int main()
{

cin>>s>>s1;
int a,b;a=strlen(s);b=strlen(s1);
 for(int i=1;i<=a;i++)
    ss[s[i]-'a']++,ss1[s1[i]-'a']++;
    for(int i=1;i<=a;i++)
    if(s[i]!=s1[i]&&ss[s[i]-'a']!=ss1[s1[i]-'a']){cout<<"No";return 0;}
    cout<<"Yes";
return 0;
}

Score : 300 points

Problem Statement

You are given strings S and T consisting of lowercase English letters.

You can perform the following operation on S any number of times:

Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.

Determine if S and T can be made equal by performing the operation zero or more times.

Constraints

1 \leq |S| \leq 2 \times 10^5

|S| = |T|

S and T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S and T can be made equal, print Yes; otherwise, print No.

Sample Input 1

azzel
apple

Sample Output 1

Yes

azzel can be changed to apple, as follows:

Choose e as c_1 and l as c_2. azzel becomes azzle.

Choose z as c_1 and p as c_2. azzle becomes apple.

Sample Input 2

chokudai
redcoder

Sample Output 2

No

No sequences of operation can change chokudai to redcoder.

Sample Input 3

abcdefghijklmnopqrstuvwxyz
ibyhqfrekavclxjstdwgpzmonu

Sample Output 3

Yes


#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stdlib.h>
#include <string>
#include <utility>
#include <vector>
#define rep(i, n) for (int i = 0; i < (n); i++)
#define loop(i, x, n) for (int i = (x); i < (n); i++)
#define all(v) (v).begin(), (v).end()
#define int long long
using namespace std;
const int MOD = 1e9 + 7;
const int INF = 1e18;
template<typename T> void cmax(T &a, T b) { a = max(a, b); }
template<typename T> void cmin(T &a, T b) { a = min(a, b); }

int modinv(int a, int m) {
  int b = m, u = 1, v = 0;
  while (b) {
    int t = a / b;
    a -= t * b;
    swap(a, b);
    u -= t * v;
    swap(u, v);
  }
  u %= m;
  if (u < 0) u += m;
  return u;
}

map<int, int> prime_fac(int n) {
  map<int, int> ret;
  for (int i = 2; i * i <= n; i++) {
    while (n % i == 0) {
      ret[i]++;
      n /= i;
    }
  }
  if (n != 1) ret[n] = 1;
  return ret;
}
int fact[200005];
int inv[200005];

signed main() {
  int n, m;
  cin >> n >> m;
  map<int, int> mp = prime_fac(m);
  fact[0] = 1;
  inv[0] = 1;
  loop(i, 1, 200005) {
    fact[i] = fact[i - 1] * i;
    fact[i] %= MOD;
    inv[i] = modinv(fact[i], MOD);
  }

  int ans = 1;
  for (auto x : mp) {
    int t = x.second;
    // cout << x.first << ' ' << t << endl;
    ans *= fact[t + n - 1] * inv[t] % MOD * inv[n - 1] % MOD;
  }
  cout << ans % MOD << endl;
  return 0;
}

Score : 400 points

Problem Statement

You are given positive integers N and M.

How many sequences a of length N consisting of positive integers satisfy a_1 \times a_2 \times ... \times a_N = M? Find the count modulo 10^9+7.

Here, two sequences a' and a'' are considered different when there exists some i such that a_i' \neq a_i''.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of the sequences consisting of positive integers that satisfy the condition, modulo 10^9 + 7.

Sample Input 1

2 6

Sample Output 1

4

Four sequences satisfy the condition: \{a_1, a_2\} = \{1, 6\}, \{2, 3\}, \{3, 2\} and \{6, 1\}.

Sample Input 2

3 12

Sample Output 2

18

Sample Input 3

100000 1000000000

Sample Output 3

957870001


#include <iostream>
int main(){
int N;
int x;
int kids[105];
int order[105];
int all=0;
int flag =0;
std::cin >> N >> x;
for(int i = 0;i <N;i++){
std::cin >> kids[i];
all+=kids[i];

order[i] = kids[i];
if(i != 0){
for(int j = i;j > 0;j--){
if(kids[j] > order[j-1]){
order[j] = order [j-1];
order[j-1] = kids[j];
}
}
}
}
if(all == x){
std::cout << N <<'\n';
flag =1;
}else if (all > x){
std::cout << N-1<<'\n';
flag =1;
}else{
for(int i = 0;i<N;i++){
if(x >= all - order[i]){
std::cout << N -  i - 1 << '\n';
flag =1;
}else{
all -= order[i];
}
}

}
if(!flag)std::cout << 0 << '\n';
  return 0;
}

Score : 200 points

Problem Statement

There are N children, numbered 1, 2, ..., N.

Snuke has decided to distribute x sweets among them.
He needs to give out all the x sweets, but some of the children may get zero sweets.

For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets.
Snuke is trying to maximize the number of happy children by optimally distributing the sweets.
Find the maximum possible number of happy children.

Constraints

All values in input are integers.

2 \leq N \leq 100

1 \leq x \leq 10^9

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the maximum possible number of happy children.

Sample Input 1

3 70
20 30 10

Sample Output 1

2

One optimal way to distribute sweets is (20, 30, 20).

Sample Input 2

3 10
20 30 10

Sample Output 2

1

The optimal way to distribute sweets is (0, 0, 10).

Sample Input 3

4 1111
1 10 100 1000

Sample Output 3

4

The optimal way to distribute sweets is (1, 10, 100, 1000).

Sample Input 4

2 10
20 20

Sample Output 4

0

No children will be happy, no matter how the sweets are distributed.


#include <bits/stdc++.h>
#define rep(i, a, n) for(int i = a; i < n; i++)
#define repr(i, a, b) for(int i = a; i >= b; i--)
#define int long long
#define all(a) a.begin(), a.end()
#define chmax(x, y) x = max(x, y)
#define chmin(x, y) x = min(x, y)
using namespace std;
typedef pair<int, int> P;
const int mod = 1000000007;
const int INF = 1e18;

int n, x;
vector<int> a;
int cost[2010][2010];
int dp[2010];

signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin >> n >> x;
	assert(n <= 2000);
	a.resize(n);
	rep(i, 0, n) cin >> a[i];
	rep(i, 0, n){
		int now = x + a[i], cnt = 0;
		for(int j = i; j >= 0; j--){
			now += x;
			cnt++;
			cost[j][i] = now + (cnt + 1) * (cnt + 1) * a[j];
			if(j) now += (cnt + 1) * (cnt + 1) * (a[j] - a[j - 1]);
		}
	}
	rep(i, 0, n + 1) dp[i] = INF;
	dp[0] = 0;
	rep(i, 0, n){
		rep(j, 0, n){
			dp[j + 1] = min(dp[j + 1], dp[i] + cost[i][j]);
		}
	}
	cout << dp[n] << endl;
}

Score : 700 points

Problem Statement

Snuke has decided to use a robot to clean his room.

There are N pieces of trash on a number line.
The i-th piece from the left is at position x_i.
We would like to put all of them in a trash bin at position 0.

For the positions of the pieces of trash, 0 < x_1 < x_2 < ... < x_{N} \leq 10^{9} holds.

The robot is initially at position 0.
It can freely move left and right along the number line, pick up a piece of trash when it comes to the position of that piece, carry any number of pieces of trash and put them in the trash bin when it comes to position 0. It is not allowed to put pieces of trash anywhere except in the trash bin.

The robot consumes X points of energy when the robot picks up a piece of trash, or put pieces of trash in the trash bin. (Putting any number of pieces of trash in the trash bin consumes X points of energy.)
Also, the robot consumes (k+1)^{2} points of energy to travel by a distance of 1 when the robot is carrying k pieces of trash.

Find the minimum amount of energy required to put all the N pieces of trash in the trash bin.

Constraints

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

0 < x_1 < ... < x_N \leq 10^9

1 \leq X \leq 10^9

All values in input are integers.

Partial Scores

400 points will be awarded for passing the test set satisfying N \leq 2000.

Input

Input is given from Standard Input in the following format:

N X
x_1 x_2 ... x_{N}

Output

Print the answer.

Sample Input 1

2 100
1 10

Sample Output 1

355

Travel to position 10 by consuming 10 points of energy.

Pick up the piece of trash by consuming 100 points of energy.

Travel to position 1 by consuming 36 points of energy.

Pick up the piece of trash by consuming 100 points of energy.

Travel to position 0 by consuming 9 points of energy.

Put the two pieces of trash in the trash bin by consuming 100 points of energy.

This strategy consumes a total of 10+100+36+100+9+100=355 points of energy.

Sample Input 2

5 1
1 999999997 999999998 999999999 1000000000

Sample Output 2

19999999983

Sample Input 3

10 8851025
38 87 668 3175 22601 65499 90236 790604 4290609 4894746

Sample Output 3

150710136

Sample Input 4

16 10
1 7 12 27 52 75 731 13856 395504 534840 1276551 2356789 9384806 19108104 82684732 535447408

Sample Output 4

3256017715


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

using Graph=vector<vector<int>>;
int main(){
    int n;
    cin>>n;
    int m;
    cin>>m;
    string s;
    cin>>s;
    Graph g(n);
    for(int i=0;i<m;i++){
        int a,b;
        cin>>a>>b;
        a--,b--;
        g[a].push_back(b);
        g[b].push_back(a);
    }
    vector<int> acnt(n);
    vector<int> bcnt(n);
    vector<int> ng(n,false);
    stack<int> ngs;
    for(int i=0;i<n;i++){
        for(int j=0;j<g[i].size();j++){
            if(s[g[i][j]]=='A') acnt[i]++;
            if(s[g[i][j]]=='B') bcnt[i]++;
        }
        if(acnt[i]==0 || bcnt[i]==0){
            ng[i]=true;
            ngs.push(i);
        }
    }

    while(!ngs.empty()){
        int v=ngs.top();
        ngs.pop();
        for(int i=0;i<g[v].size();i++){
            if(s[v]=='A'){
                if((--acnt[g[v][i]])==0 && !ng[g[v][i]]){
                    ng[g[v][i]]=true;
                    ngs.push(g[v][i]);
                }

            }
            if(s[v]=='B'){
                if((--bcnt[g[v][i]])==0 && !ng[g[v][i]]){
                    ng[g[v][i]]=true;
                    ngs.push(g[v][i]);
                }
            }
        }
    }
    //cerr<<"#"<<endl;
    //for(int i=0;i<n;i++) cerr<<ng[i]<<endl;
    cout<<(accumulate(ng.begin(),ng.end(),0)==n ? "No" : "Yes")<<endl;

    return 0;
}

Score : 900 points

Problem Statement

You are given an undirected graph consisting of N vertices and M edges.
The vertices are numbered 1 to N, and the edges are numbered 1 to M.
In addition, each vertex has a label, A or B. The label of Vertex i is s_i.
Edge i bidirectionally connects vertex a_i and b_i.

The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times.
Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.

For example, in a graph where Vertex 1 has the label A and Vertex 2 has the label B, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is ABABB.

Determine if Nusook can make all strings consisting of A and B.

Constraints

2 \leq N \leq 2 \times 10^{5}

1 \leq M \leq 2 \times 10^{5}

|s| = N

s_i is A or B.

1 \leq a_i, b_i \leq N

The given graph may NOT be simple or connected.

Input

Input is given from Standard Input in the following format:

N M
s
a_1 b_1
:
a_{M} b_{M}

Output

If Nusook can make all strings consisting of A and B, print Yes; otherwise, print No.

Sample Input 1

2 3
AB
1 1
1 2
2 2

Sample Output 1

Yes

Since Nusook can visit Vertex 1 and Vertex 2 in any way he likes, he can make all strings consisting of A and B.

Sample Input 2

4 3
ABAB
1 2
2 3
3 1

Sample Output 2

No

For example, Nusook cannot make BB.

The given graph may not be connected.

Sample Input 3

13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9

Sample Output 3

Yes

Sample Input 4

13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11

Sample Output 4

No


#include<iostream>
#include<vector>

using namespace std;

int main(){
  int H,W; cin >> H >> W;
  vector<vector<int>> A(H,vector<int>(W));
  vector<int> Y1; vector<int> X1; vector<int> Y2; vector<int> X2;

  for(int i = 0; i < H; i++){
    for(int j = 0; j < W; j++){ cin >> A[i][j];}}
    int cnt = 0;
    for(int i = 0; i < H; i++){
     if( i % 2 == 0){ //0-indexedで偶数番目の行について調べる
       for(int j = 0; j < W; j++){
         if( j != W - 1){
          if( A[i][j] % 2 == 0){ continue;}
          else{ A[i][j]--; A[i][j+1]++; cnt++; Y1.push_back(i+1); X1.push_back(j+1);
                                               Y2.push_back(i+1); X2.push_back(j+2);
                            }}
         else{ // j == W - 1の時
           if( A[i][j] % 2 != 0){ A[i][j]--;A[i+1][j]++; cnt++;
                                              Y1.push_back(i+1); X1.push_back(j+1);
                                              Y2.push_back(i+2); X2.push_back(j+1);
                                }}
       }} //偶数行終了
     else{
       for(int j = W- 1; j >= 0; j--){
         if( j != 0){
           if( A[i][j] % 2 == 0){ continue;}
           else{ A[i][j]--; A[i][j-1]--; cnt++;
                 Y1.push_back(i+1); X1.push_back(j+1);
                 Y2.push_back(i+1); X2.push_back(j);}}
         else{ // j == 0の時
           if( A[i][j] % 2 != 0){ A[i][j]--; A[i+1][j]++; cnt++;
                 Y1.push_back(i+1); X1.push_back(j+1);
                 Y2.push_back(i+2); X2.push_back(j+1);}}
       }}} //奇数行終了

      cout << cnt << endl;
      if( cnt != 0){

      for(int i = 0; i < cnt; i++){
        cout << Y1[i] << " " << X1[i] << " " << Y2[i] << " " << X2[i] << endl;}}

     return 0;}

Score : 400 points

Problem Statement

There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).

In Cell (i, j), a_{ij} coins are placed.

You can perform the following operation any number of times:

Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.

Maximize the number of cells containing an even number of coins.

Constraints

All values in input are integers.

1 \leq H, W \leq 500

0 \leq a_{ij} \leq 9

Input

Input is given from Standard Input in the following format:

H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}

Output

Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:

N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'

That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.

In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').

Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.

Sample Input 1

2 3
1 2 3
0 1 1

Sample Output 1

3
2 2 2 3
1 1 1 2
1 3 1 2

Every cell contains an even number of coins after the following sequence of operations:

Move the coin in Cell (2, 2) to Cell (2, 3).

Move the coin in Cell (1, 1) to Cell (1, 2).

Move one of the coins in Cell (1, 3) to Cell (1, 2).

Sample Input 2

3 2
1 0
2 1
1 0

Sample Output 2

3
1 1 1 2
1 2 2 2
3 1 3 2

Sample Input 3

1 5
9 9 9 9 9

Sample Output 3

2
1 1 1 2
1 3 1 4


#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iomanip>
#include<vector>
#include<queue>
#include<deque>
#include<string>
#include<utility>
#include<cmath>
#include<algorithm>
#include<cctype>
#include<set>
#include<map>
#include<bitset>
#include<stack>
#include<ctime>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,int> pli;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vpii;
typedef vector<pli> vpli;

inline ll read(){
    ll Hashimoto=0;
	bool Kanna=1;
    char I_Love=getchar();
    while(I_Love<'0'||I_Love>'9'){
        if(I_Love=='-')Kanna=0;
        I_Love=getchar();
    }
    while(I_Love>='0'&&I_Love<='9'){
        Hashimoto=Hashimoto*10+I_Love-'0';
        I_Love=getchar();
    }
    return (Kanna?Hashimoto:-Hashimoto);
}
template<typename T1,typename T2> inline void Umax(T1 &a,T2 b){
	if(a<b)a=b;
}
template<typename T1,typename T2> inline void Umin(T1 &a,T2 b){
	if(a>b)a=b;
}

#define I_Love_Hashimoto_Kanna main
#define fastio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define filein(s) freopen(s,"r",stdin);
#define fileout(s) freopen(s,"w",stdout);
#define file freopen("I_Love_Hashimoto_Kanna.out","w",stdout);
#define RE cout<<"I_Love_Hashimoto_Kanna"<<endl;
#define Tone(Kanna) cout<<Kanna<<endl;
#define Tall(Hashimoto,Kanna) for(int I_Love=0;I_Love<(Kanna);++I_Love)cout<<Hashimoto[I_Love]<<(I_Love==(Kanna)-1?"\n":" ");
#define FOR(I_Love,Hashimoto,Kanna) for(int I_Love=Hashimoto;I_Love<(Kanna);++I_Love)
#define MP(Hashimoto,Kanna) make_pair(Hashimoto,Kanna)
#define REV(Kanna) reverse(Kanna.begin(),Kanna.end());
#define SORT(Kanna) sort(Kanna.begin(),Kanna.end());
#define inf (int)1e9
#define linf (ll)1e18
#define mod (inf+7)

int n,k;

int I_Love_Hashimoto_Kanna() {
	fastio;
	cin>>n>>k;
	ll cnt=0;
	ll cnt2=0;
	for(int i=1;i<=n;i++){
		if(2*i%k==0){
			if((2*i/k)%2)cnt++;
			else cnt2++;
		}
	}

	Tone(cnt*cnt*cnt+cnt2*cnt2*cnt2)

	return 0;
}

Score : 300 points

Problem Statement

You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.
The order of a,b,c does matter, and some of them can be the same.

Constraints

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

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K.

Sample Input 1

3 2

Sample Output 1

9

(1,1,1),(1,1,3),(1,3,1),(1,3,3),(2,2,2),(3,1,1),(3,1,3),(3,3,1) and (3,3,3) satisfy the condition.

Sample Input 2

5 3

Sample Output 2

1

Sample Input 3

31415 9265

Sample Output 3

27

Sample Input 4

35897 932

Sample Output 4

114191


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

// Loops
#define _overload3(_1, _2, _3, name, ...) name
#define _rep(i, n) repi(i, 0, n)
#define repi(i, a, b) for (int i = int(a); i < int(b); ++i)
#define _rrep(i, n) rrepi(i, n, 0)
#define rrepi(i, a, b) for (int i = int(a) - 1; i >= int(b); --i)

#define rep(...) _overload3(__VA_ARGS__, repi, _rep, )(__VA_ARGS__)
#define rrep(...) _overload3(__VA_ARGS__, rrepi, _rrep, )(__VA_ARGS__)
#define each(xi, x) for (auto &&xi : x)
// Note: we can use rep(i,N) or rep(i,from,to)

// typedef
template <class T> using vec = vector<T>;
using ll = long long;
using vi = vec<ll>;
using vvi = vec<vi>;
using vvvi = vec<vvi>;
using pii = pair<ll, ll>;

// Constants

// Shorter repr for frequently used terms
#define pb push_back
#define mp make_pair

// Algorithms
#define all(x) (x).begin(), (x).end()
#define uniq(v) v.erase(unique(all(v)), v.end())
#define perm(c)                                                                \
  sort(all(c));                                                                \
  for (bool c##p = 1; c##p; c##p = next_permutation(all(c)))

template <class T> pair<T, size_t> max(vector<T> &x) {
  auto it = max_element(all(x));
  return mp(*it, it - x.begin());
}
template <class T> pair<T, size_t> min(vector<T> &x) {
  auto it = min_element(all(x));
  return mp(*it, it - x.begin());
}

template <class T> inline bool chmax(T &maxval, const T &newval) {
  if (maxval < newval) {
    maxval = newval;
    return 1;
  }
  return 0;
}
template <class T> inline bool chmin(T &minval, const T &newval) {
  if (minval > newval) {
    minval = newval;
    return 1;
  }
  return 0;
}

// Utilities
// Grid world utilities
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
#define inside(H, W, y, x) 0 <= (x) && (x) < (W) && 0 <= (y) && (y) < (H)

// Debug
#ifdef LOCAL
#include "dump.hpp"
#define debug(x) cerr << #x << ": " << x << '\n'
#else
#define dump(...)
#define debug(x)
#endif

// Yes or No
void yesno(bool ok, string yes = "Yes", string no = "No") {
  cout << (ok ? yes : no) << endl;
}

// Paste snippets here!!

//

void solve(long long N, long long i) {
  cout << N - i + 1 << endl;
}

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false); // Magic for faster cin
  cout.precision(12);
  long long N;
  std::cin >> N;
  long long i;
  std::cin >> i;
  solve(N, i);
  return 0;
}

Score : 100 points

Problem Statement

There is an N-car train.

You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."

Constraints

1 \leq N \leq 100

1 \leq i \leq N

Input

Input is given from Standard Input in the following format:

N i

Output

Print the answer.

Sample Input 1

4 2

Sample Output 1

3

The second car from the front of a 4-car train is the third car from the back.

Sample Input 2

1 1

Sample Output 2

1

Sample Input 3

15 11

Sample Output 3

5


#include<bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define Would
#define you
#define please

int main() {
	int N,i;
	cin >> N >> i;
	cout << N + 1 - i << "\n";

	Would you please return 0;
}


#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
const int INF = 1 << 30;
const ll INFll = 1ll << 60;

int main() {
  int h, w;
  cin >> h >> w;
  vector<int> H;
  vector<int> W;
  vector<vector<char>> A(h, vector<char>(w));
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      char a;
      cin >> a;
      A[i][j] = a;
      if (a == '#') {
        H.push_back(i);
        W.push_back(j);
      }
    }
  }

  for (int i : H) {
    for (int j : W) {
      cout << A[i][j];
    }
    cout << endl;
  }

  return 0;
}

Score : 200 points

Problem Statement

There is a grid of squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column from the left is represented as (i, j).
Each square is black or white.
The color of the square is given as an H-by-W matrix (a_{i, j}).
If a_{i, j} is ., the square (i, j) is white; if a_{i, j} is #, the square (i, j) is black.

Snuke is compressing this grid.
He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares:

Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns.

It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation.
Find the final state of the grid.

Constraints

1 \leq H, W \leq 100

a_{i, j} is . or #.

There is at least one black square in the whole grid.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}...a_{1, W}
:
a_{H, 1}...a_{H, W}

Output

Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity.

Sample Input 1

4 4
##.#
....
##.#
.#.#

Sample Output 1

###
###
.##

The second row and the third column in the original grid will be removed.

Sample Input 2

3 3
#..
.#.
..#

Sample Output 2

#..
.#.
..#

As there is no row or column that consists only of white squares, no operation will be performed.

Sample Input 3

4 5
.....
.....
..#..
.....

Sample Output 3

#

Sample Input 4

7 6
......
....#.
.#....
..#...
..#...
......
.#..#.

Sample Output 4

..#
#..
.#.
.#.
#.#


#include<bits/stdc++.h>
using namespace std;
int n,m;
char f[101][101]={0};
int check(int a,int i)
{
	int j;
	if(a==0)
	{
		for(j=0;j<m;j++)
		{
			if(f[i][j]=='#')
				return 0;
		}
		return 1;
	}
	else
	{
		for(j=0;j<n;j++)
		{
			if(f[j][i]=='#')
				return 0;
		}
		return 1;
	}
}
void remove(int a,int i)
{
	int j;
	if(a==0)
	{
		for(j=0;j<m;j++)
		{
			f[i][j]=' ';
		}
	}
	else
	{
		for(j=0;j<n;j++)
		{
			f[j][i]=' ';
		}
	}
}
int main()
{
	int i,j,t;
	scanf("%d %d",&n,&m);
	getchar();
	for(i=0;i<n;i++)
	{
		scanf("%s",f[i]);
	}
	for(i=0;i<n;i++)
	{
		if(check(0,i))
			remove(0,i);
	}
	for(j=0;j<m;j++)
	{
		if(check(1,j))
			remove(1,j);
	}
	for(i=0;i<n;i++)
	{
		t=0;
		for(j=0;j<m;j++)
		{
			if(f[i][j]!=' ')
			{
				printf("%c",f[i][j]);
				t=1;
			}
		}
		if(t)
			printf("\n");
	}
	return 0;
}


#include <iostream>
#include <algorithm>
using namespace std;
#define MAX_N 100001

int N;
int K;
long int x[MAX_N];

int main(){
    cin >> N >> K;
    bool flag = true;
    for (int i = 0; i < N; i++){
        long int element;
        cin >> element;
        // if ((element > 0) && (flag)){
            // flag = false;
            // x[i] = 0;
            // i ++;
        // }
        x[i] = element;
    }
    // for (int i = 0; i <= N; i++){
    //     cout << x[i] << endl;
    // }
    int left = 0;
    int right = K - 1;
    long int distance = 10000000001;
    if (x[0] >= 0){
        distance = x[K - 1];
    }
    else if (x[N - 1] <= 0){
        distance = - x[N - K];
    }
    else{
        while (right < N){
            if ((x[right] >= 0) && (x[left] <= 0)){
                distance = min(min(2 * x[right] - x[left], x[right] - 2 * x[left]), distance);
            }
            left ++;
            right ++;
        }
    }
    cout << distance << endl;

    return 0;
}

Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

8 5
-9 -7 -4 -3 1 2 3 4

Sample Output 4

10


#include <functional>
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;

template<typename Monoid>
struct SegmentTree {
    using F = function<Monoid(Monoid, Monoid)>;

    int sz;
    vector<Monoid> seg;

    const F f;
    const Monoid M1;

    SegmentTree(int n, const F f, const Monoid &M1) : f(f), M1(M1) {
        sz = 1;
        while(sz < n) sz <<= 1;
        seg.assign(2 * sz, M1);
    }

    void set(int k, const Monoid &x) {
        seg[k + sz] = x;
    }

    void build() {
        for(int k = sz - 1; k > 0; k--) {
            seg[k] = f(seg[2 * k + 0], seg[2 * k + 1]);
        }
    }

    void update(int k, const Monoid &x) {
        k += sz;
        seg[k] = x;
        while(k >>= 1) {
            seg[k] = f(seg[2 * k + 0], seg[2 * k + 1]);
        }
    }

    Monoid query(int a, int b) {
        Monoid L = M1, R = M1;
        for(a += sz, b += sz; a < b; a >>= 1, b >>= 1) {
            if(a & 1) L = f(L, seg[a++]);
            if(b & 1) R = f(seg[--b], R);
        }
        return f(L, R);
    }

    Monoid operator[](const int &k) const {
        return seg[k + sz];
    }
};

int main()
{
    int n;
    cin >> n;
    int a[100002];
    for(int i = 0; i < n; i++) cin >> a[i];
    int now = 1048576 * 512 - 1;
    int mid = 1048576 * 256;
    while(mid){
        int b[100002]{0};
        for(int i = 0; i < n; i++){
            if(a[i] >= now) b[i]++;
            else b[i]--;
            b[i + 1] += b[i];
        }
        ll s[200002]{0};
        for(int i = 0; i < n; i++) s[b[i] + 100000]++;
        SegmentTree<ll> seg(200000, [](ll a, ll b){return a + b;}, 0ll);
        for(int i = 0; i <= 200000; i++) seg.set(i, s[i]);
        seg.build();
        int k = 0;
        ll sum = 0;
        for(int i = 0; i < n; i++){
            sum += seg.query(k + 100000, 200001);
            seg.update(b[i] + 100000, seg[b[i] + 100000] - 1);
            if(a[i] < now) k--;
            else k++;
        }
        if(sum >= (n * (n + 1) / 2 + 1) / 2) now += mid;
        else now -= mid;
        mid /= 2;
    }
    int b[100002]{0};
    for(int i = 0; i < n; i++){
        if(a[i] >= now) b[i]++;
        else b[i]--;
        b[i + 1] += b[i];
    }
    ll s[200002]{0};
    for(int i = 0; i < n; i++) s[b[i] + 100000]++;
    SegmentTree<ll> seg(200000, [](ll a, ll b){return a + b;}, 0ll);
    for(int i = 0; i <= 200000; i++) seg.set(i, s[i]);
    seg.build();
    int k = 0;
    ll sum = 0;
    for(int i = 0; i < n; i++){
        sum += seg.query(k + 100000, 200001);
        seg.update(b[i] + 100000, seg[b[i] + 100000] - 1);
        if(a[i] < now) k--;
        else k++;
    }
    if(sum < (n * (n + 1) / 2 + 1) / 2) now--;
    cout << now << endl;
}

Score : 700 points

Problem Statement

We will define the median of a sequence b of length M, as follows:

Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.

For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.

Snuke comes up with the following problem.

You are given a sequence a of length N.
For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a.
We will list m_{l, r} for all pairs (l, r) to create a new sequence m.
Find the median of m.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the median of m.

Sample Input 1

3
10 30 20

Sample Output 1

30

The median of each contiguous subsequence of a is as follows:

The median of (10) is 10.

The median of (30) is 30.

The median of (20) is 20.

The median of (10, 30) is 30.

The median of (30, 20) is 30.

The median of (10, 30, 20) is 20.

Thus, m = (10, 30, 20, 30, 30, 20) and the median of m is 30.

Sample Input 2

1
10

Sample Output 2

10

Sample Input 3

10
5 9 5 9 8 9 3 5 4 3

Sample Output 3

8


#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn=1e6+10;
int a[maxn],b[maxn];
struct node{
	int val,loc;
}sub[maxn];
long long tre[maxn],n;
int cmp(const node &a,const node &b){
	if(a.val==b.val) return a.loc<b.loc;
	else return a.val<b.val;
}
inline int lowbit(int x){
	return x&(-x);
}
void add(int pos,int val){
	while(pos<=n){
		tre[pos]+=val;
		pos+=lowbit(pos);
	}
	return;
}
long long query(int pos){
	long long sum=0;
	while(pos>0){
		sum+=tre[pos];
		pos-=lowbit(pos);
	}
	return sum;
}
long long check(int val){
	memset(tre,0,sizeof(tre));
	long long ans=0;
	for(int i=1;i<=n;i++){
		if(a[i]<val) sub[i].val=-1;
		else sub[i].val=1;
		sub[i].val+=sub[i-1].val;
		sub[i].loc=i;
	}
	sort(sub+1,sub+n+1,cmp);
	for(int i=1;i<=n;i++){
		add(sub[i].loc,1);
		ans+=query(sub[i].loc-1);
		if(sub[i].val>=0) ans++;
	}
	return ans;
}
int erf(int l,int r){
	int mid;
	long long _std=(n+1)*n/4+1;
	while(l<r){
		mid=(l+r+1)>>1;
		if(check(b[mid])>=_std) l=mid;//Çó³ö±Èb[mid]´óÓÚµÈÓÚµÄ
		else r=mid-1;
	}
	return l;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++) {
		scanf("%d",&a[i]);b[i]=a[i];
	}

	sort(b+1,b+n+1);
	cout<<b[erf(1,n)];

	return 0;
}


#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
long long n,k,s[101010],minv=200000020;
int main()
{
	cin>>n>>k;
	for(int i=1;i<=n;i++)
	{
		cin>>s[i];
	}
	for(int i=1;i<=(n-k+1);i++)minv=min(minv,(s[i]*s[i+k-1]>0)?max(abs(s[i]),abs(s[i+k-1])):min(abs(s[i]),abs(s[i+k-1]))*2+max(abs(s[i]),abs(s[i+k-1])));
	cout<<minv;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#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 trv(p, u) for (edg *p = h[u]; p; p = p->nxt)
#define push_back pb
typedef long long ll;
typedef double db;
const int N = 2e5 + 100;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;

inline int rd() {
  int s = 0, w = 1; char c = getchar();
  while (c < '0' || c > '9') { if (c == '-') w = -1; c = getchar(); }
  while (c >= '0' && c <= '9') s = s * 10 + c - '0', c = getchar();
  return s * w;
}

int n, ans, a[N], s[N];

struct nod {
  int lft, rgt, sum;
  nod *ls, *rs;
  inline void setc() { sum++; }
  inline void upd() { sum = ls->sum + rs->sum; }
} pol[N << 3], *rot, *cur = pol;

inline void build(nod *r, int lft, int rgt) {
  r->lft = lft, r->rgt = rgt;
  if (lft == rgt) {
    r->sum = 0;
    return ;
  }
  int mid = (lft + rgt) >> 1;
  nod *ls = ++cur, *rs = ++cur;
  r->ls = ls, r->rs = rs;
  build(ls, lft, mid), build(rs, mid + 1, rgt);
  r->upd();
}

inline void chg(nod *r, int pos) {
  if (r->lft == pos && r->rgt == pos) {
    r->setc(); return ;
  }
  if (r->ls->rgt >= pos) chg(r->ls, pos);
  else chg(r->rs, pos);
  r->upd();
}

inline int qry(nod *r, int lft, int rgt) {
  if (lft > rgt) return 0;
  if (r->lft == lft && r->rgt == rgt) return r->sum;
  if (r->ls->rgt >= rgt) return qry(r->ls, lft, rgt);
  else if (r->rs->lft <= lft) return qry(r->rs, lft, rgt);
  else return qry(r->ls, lft, r->ls->rgt) +
              qry(r->rs, r->rs->lft, rgt);
}

inline bool chk(int x) {
  ll res = 0;
  memset(s, 0, sizeof(s));
  cur = pol;
  rep(i, 1, n) {
    if (a[i] <= x) s[i] = s[i - 1] + 1;
    else s[i] = s[i - 1] - 1;
  }
  rep(i, 0, n) s[i] += (n + 1);
  build(rot = pol, 1, N - 100);
  rep(i, 0, n) {
    res += 1ll * qry(rot, 1, s[i] - 1);
    chg(rot, s[i]);
  }
  return (res >= 1ll * n * (n + 1) / 4 + 1);
}

int main() {
  n = rd();
  rep(i, 1, n) a[i] = rd();
  int l = 1, r = inf;
  while (l <= r) {
    int mid = (l + r) >> 1;
    if (chk(mid)) ans = mid, r = mid - 1;
    else l = mid + 1;
  }
  printf("%d\n", ans);
  return 0;
}


//url:
//problem name:

#include <bits/stdc++.h>
#define REP(i,n) for (int i = 0; i < (n); ++i)
template<class T> inline bool chmin(T& a, T b) {if (a > b) {a = b;return true;}return false;}
template<class T> inline bool chmax(T& a, T b) {if (a < b) {a = b;return true;}return false;}
using namespace std;
using ll = long long;
using P = pair<int,int>;
using Pl = pair<long,long>;
using veci = vector<int>;
using vecl = vector<long>;
using vecveci = vector<vector<int>>;
using vecvecl = vector<vector<long long>>;

int main() {
    string S;
    ll K;
    cin >> S >> K;
    if(K == 1) cout << S[0] << endl;
    else if(S[0] == '1') {
        int i = 1;
        while(S[i] == '1') i++;
        cout << S[i] << endl;
    }
    else cout << S[0] << endl;
}

Score: 300 points

Problem Statement

Mr. Infinity has a string S consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:

Each occurrence of 2 in S is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.

For example, if S is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?

Constraints

S is a string of length between 1 and 100 (inclusive).

K is an integer between 1 and 10^{18} (inclusive).

The length of the string after 5 \times 10^{15} days is at least K.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

The first five characters in the string after 5 \times 10^{15} days is 12222. As K=4, we should print the fourth character, 2.

Sample Input 2

3
157

Sample Output 2

3

The initial string is 3. The string after 5 \times 10^{15} days consists only of 3.

Sample Input 3

299792458
9460730472580800

Sample Output 3

2


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

int main(){
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	string s; long long n;
	cin >> s >> n;
	long long temp=0;
	for(int i=0;i<s.length();i++){
		if(s[i]-'0' > 1){
			if(n < temp){
				puts("1");
				return 0;
			}
			else{
				cout << s[i] << "\n";
				return 0;
			}
		}
		temp++;
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> P;
typedef pair<ll,ll> l_l;
const int INF=1001001000;
const int mINF=-1001001000;
const ll LINF=10100100100100100;
int main(){
    int n,m,Q;cin >> n >> m >> Q;
    vector<int> L(m),R(m);
    vector<vector<int>> sum(n+1,vector<int>(n+1,0));
    for(int i=0;i<m;i++){
        cin >> L[i] >> R[i];
        sum[L[i]][R[i]]++;
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            sum[i][j]+=sum[i][j-1]+sum[i-1][j];
            sum[i][j]-=sum[i-1][j-1];
        }
    }
    vector<int> ans(Q);
    for(int i=0;i<Q;i++){
        int p,q;cin >> p >> q;
        ans[i]=sum[q][q]-sum[q][p-1]-sum[p-1][q]+sum[p-1][p-1];
    }
    for(int i=0;i<Q;i++) cout << ans[i] << endl;
    return 0;
}

Score: 400 points

Problem Statement

In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east.
A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i).
Takahashi the king is interested in the following Q matters:

The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.

Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.

Constraints

N is an integer between 1 and 500 (inclusive).

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

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

1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)

1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q

Output

Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.

Sample Input 1

2 3 1
1 1
1 2
2 2
1 2

Sample Output 1

3

As all the trains runs within the section from City 1 to City 2, the answer to the only query is 3.

Sample Input 2

10 3 2
1 5
2 8
7 10
1 7
3 10

Sample Output 2

1
1

The first query is on the section from City 1 to 7. There is only one train that runs strictly within that section: Train 1.
The second query is on the section from City 3 to 10. There is only one train that runs strictly within that section: Train 3.

Sample Input 3

10 10 10
1 6
2 9
4 5
4 7
4 7
5 8
6 6
6 7
7 9
10 10
1 8
1 9
1 10
2 8
2 9
2 10
3 8
3 9
3 10
1 10

Sample Output 3

7
9
10
6
8
9
6
7
8
10


#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <vector>
#include <regex>
#include <map>
#include <set>
using namespace std;
int main(){
    int N,K;
    cin >> N >> K;
    cout << N%K << endl;

return 0;
}

Score : 100 points

Problem Statement

Takahashi has decided to distribute N AtCoder Crackers to K users of as evenly as possible.
When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Constraints

1 \leq N,K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Sample Input 1

7 3

Sample Output 1

1

When the users receive two, two and three crackers, respectively, the (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user, is 1.

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0


#include <iostream>

using namespace std;

int main() {
    int N, K;
    cin >> N >> K;
    if(N < K) cout << 1 << "\n";
    else cout << N%K << "\n";
}


#include<cstdio>
#include<iostream>
using namespace std;
int main(){
	int n,k;
	cin>>n>>k;
	if(n%k==0)
	printf("0");
	else
	printf("1");
}


#include <iostream>
#include <iomanip> //! for setprecision(10)
#include <math.h>
#include <algorithm>
#include <functional>
#include <string>
#include <vector>

#include <cstring>
#include <set>
#include <map>
#include <queue>
#include <utility>

using namespace std;

typedef long long LL;

#define dump(c) { for (auto it = c.begin(); it != c.end(); ++it) if (it == c.begin()) cout << *it; else cout << ' ' << *it; cout << endl; }
#define rep(i,n) for (int i = 0; i < (n); ++i)

const int MOD = 1000000007;

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

    int N;
    cin >> N;

    int ans = 0;
    for (int i = 0; i*4 <= N; ++i) {
        if ((N-i*4)%7 == 0) {
            ++ans;
        }
    }

    cout << (ans ? "Yes" : "No") << endl;

    return 0;
}

Score : 200 points

Problem Statement

La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each.
Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.

Constraints

N is an integer between 1 and 100, inclusive.

Input

Input is given from Standard Input in the following format:

N

Output

If there is a way to buy some cakes and some doughnuts for exactly N dollars, print Yes; otherwise, print No.

Sample Input 1

11

Sample Output 1

Yes

If you buy one cake and one doughnut, the total will be 4 + 7 = 11 dollars.

Sample Input 2

40

Sample Output 2

Yes

If you buy ten cakes, the total will be 4 \times 10 = 40 dollars.

Sample Input 3

3

Sample Output 3

No

The prices of cakes (4 dollars) and doughnuts (7 dollars) are both higher than 3 dollars, so there is no such way.


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

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

	int n = 0;
	for (int i = 0; i < 26; i++) {
		for (int j = 0; j < 16; j++) {
			if ((4*i + 7*j) == x)n++;
		}
	}

	if (n > 0)cout << "Yes";
	else cout << "No";
}


#include <bits/stdc++.h>

#define F first
#define S second
#define PB push_back

using namespace std;

typedef long long LL;
typedef pair<int, int> PII;
typedef priority_queue<int> HEAP;
typedef priority_queue<int, vector<int>, greater<int> > RHEAP;

const int N = 100010, M = 1010;

int n, m = -2;
string res;

int main()
{
	cin >> n;
	if (!n) puts("0");
	else
	{
		for (int i = n; i; i /= m)
		{
			if (i % abs(m))
			{
				res += "1";
				if (m < 0) i -- ;
			}
			else res += "0";
		}
		reverse(res.begin(), res.end());
	}
	cout << res << endl;
    return 0;
}

Score : 300 points

Problem Statement

Given an integer N, find the base -2 representation of N.

Here, S is the base -2 representation of N when the following are all satisfied:

S is a string consisting of 0 and 1.

Unless S = 0, the initial character of S is 1.

Let S = S_k S_{k-1} ... S_0, then S_0 \times (-2)^0 + S_1 \times (-2)^1 + ... + S_k \times (-2)^k = N.

It can be proved that, for any integer M, the base -2 representation of M is uniquely determined.

Constraints

Every value in input is integer.

-10^9 \leq N \leq 10^9

Input

Input is given from Standard Input in the following format:

N

Output

Print the base -2 representation of N.

Sample Input 1

-9

Sample Output 1

1011

As (-2)^0 + (-2)^1 + (-2)^3 = 1 + (-2) + (-8) = -9, 1011 is the base -2 representation of -9.

Sample Input 2

123456789

Sample Output 2

11000101011001101110100010101

Sample Input 3

0

Sample Output 3

0


#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
typedef long long ll;
using namespace std;

int main() {
    ll n; cin >> n;
    string s;
    while (n) {
        if (n == 0) {
            cout << 0 << endl;
        }
        if (n % 2 == 0){
            s = "0" + s;
            n /= -2;
        } else {
            n -= 1;
            s = "1" + s;
            n /= -2;
        }
    }
    cout << s << endl;
    return 0;
}


#include<iostream>
using namespace std;

int main(){
int N;
int A[1000];
double all=0;
double ten=1;
int x;
int i=0;
int total;

cin >> N;
while(1){
  if(N == 0){
    break;
  }

x = N%(-2);
if(x==(-1))x=1;
A[i] = x;
i++;
N -= x;
N = N/(-2);
}

total = i-1;
for(int k = total; k>=0; k--)
cout << A[k] ;

cout << endl;

}


/*
                  友利奈緒ぱわーでACしてくれ！！！！！！！！！！！！
                  Charlotteまだ見てない人は見ような！！！！！！！

                  ／　 /:／　　　　　　　　　　　 　 ＼:ヽ　＼
  　　　　　　　 /　　／　　　　　　 　 　 　 　 　 　 　 ＼　　ヽ
  　　　　　＼__L 彡　　　　　　　　　　　　　　　　　　　 ヽ　　',
  　　　　　　　ﾌ /　　　/　　/　 /　　　,　　 　 　 　 ヽ　　', 　ｊ
  　　　　　　　ﾚ　　　 /　　/ 　/　 　 　 　 　 　 　 　 ', 　ヽ　j
  　　　 　 　 // 　 　 !　/_l＿/__ノ 　　{ ＼}　　　　 　 ',　　',/
  　　　　　　i ﾊ 　 　 {　从j　ﾊ　i　　　 ',　 ト-､}　 i i　 }　　jj
  　　　　　　( ﾊ　　　(　 川　ハ ﾊ　 !　 '　ﾊ　 ﾊ　j j　,' 　 八
  　　　 ＜＿,ｨ∧　　　斗芹ﾃミxハ ﾊ　 ﾚ　} /__ﾚﾚ　/ 　 ∧ ＼　ﾉ
  　　　 　 　 ∨　＼ 　ゝ　辷:ソ　　 　)　芹ﾚ心ヾレ′　/ ト--　´
  　　　＼ｰ‐'　ﾉ　　 ＼ゝ　　　　　　 　 　 ゞ:_ソ "/ 　／ 　ヽ
  　　　　 　 フ　　　　i八 " "　　　,　　　　　　　ム彡　　　　＼
  　　　　 　/　　/　　j　 ト　　　　　　 　 　 " "イト＜　 　 　 ＼＼
  　　　　 /　　/　　　j　/／ヽ､ 　 ∩　　 　 イ　{ {　　￣ フフへ ＼＼
  　　　　(　／　　　 ,/ / 　　i　＞――＜ニニニﾆ┐　 〃／: : ヽ　ヽヽ
  　　　　／　　ィT´/ /┌―　￣￣ /::: , ,)　 　 　 〃／／: : : : : :}　ヽヽ)
  　　　/ /　 ∧ヾi┌― { {￣　　　 ﾉ:::トﾟ<　 　 　 ∥//: : : : : : : : i　 ﾉ ﾉ
  . 　　( 人　 {:ヽヾi∨　∧V　　　 /:::/　､ヽ　　　 ∥/: : : : : : : : : :}　/
  　　　V　( ∧: :＼'∨　∧V　　 ﾉ:::/　 ∧ 〉＿__∥: : : : : :／: : : :ﾚ
  　　 　 　 /∧: : : : ∨　∧V┬ｲ:::ﾉ　 〈 TT　|　|{{: : : : ／: : : : : ∧　　 ﾉ
  　　　 　 (　ハ: : : : :∨'T∧Vi　i (　 　 V　!　!　{{: : ／ : : : : : : /　ｰ　ノ
  　　　　　V　ハ: : : : :∨ﾍ∧V　i ゝゝ　 i／⌒＼{／ : : : : : : : /ｰ― ´
  　　　　　 ∨　ヽ: : : : :∨ﾍ∧∨i　〉 〉 /　/二　 ): : : : : : : : :/

          (https://seesaawiki.jp/asciiart/d/Charlotte より)
*/
#include <bits/stdc++.h>
using namespace std;
using ll = long long; using ull = unsigned long long;
// #define int ll
// #define DEBUG 42
inline void nprint(){}
template <class Head, class... Tail>
inline void nprint(Head &&head, Tail &&... tail) {
    cout << head << endl;
    nprint(move(tail)...);
}
#ifdef DEBUG
  #define eprint(...) nprint(__VA_ARGS__)
#else
  #define eprint(...) if(0==1) cout << 1 << endl;
#endif
#define Yes(a) cout << (a ? "Yes" : "No") << endl
#define YES(a) cout << (a ? "YES" : "NO") << endl
#define POSSIBLE(a) cout << (a ? "POSSIBLE" : "IMPOSSIBLE") << endl
using cmp = complex<double>;
using vb = vector<bool>; using vvb = vector<vb>;
using vi = vector<int>; using vvi = vector<vi>;
using vl = vector<ll>; using vvl = vector<vl>;
template<class T> using V = vector<T>;
template<class T> using VV = vector<V<T>>;
#define fi first
#define se second
#define maxs(x,y) (x=max(x,y))
#define mins(x,y) (x=min(x,y))
using pii = pair<int,int>; using pll = pair<ll,ll>;
#define FOR(i,a,b) for(ll i = (a); i < (ll)(b); ++i)
#define REP(i,n) FOR(i,0,n)
#define FORS(i,a,b) FOR(i,a,b+1)
#define REPS(i,n) REP(i,n+1)
#define RFOR(i,a,b) for(ll i = (ll)(b)-1;i >= a;--i)
#define RREP(i,n) RFOR(i,0,n)
#define RREPS(i,n) RREP(i,n+1)
#define RFORS(i,a,b) RFOR(i,a,b+1)
#define ALL(obj) (obj).begin(), (obj).end()
#define RALL(obj) (obj).rbegin(), (obj).rend()
#define PERM(c) sort(ALL(c)); for(bool cp = true;cp;cp = next_permutation(ALL(c)))
#define eb(val) emplace_back(val)
const double PI = acos(-1), EPS = 1e-10;
constexpr ll MOD = 1E9+7;
constexpr int dx[] = {1,0,-1,0}; constexpr int dy[] = {0,1,0,-1};
template<typename T1, typename T2> ostream& operator<<(ostream& s, const pair<T1, T2>& p){
  return s << "(" << p.first << ", " << p.second << ")";
}
template<class T> istream& operator>>(istream &is,vector<T> &st){
  for(size_t i=0;i<st.size();++i) is >> st[i];
  return is;
}
template<class T> istream& operator>>(istream &is,vector<vector<T>> &st){
  for(size_t i=0;i<st.size();++i) is >> st[i];
  return is;
}
template<class T> ostream& operator<<(ostream &os, const vector<T> &st){
  for(size_t i=0;i<st.size();++i){
    if(i==st.size()-1) os << st[i];
    else os << st[i] << " ";
  }
  return os;
}
template<class T> ostream& operator<<(ostream &os, const vector<vector<T>> &st){
  for(size_t i=0;i<st.size();++i){
    os << st[i];
    if(i!=st.size()-1) os << endl;
  }
  return os;
}
signed main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(10);
  int n,m;
  cin >> n >> m;
  vi a(n);
  ll sum[n+1];
  cin >> a;
  sum[0] = 0;
  REP(i,n){
    sum[i+1] = sum[i] + a[i];
  }
  ll ans = 0;
  int i=0,j=0;
  ++n;
  for(i=0;i<n;++i)for(j=i+1;j<n;++j)if(!((sum[j]-sum[i])%m)) ++ans;
  cout << ans << endl;
}

Score : 400 points

Problem Statement

There are N boxes arranged in a row from left to right. The i-th box from the left contains A_i candies.

You will take out the candies from some consecutive boxes and distribute them evenly to M children.

Such being the case, find the number of the pairs (l, r) that satisfy the following:

l and r are both integers and satisfy 1 \leq l \leq r \leq N.

A_l + A_{l+1} + ... + A_r is a multiple of M.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

2 \leq M \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the number of the pairs (l, r) that satisfy the conditions.

Note that the number may not fit into a 32-bit integer type.

Sample Input 1

3 2
4 1 5

Sample Output 1

3

The sum A_l + A_{l+1} + ... + A_r for each pair (l, r) is as follows:

Sum for (1, 1): 4

Sum for (1, 2): 5

Sum for (1, 3): 10

Sum for (2, 2): 1

Sum for (2, 3): 6

Sum for (3, 3): 5

Among these, three are multiples of 2.

Sample Input 2

13 17
29 7 5 7 9 51 7 13 8 55 42 9 81

Sample Output 2

6

Sample Input 3

10 400000000
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

25


#include<stdio.h>
int main(void){
  int R;
  scanf("%d",&R);
  if(R<1200){
    printf("ABC");
  }
  else if(1200<=R&&R<2800){
    printf("ARC");
  }
  else{
	printf("AGC");
  }
  return 0;
}

Score : 100 points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200.

The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800.

The contest after the ARC is called AGC, which is rated for all contestants.

Takahashi's rating on AtCode is R. What is the next contest rated for him?

Constraints

0 ≤ R ≤ 4208

R is an integer.

Input

Input is given from Standard Input in the following format:

R

Output

Print the name of the next contest rated for Takahashi (ABC, ARC or AGC).

Sample Input 1

1199

Sample Output 1

ABC

1199 is less than 1200, so ABC will be rated.

Sample Input 2

1200

Sample Output 2

ARC

1200 is not less than 1200 and ABC will be unrated, but it is less than 2800 and ARC will be rated.

Sample Input 3

4208

Sample Output 3

AGC


#include<bits/stdc++.h>

using namespace std;
int d,g;
pair<int,int> pc[10];
int ans=100000;

bool dfs(int sum,int cnt,int i){
    if(sum>=g){
        ans=min(ans,cnt);
        return true;
    }else if(i<0)
        return false;

    dfs(sum+(i+1)*100*(pc[i].first)+pc[i].second,cnt+(pc[i].first),i-1);

    for(int j=0;j<pc[i].first;j++){
        if(dfs(sum+(i+1)*100*j,cnt+j,i-1)==false)
            break;
    }

    return true;
}

void solve(){
    if(dfs(0,0,d-1));
    printf("%d\n",ans);
}

int main(void){
    cin >> d >> g;
    for(int i=0;i<d;i++)
        cin >> pc[i].first >> pc[i].second;

    solve();
    return 0;
}

Score : 300 points

Problem Statement

A programming competition site AtCode provides algorithmic problems.
Each problem is allocated a score based on its difficulty.
Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points.
These p_1 + … + p_D problems are all of the problems available on AtCode.

A user of AtCode has a value called total score.
The total score of a user is the sum of the following two elements:

Base score: the sum of the scores of all problems solved by the user.

Perfect bonuses: when a user solves all problems with a score of 100i points, he/she earns the perfect bonus of c_i points, aside from the base score (1 ≤ i ≤ D).

Takahashi, who is the new user of AtCode, has not solved any problem.
His objective is to have a total score of G or more points.
At least how many problems does he need to solve for this objective?

Constraints

1 ≤ D ≤ 10

1 ≤ p_i ≤ 100

100 ≤ c_i ≤ 10^6

100 ≤ G

All values in input are integers.

c_i and G are all multiples of 100.

It is possible to have a total score of G or more points.

Input

Input is given from Standard Input in the following format:

D G
p_1 c_1
:
p_D c_D

Output

Print the minimum number of problems that needs to be solved in order to have a total score of G or more points. Note that this objective is always achievable (see Constraints).

Sample Input 1

2 700
3 500
5 800

Sample Output 1

3

In this case, there are three problems each with 100 points and five problems each with 200 points. The perfect bonus for solving all the 100-point problems is 500 points, and the perfect bonus for solving all the 200-point problems is 800 points. Takahashi's objective is to have a total score of 700 points or more.

One way to achieve this objective is to solve four 200-point problems and earn a base score of 800 points. However, if we solve three 100-point problems, we can earn the perfect bonus of 500 points in addition to the base score of 300 points, for a total score of 800 points, and we can achieve the objective with fewer problems.

Sample Input 2

2 2000
3 500
5 800

Sample Output 2

7

This case is similar to Sample Input 1, but the Takahashi's objective this time is 2000 points or more. In this case, we inevitably need to solve all five 200-point problems, and by solving two 100-point problems additionally we have the total score of 2000 points.

Sample Input 3

2 400
3 500
5 800

Sample Output 3

2

This case is again similar to Sample Input 1, but the Takahashi's objective this time is 400 points or more. In this case, we only need to solve two 200-point problems to achieve the objective.

Sample Input 4

5 25000
20 1000
40 1000
50 1000
30 1000
1 1000

Sample Output 4

66

There is only one 500-point problem, but the perfect bonus can be earned even in such a case.


#include <bits/stdc++.h>
using namespace std;
using P = pair<int, int>;

const int INF = 1 << 30;

int main(){
	int d, g;
	scanf("%d%d", &d, &g);
	vector<pair<int, int> > p;
	for(int i = 0; i < d; i++) {
		int a, b;
		scanf("%d%d", &a, &b);
		p.push_back(make_pair(a, b));
	}
	int ans = INF;
	for(int i = 0; i < (1 << d); i++) {
		int sum = 0, last = -1;
		int cnt = 0;
		for(int j = 0; j < d; j++) {
			if(i & (1 << j)) {
				sum += 100 * (j + 1) * p[j].first + p[j].second;
				cnt += p[j].first;
			}else{
				last = j;
			}
		}
		if(sum < g) {
			int point = 100 * (last + 1);
			int need = (g - sum + point - 1) / point;
			if(need >= p[last].first) continue;
			cnt += need;
		}
		ans = min(ans, cnt);
	}
	printf("%d\n", ans);
}


#include <bits/stdc++.h>
typedef long long int ll;
typedef long double ld;
using namespace std;
const long long int INF = 1e18;
const long long int mod = 1e9+7;

typedef pair<ll, ll> pairs;
typedef vector<pairs> p;

struct Edge{
    ll to, weight;
    Edge(ll t, ll w) : to(t), weight(w){}
};
using graph = vector<vector<ll>>;
using Graph = vector<vector<Edge>>;

ll gcd(ll a,ll b){
    if(b == 0){
        return a;
    }else{
        return gcd(b, a%b);
    }
}

ll lcm(ll a, ll b){
    return a / gcd(a, b) * b;
}

ll keta(ll N){
    int tmp{};
    while( N > 0 ){
        tmp += ( N % 10 );
        N /= 10;
    }
    N = tmp;
    return N;
}

// 回文
bool kai(string S){
    bool flag = true;
    for(ll i=0;i<S.size()/2;++i){
        if(S[i] != S[S.size()-i-1]){
            flag = false;
            break;
        }
    }
    return flag;
}
// ---------------------------------------------

int main(){
    ll d, g;
    cin>>d>>g;
    vector<ll> p(d), c(d);
    for(ll i=0;i<d;++i){
        cin>>p[i]>>c[i];
    }

    ll ans = INF;
    for(ll b=0;b<(1 << d);++b){
        ll flag = 0;
        ll num = 0;
        ll r = -1;
        for(ll i=0;i<d;++i){
            if(b >> i & 1){
                flag += 100 * (i+1) * p[i] + c[i];
                num += p[i];
            }else{
                r = i;
            }
        }
        if(flag < g){
            ll fl = 100 * (r+1);
            ll sum = (g - flag + fl -1) / fl;
            if(sum >= p[r]){
                continue;
            }
            num += sum;
        }
        ans = min(ans, num);
    }
    cout<<ans<<endl;

    return 0;
}


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

int main()
{
     ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int d,g;
    cin>>d>>g;
    vector<pair<long long int,long long int> >ar(d+1);
    for(int i=1;i<=d;i++)
       {
           cin>>ar[i+1].first>>ar[i+1].second;
       }
    long long int y=0;long long int ans=0;
    for(int i=d;i;i--)
    {   if(g<=0)break;
        y=ar[i].first*100*i;y+=ar[i].second;
        if(y<=g){g-=y;ans+=ar[i].first;continue;}
        y-=ar[i].second;y/=ar[i].first;
        long long int v=g/y;
        if(g%y&&v<ar[i].first)v++;
        ans+=v;
        g-=(v*100*i);
        if(g<=0)break;
    }
    cout<<ans<<"\n";
return 0;
}


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

int main(){
    vector<int> a(3);
    for(int i=0;i<3;i++)cin>>a[i];
    sort(a.begin(),a.end());
    cout<<(a[1]-a[0])+(a[2]-a[1])<<endl;
    return 0;
}

Score : 100 points

Problem Statement

You have three tasks, all of which need to be completed.

First, you can complete any one task at cost 0.

Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.

Here, |x| denotes the absolute value of x.

Find the minimum total cost required to complete all the task.

Constraints

All values in input are integers.

1 \leq A_1, A_2, A_3 \leq 100

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

Print the minimum total cost required to complete all the task.

Sample Input 1

1 6 3

Sample Output 1

5

When the tasks are completed in the following order, the total cost will be 5, which is the minimum:

Complete the first task at cost 0.

Complete the third task at cost 2.

Complete the second task at cost 3.

Sample Input 2

11 5 5

Sample Output 2

6

Sample Input 3

100 100 100

Sample Output 3

0


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

int main(){
  string s,t;
  cin >> s >> t;
  for(int i = 0; i < s.size(); i++){
    s = s.substr(s.size()-1, 1) + s;
    s.pop_back();
    if(s == t){
      cout << "Yes" << endl;
      return 0;
    }
  }
  cout << "No" << endl;
  return 0;
}

Score : 200 points

Problem Statement

You are given string S and T consisting of lowercase English letters.

Determine if S equals T after rotation.

That is, determine if S equals T after the following operation is performed some number of times:

Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.

Here, |X| denotes the length of the string X.

Constraints

2 \leq |S| \leq 100

|S| = |T|

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S equals T after rotation, print Yes; if it does not, print No.

Sample Input 1

kyoto
tokyo

Sample Output 1

Yes

In the first operation, kyoto becomes okyot.

In the second operation, okyot becomes tokyo.

Sample Input 2

abc
arc

Sample Output 2

No

abc does not equal arc after any number of operations.

Sample Input 3

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Sample Output 3

Yes


#include<iostream>
#include<iomanip>
#include<math.h>
#include<algorithm>
#include<utility>
#include<queue>
#include<string.h>
#include<string>
#include<set>
#include<map>
#include<unordered_map>
#include<vector>
#include<functional>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
const ll INF=4e18;
const ll MOD=1e9+7;
const double EPS=1e-7;

ll N,M;
struct Edge{
  ll to,cost;
};
vector<Edge> edges[100010];
P state[100010];
ll cnt=0;
map<P,bool> used;
void Serch(ll n){
  for(auto e:edges[n]){
    if(used[P(min(n,e.to),max(n,e.to))])continue;
    if(state[e.to].first==-1){
      if(state[n].second==0){
        state[e.to] = P(-(e.cost-state[n].first),1);
      }else{
        state[e.to] = P(e.cost+state[n].first,0);
      }
      used[P(min(n,e.to),max(n,e.to))]=true;
      Serch(e.to);
    }else{
      used[P(min(n,e.to),max(n,e.to))]=true;
      cnt++;
      if(cnt>=2){
        return;
      }
    }
  }
}
int main(){
    cin>>N>>M;
    for(ll i=0;i<M;i++){
      ll u,v,s;
      cin>>u>>v>>s;
      u--;v--;
      edges[u].push_back(Edge{v,s});
      edges[v].push_back(Edge{u,s});
    }
    for(ll i=0;i<N;i++){
      state[i]=P(-1,0);
    }
    state[0]=P(0,1);
    Serch(0);
    if(cnt==0){
      ll d=1,u=INF;
      for(ll i=1;i<N;i++){
          //cout<<state[i].first<<","<<state[i].second<<endl;
        if(state[i].second==0){
          u=min(u,state[i].first-1);
        }else{
          d=max(d,state[i].first);
        }
      }
      cout<<max(0ll,u-d+1)<<endl;
    }else if(cnt==1){
      cout<<1<<endl;
    }else{
      cout<<0<<endl;
    }
    return 0;
}

Score : 600 points

Problem Statement

Kenkoooo found a simple connected graph.
The vertices are numbered 1 through n.
The i-th edge connects Vertex u_i and v_i, and has a fixed integer s_i.

Kenkoooo is trying to write a positive integer in each vertex so that the following condition is satisfied:

For every edge i, the sum of the positive integers written in Vertex u_i and v_i is equal to s_i.

Find the number of such ways to write positive integers in the vertices.

Constraints

2 \leq n \leq 10^5

1 \leq m \leq 10^5

1 \leq u_i < v_i \leq n

2 \leq s_i \leq 10^9

If i\neq j, then u_i \neq u_j or v_i \neq v_j.

The graph is connected.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n m
u_1 v_1 s_1
:
u_m v_m s_m

Output

Print the number of ways to write positive integers in the vertices so that the condition is satisfied.

Sample Input 1

3 3
1 2 3
2 3 5
1 3 4

Sample Output 1

1

The condition will be satisfied if we write 1,2 and 3 in vertices 1,2 and 3, respectively.
There is no other way to satisfy the condition, so the answer is 1.

Sample Input 2

4 3
1 2 6
2 3 7
3 4 5

Sample Output 2

3

Let a,b,c and d be the numbers to write in vertices 1,2,3 and 4, respectively.
There are three quadruples (a,b,c,d) that satisfy the condition:

(a,b,c,d)=(1,5,2,3)

(a,b,c,d)=(2,4,3,2)

(a,b,c,d)=(3,3,4,1)

Sample Input 3

8 7
1 2 1000000000
2 3 2
3 4 1000000000
4 5 2
5 6 1000000000
6 7 2
7 8 1000000000

Sample Output 3

0


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

#define REP(i,n) for(long long i = 0; i < (n); i++)
#define FOR(i, m, n) for(long long i = (m);i < (n); ++i)
#define ALL(obj) (obj).begin(),(obj).end()

template<class T> using V = vector<T>;
template<class T, class U> using P = pair<T, U>;

const ll MOD = (ll)1e9 + 7;
const ll MOD2 = 998244353;
const ll LLINF = (ll)1e18;
const ll INTINF = (ll)1e9;
const long double PI = 3.1415926535897932384626433;

template <class T> void corner(bool flg, T hoge) {if (flg) {cout << hoge << endl; exit(0);}}
template <class T, class U>ostream &operator<<(ostream &o, const map<T, U>&obj) {o << "{"; for (auto &x : obj) o << " {" << x.first << " : " << x.second << "}" << ","; o << " }"; return o;}
template <class T>ostream &operator<<(ostream &o, const set<T>&obj) {o << "{"; for (auto itr = obj.begin(); itr != obj.end(); ++itr) o << (itr != obj.begin() ? ", " : "") << *itr; o << "}"; return o;}
template <class T>ostream &operator<<(ostream &o, const vector<T>&obj) {o << "{"; for (int i = 0; i < (int)obj.size(); ++i)o << (i > 0 ? ", " : "") << obj[i]; o << "}"; return o;}
template <class T, class U>ostream &operator<<(ostream &o, const pair<T, U>&obj) {o << "{" << obj.first << ", " << obj.second << "}"; return o;}
template <template <class tmp>  class T, class U> ostream &operator<<(ostream &o, const T<U> &obj) {o << "{"; for (auto itr = obj.begin(); itr != obj.end(); ++itr)o << (itr != obj.begin() ? ", " : "") << *itr; o << "}"; return o;}
void print(void) {cout << endl;}
template <class Head> void print(Head&& head) {cout << head;print();}
template <class Head, class... Tail> void print(Head&& head, Tail&&... tail) {cout << head << " ";print(forward<Tail>(tail)...);}
template <class T> void chmax(T& a, const T b){a=max<T>(a,b);}
template <class T> void chmin(T& a, const T b){a=min<T>(a,b);}
void YN(bool flg) {cout << ((flg) ? "YES" : "NO") << endl;}
void Yn(bool flg) {cout << ((flg) ? "Yes" : "No") << endl;}
void yn(bool flg) {cout << ((flg) ? "yes" : "no") << endl;}

int main() {
	int N,M; cin >> N >> M;
	ll mini = 1, maxi = 0, x = 0;
	V<V<P<int,ll>>> edge(N);
	V<P<int,ll>> node(N,{0,0});
	for(int i = 0; i < M; ++i){
		int u,v; ll s;
		cin >> u >> v >> s;
		u--,v--;
		edge[u].push_back({v,s});
		edge[v].push_back({u,s});
		chmax(maxi,s-1);
	}

	node[0] = {1,0};
	queue<int> q;
	q.push(0);
	while(q.size()){
		int from = q.front();
		q.pop();
		for(auto e:edge[from]){
			int to = e.first;
			ll cost = e.second;
			int type = -node[from].first;
			ll val = cost-node[from].second;

			if(node[to].first==0){
				node[to] = {type,val};
				if(node[to].first==-1) chmin(maxi,node[to].second - 1);
				if(node[to].first== 1) chmax(mini,1 - node[to].second);
				q.push(to);
			}
			else{
				if(type == node[to].first){
					corner(val != node[to].second,0);
				}
				else{
					ll a = val, b = node[to].second;
					if(type > node[to].first) swap(a,b);
					corner(a-b<=0||(a-b)%2,0);
					x = (a-b)/2;
					while(q.size())q.pop();
					break;
				}
			}
		}
	}

	corner(x==0,max(maxi-mini+1LL,0LL));

	for(int i = 0; i < N; ++i) node[i] = {0,0};
	node[0] = {1,x};
	q.push(0);

	while(q.size()){
		int from = q.front();
		q.pop();
		for(auto e:edge[from]){
			int to = e.first;
			ll cost = e.second;
			ll val = cost-node[from].second;

			if(node[to].first==0){
				node[to] = {1,val};
				q.push(to);
			}
			else{
				corner(val != node[to].second, 0);
			}
		}
	}
	cout << 1 << endl;
	return 0;
}


#include <cstdio>
#include <vector>
#include <utility>
#include <tuple>
#include <cstring>
#include <iostream>
using namespace std;

int N, M;
using Graph = vector< vector< pair<int, int> > >;

const int INF = 1 << 28;
bool is_bipartite = true, exist_solution = true;
int color[100010], value[100010], start_val = -INF;

void dfs(Graph &G, int cur, int par=-1, int verify=false) {
    for(auto e : G[cur]) {
        int to, val; tie(to, val) = e;
        if(to == par) continue;

        if(color[to] >= 0) {
            if(color[to] == color[cur]) {
                is_bipartite = false;

                int diff = (value[cur] + value[to]) - val;
                if(abs(diff) % 2) {
                    exist_solution = false;
                }
                else {
                    int chg_val;
                    if(color[cur] == 1) {
                        chg_val = 1 + diff / 2 * (-1);
                    }
                    else {
                        chg_val = 1 + diff / 2;
                    }

                    if(start_val == -INF) {
                        start_val = chg_val;
                    }
                    else {
                        if(start_val != chg_val || chg_val <= 0) {
                            exist_solution = false;
                        }
                    }
                }
            }
        }
        else {
            color[to] = 1 - color[cur];
            value[to] = val - value[cur];
            if(verify && value[to] <= 0) exist_solution = false;
            dfs(G, to, cur);
        }
    }
}

int main() {
    scanf("%d%d", &N, &M);

    Graph G(N);
    for(int i=0; i<M; i++) {
        int u, v, s; scanf("%d%d%d", &u, &v, &s);
        u--; v--;
        G[u].push_back(make_pair(v, s));
        G[v].push_back(make_pair(u, s));
    }

    memset(color, -1, sizeof(color));
    value[0] = color[0] = 1;
    dfs(G, 0, -1, false);

    if(is_bipartite) {
        // color[i] == 1 側について、どれだけ上げないと成立しないか
        // color[i] == 0 側について、どれだけ余裕があるか
        int m1 = 0, m2 = INF;
        for(int i=0; i<N; i++) {
            if(color[i] == 1) {
                m1 = max(m1, -value[i] + 1);
            }
            else {
                m2 = min(m2,  value[i] - 1);
            }
        }

        if(m2 < 0 || m1 > m2) {
            cout << 0 << endl;
        }
        else {
            cout << m2 - m1 + 1 << endl;
        }
    }
    else {
        memset(color, -1, sizeof(color));
        value[0] = start_val;
        color[0] = 1;
        dfs(G, 0, -1, true);

        cout << exist_solution << endl;
    }
    return 0;
}


#include<bits/stdc++.h>
typedef long long int ll;
using namespace std;
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    ll n,i,x,sum=0,summ,j;
    cin>>n;
    int a[n];
    for(i=0; i<n; i++){
        cin>>a[i];
        sum+=abs(a[i]-i-1);
    }
    x=ceil((double)sum/n);
    for(j=summ=0; j<n; j++){
            summ+=abs(a[j]-x-j-1);
    }
    sum=min(sum,summ);
    x*=(-1);
    for(j=summ=0; j<n; j++){
        summ+=abs(a[j]-x-j-1);
    }
    sum=min(sum,summ);
    cout<<sum<<endl;
    return 0;
}

Score : 200 points

Problem Statement

You are given an integer sequence A of length N.
Find the maximum absolute difference of two elements (with different indices) in A.

Constraints

2 \leq N \leq 100

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 maximum absolute difference of two elements (with different indices) in A.

Sample Input 1

4
1 4 6 3

Sample Output 1

5

The maximum absolute difference of two elements is A_3-A_1=6-1=5.

Sample Input 2

2
1000000000 1

Sample Output 2

999999999

Sample Input 3

5
1 1 1 1 1

Sample Output 3

0


#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    int n;
    cin>>n;
    int ar[n];
    for(int i=0; i<n; i++)
        cin>>ar[i];
     int big=0;
     int low=0;
     if(n==2)
     {
        big=ar[0];
        low=ar[1];
     }
     else{
    for(int i=0; i<n; i++)
    {
        if(ar[i]>ar[i+1]){
            big=ar[i];
            ar[i+1]=ar[i];}
        else
            big=ar[i+1];

        if(ar[i]<ar[i+1]){
            low=ar[i];
            ar[i+1]=ar[i];}
        else
            low=ar[i+1];
    }
     }
    cout<<abs(big-low)<<endl;
    return 0;
}


#include <stdio.h>
int main(void)
{
	int a, max = 1, min = 100000000,i;
	float c;
	scanf("%d", &a);
	for (i = 0; i < a; i++) {
		scanf("%f", &c);
		if (c > max)max = c;
		if (c < min) {
			min = c;
		}
	}
	printf("%d\n", max - min);
	return 0;
}


#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <iomanip>
#include <set>
using namespace std;

#define rep(i, s) for (int i = 0; i < s; ++i)
#define all(v) (v.begin(), v.end())
#define COUT(x) cout << #x << " = " << (x) << " (L" << __LINE__ << ")" << endl
#define EACH(i, s) for (__typeof__((s).begin()) i = (s).begin(); i != (s).end(); ++i)
#define VEC(a, n) vector<int>a(n)
#define PQ(a) priority_queue<int>a
#define PQmin(a) priority_queue< int, :vector<int>, greater<int> >a
#define PAIR pair<int, int>
/*
sort(sp.begin(), sp.end(), [](PAIR l, PAIR r){
        return l.first<r.first || (l.first==r.first && l.second > r.second);
        });
*/

typedef long long  ll;

#define EPS (1e-7)
#define INF (1e9)
#define PI (acos(-1))

template<class T> inline bool chmin(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template<class T> inline bool chmax(T& a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

int main() {
    int n;
    cin>>n;
    vector<int>a(n);
    for(int i=0;i<n;i++){
        int x;
        cin>>x;
        a.at(i)=x-(i+1);
    }
    double AVE=0;
    for(int i=0;i<n;i++){
        AVE+=a.at(i);
    }
    AVE/=n;
    int ans=1000000000;
    for(int i=-1000;i<=1000;i++){
        int SUM=0;
        for(int j=0;j<n;j++){
            SUM+=abs(a.at(j)-(int)AVE+i);
        }
        ans=min(ans,SUM);
    }
    cout<<ans<<endl;

    return 0;
}

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