#include <algorithm>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <vector>

using namespace std;

typedef long long ll;
// constexpr ll MOD = 998244353;
constexpr ll MOD = 1000000007;

// struct UnionFind {
//     vector<ll> par;
//     vector<ll> siz;

//     UnionFind(ll N): par(N), siz(N,1LL) {
//         for (ll i=0;i<N;i++) par[i] = i;
//     }

//     ll root(ll x) {
//         if (par[x] == x) return x;
//         else return par[x] = root(par[x]);
//     }

//     void unite(ll x, ll y) {
//         ll rx = root(x);
//         ll ry = root(y);
//         if (rx == ry) return;
//         par[rx] = ry;
//         siz[ry] += siz[rx];
//     }

//     bool same(ll x, ll y) {
//         ll rx = root(x);
//         ll ry = root(y);
//         return rx == ry;
//     }

//     ll size(ll x) {
//         return siz[root(x)];
//     }
// };

int main(void) {
    int N, v[100010];
    cin >> N;
    for (int i=0;i<N;i++) cin >> v[i];

    vector<int> O(100010,0),E(100010,0);
    for (int i=0;i<N;i+=2) O[v[i]]++;
    for (int i=1;i<N;i+=2) E[v[i]]++;

    multimap<int,int,greater<int>> Om, Em;
    Om.emplace(0,0), Em.emplace(0,0);
    for (int i=0;i<100010;i++) {
        if (O[i]) Om.emplace(O[i],i);
        if (E[i]) Em.emplace(E[i],i);
    } // first: count, second: number
    // for (auto itr: Om) {
    //     cout << itr.first << ": " << itr.second << endl;
    // }
    // for (auto itr: Em) {
    //     cout << itr.first << ": " << itr.second << endl;
    // }
    auto oitr = Om.begin(), eitr = Em.begin();
    bool flag = false;
    while (oitr->second == eitr->second) {
        oitr++; eitr++;
        flag = true;
        if (oitr == Om.end()) break;
    }
    if (oitr == Om.end()) {
        oitr = Om.begin(), eitr = Em.begin();
        eitr++;
    } else if (flag) {
        if (oitr->first < eitr->first) {
            oitr = Om.begin(), eitr = Em.begin();
            eitr++;
        } else {
            oitr = Om.begin(), eitr = Em.begin();
            oitr++;
        }
    }
    cout << N - oitr->first - eitr->first << 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 <bits/stdc++.h>
#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define INF 2e9
#define ALL(v) (v).begin(), (v).end()
using namespace std;
typedef long long ll;
ll GCD(ll a,ll b){return b?GCD(b,a%b):a;}
ll LCM(ll a,ll b){return (a*b)/GCD(a,b);}
int abs(int x){return x>0?x:-x;}

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

int main()
{
	int n;
	cin >> n;
	int a[n];
	map<int , int> m;
	REP(i, n){
		cin >> a[i];
		m[a[i]]++;
	}

	int max1 = 0, max2 = 0;

	if ((int)m.size() == 1){
		cout << n / 2 << endl;
		return 0;
	}

	int key;
	for (auto x : m){
		if (max1 < x.second){
			max1 = x.second;
			key = x.first;
		}
	}

	m.erase(key);

	for (auto x : m){
		if (max2 < x.second){
			max2 = x.second;
		}
	}

	cout << n - (max1 + max2) << endl;
}

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

Submitted source-code file size, in bytes.

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

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


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

#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define ALL(obj) (obj).begin(), (obj).end()
#define INF 1e9
typedef long long ll;

typedef pair<ll,ll> P;

int main() {
    int N; cin >> N;
    vector<P> coord(N);
    REP(i,N){
        ll x,y; cin >> x >> y;
        coord[i] = {x,y};
    }
    int p = (abs(coord[0].first) + abs(coord[0].second))%2;
    REP(i,N){
        if(p != (abs(coord[i].first) + abs(coord[i].second))%2){
            cout << -1 << endl;
            return 0;
        }
    }

    vector<ll> D(39);
    REP(i,39){
        D[i] = (1LL<<(38-i));
    }
    if(p%2 == 0) D.push_back(1);

    cout << D.size() << endl;
    REP(i,D.size()){
        cout << D[i];
        if(i!=D.size()-1) cout << " ";
    }
    cout << endl;

    REP(i,N){
        ll X = coord[i].first, Y = coord[i].second;
        ll x=0, y=0;
        REP(i,D.size()){
            ll d = D[i];
            ll dx = X-x, dy = Y-y;

            if(abs(dx) > abs(dy)){
                if(dx>0){
                    cout << "R";
                    x += d;
                }else{
                    cout << "L";
                    x -= d;
                }
            }else{
                if(dy>0){
                    cout << "U";
                    y += d;
                }else{
                    cout << "D";
                    y -= d;
                }
            }
        }
        cout << endl;
        //cout << "(" << x << ", " << y << ")" << endl;
    }

    return 0;
}

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;
int main()
{
	int n,maxx=0,cnt=0,chek1=0,chek2=0;
 int a[100001],x[100001]={};
 cin>>n;
	for(int i=0;i<n;i++) cin>>a[i];
 for(int i=0;i<n;i+=2){
        x[a[i]]++;
        if(x[a[i]]>maxx) maxx=x[a[i]],chek1=a[i];
    }
  int x1[100001]={};
  maxx=0;
	 for(int i=1;i<n;i+=2){
        x1[a[i]]++;
        if(x1[a[i]]>maxx && a[i]!=chek1) maxx=x1[a[i]],chek2=a[i];
    }
   for(int i=0;i<n;i+=2){
        if(a[i]!=chek1) cnt++;
    }
    for(int i=1;i<n;i+=2){
        if(a[i]!=chek2) cnt++;
    }
    cout<<cnt;
}


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 <iostream>
#include <limits.h>
using namespace std;

int main(void){

    int n, m;
    cin >> n >> m;

    long long prod, primes = 2, powers = 1, prime_p[100], prime_q[100];
    prod = m;

    for (int prfc_i = 1; prfc_i <= 100; prfc_i++) {
        prime_p[prfc_i] = prime_q[prfc_i] = 0;
    }

    while (prod >= primes) {
        while (prod % primes == 0) {
            if (prime_q[powers] > 0) prime_q[powers]++;
            else {
                prime_p[powers] = primes;
                prime_q[powers]++;
            }
            prod /= primes;
            if (prod % primes != 0) powers++;
        }
        primes++;
    }
    powers--;

//    for (int prfc_i = 1; prfc_i <= powers; prfc_i++) {
//        cout << prime_p[prfc_i] << " " << prime_q[prfc_i] << endl;
//    }

    long long cb_l, cb_r, comb = 1, ans = 1;
    for (int i = 1; i <= powers; i++) {
        cb_l = n + prime_q[i] - 1;
        cb_r = prime_q[i];
        if (cb_l < cb_r || cb_l < 0 || cb_r < 0) comb = 0;
        else {
	        for (long cb_i = 1; cb_i <= cb_r; cb_i++) {
		        comb *= (cb_l - cb_i + 1);
		        comb /= cb_i;
		        if (comb > 1000000007) comb %= 1000000007;
	        }
        }
        ans *= comb;
        if (ans > 1000000007) ans %= 1000000007;
        comb = 1;
    }

    cout << ans;

}

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 <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
typedef long long int ll;

int main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n,x;
  cin >> n>>x;
  int input, count=0;
  vector<int> a(n);
  rep(i, n) {
    cin >> a[i];
  }
  sort(a.begin(), a.end());
  rep(i,n) {
	if(x >= a[i]) {
      x-=a[i];
      count++;
    }else{
      cout << count << endl;
      return 0;
    }
  }
  if(x > 0 && count > 0) count--;
  cout << count << endl;
}

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.


/*
    問題をよく読もう！
    論理的に考えよう！
    サンプルを確認しよう!
    絶対に諦めるな！
    工夫をしろ！
    配列は少し多めにとっておく

    Twitterは終わるまでログアウト！
    （間違えて解法をツイートしてはいけないから）

*/
//include
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<functional>
#include<assert.h>
#include<numeric>
#include<stdio.h>
#include<cstring>
//namespace
using namespace std;
//繰り返し
#define REP(i, m, n) for(int i=(int)m; i<(int)n; ++i)
#define rep(i, n) REP(i, 0, n)
//イテレータ
#define all_range(C) begin(C), end(C)
//簡略化
typedef long long ll;
typedef pair<int,int> pint;
typedef pair<ll,int> pli;
typedef pair<string,int> pst;

const int inf = 1e9+7;
const ll longinf = 1LL<<60;
const ll mod = 1e9+7;
//最大最小
template<typename T1, typename T2> inline void chmin(T1 &a, T2 b) {if(a>b) a=b;}
template<typename T1, typename T2> inline void chmax(T1 &a, T2 b) {if(a<b) a=b;}

//関数

//最大公約数を求める
ll my_gcd(ll x, ll y) {
  ll r;

  while(y!=0) {
    r = x%y;
    x = y;
    y = r;
  }

  return x;
}

//最小公約数を求める
ll my_lcm(ll x, ll y) {

  return (x*y)/my_gcd(x,y);
}

//xのy乗を求める ※参考：10^18乗まで
ll my_pow(ll x, ll y) {
  ll sum = 1;

  while(y>0) {
    sum *= x;
    --y;
  }

  return sum;
}

/*考えを書くスペース
  累乗和で解く

  ・総和を求める
  ・取り消すところの一つ先を見る
*/
//main.cpp----------------------------
#define max_n 100

void solve();

ll N, x;
ll a[max_n+1];

int main() {
  cin >> N >> x;
  rep(i, N) cin >> a[i];

  solve();

  return 0;
}

void solve() {

  sort(a, a+N);

  int i = 0, cnt = 0;
  while(i<N-1&&x>=a[i]) {
    x -= a[i];
    ++cnt;
    ++i;
  }

  if(x==a[N-1]) ++cnt;

  cout << cnt << endl;
}


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

int a[200010];

int main() {
	ios::sync_with_stdio(false);
	long long n,x;
	cin >> n >> x;
	long long ans = 0;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
		ans += a[i];
	}
	ans = ans*5+x*n;
	int cur = n;
	while (cur) {
		if (cur == 1) {
			ans += x;
			break;
		}
		int cnt = 2;
		while (cur-cnt && a[cur-cnt]*(cnt-1)*2 < x) {
			ans += a[cur-cnt]*(cnt-1)*2;
			cnt++;
		}
		ans += x;
		cur -= cnt;
	}
	cout << ans << "\n";
}

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


Score : 1100 points

Problem Statement

You are given an integer N.

Construct any one N-by-N matrix a that satisfies the conditions below. It can be proved that a solution always exists under the constraints of this problem.

1 \leq a_{i,j} \leq 10^{15}

a_{i,j} are pairwise distinct integers.

There exists a positive integer m such that the following holds: Let x and y be two elements of the matrix that are vertically or horizontally adjacent. Then, {\rm max}(x,y) {\rm mod} {\rm min}(x,y) is always m.

Constraints

2 \leq N \leq 500

Input

Input is given from Standard Input in the following format:

N

Output

Print your solution in the following format:

a_{1,1} ... a_{1,N}
:
a_{N,1} ... a_{N,N}

Sample Input 1

2

Sample Output 1

4 7
23 10

For any two elements x and y that are vertically or horizontally adjacent, {\rm max}(x,y) {\rm mod} {\rm min}(x,y) is always 3.


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

const int N = 100;
const int INF = 1<<30;

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

struct edge {
	int v, next;
} ;

struct graph {

	int front[N], tot, fa[N], checked[N], degree[N]; edge e[N*N];

	inline void clear() {
		memset( checked, 0, sizeof( checked ) );
		memset( degree, 0, sizeof( degree ) );
		memset( front, 0, sizeof( front ) ); tot = 0;
	}

	inline void add_edge( int u, int v ) {
		e[++tot] = { v, front[u] }; front[u] = tot; degree[v] ++;
	}

	inline void add_edge2( int u, int v ) {
		add_edge( u, v ); add_edge( v, u );
	}

	inline void calc_fa( int u, int anc )
	{
//		printf( "%d %d\n", u, fa[u] );
		for( int i = front[u]; i; i = e[i].next )
			if( e[i].v != fa[u] && e[i].v != anc ) fa[e[i].v] = u, calc_fa( e[i].v, anc );
	}

	inline bool check( int u, int anc )
	{
		if( checked[u] && checked[u] != anc )
			return true;
		if( checked[u] == anc ) return false;

		checked[u] = anc;

		for( int i = front[u]; i; i = e[i].next )
			if( !check( e[i].v, anc ) ) return false;
		return true;
	}

} A, B, G;

int n; bool visited[N];

void find( int u, int fa )
{
	if( visited[u] ) return;
	visited[u] = true;

	priority_queue <int> q;

	for( int i = A.front[u]; i; i = A.e[i].next )
		if( A.e[i].v != fa ) q.push( A.e[i].v );

	for( int i = B.front[u]; i; i = B.e[i].next )
		if( B.e[i].v != fa ) q.push( B.e[i].v );

	int last = 0;
	while( !q.empty() )
	{
		if( q.top() == last )
			find( q.top(), u );

		last = q.top(); q.pop();
	}
}

inline int calc_ans( int k )
{
	int ans = n;

	memset( visited, false, sizeof( visited ) );

	find( k, 0 );

	for( int i = 1; i <= n; i ++ )
		if( visited[i] ) ans --;

	memset( A.fa, 0, sizeof( A.fa ) ); A.calc_fa( k, k );
	memset( B.fa, 0, sizeof( B.fa ) ); B.calc_fa( k, k );

	G.clear();

	for( int i = 1; i <= n; i ++ )
	{
		if( !visited[i] && !visited[ A.fa[i] ] )
			G.add_edge( i, A.fa[i] );
		if( !visited[i] && !visited[ B.fa[i] ] )
			G.add_edge( B.fa[i], i );
	}

	for( int i = 1; i <= n; i ++ )
		if( !G.check( i, i ) ) return INF;

	return ans;
}

inline void solve()
{
	n = read(); int ans = INF;

	A.clear(); B.clear();

	for( int i = 1; i < n; i ++ )
		A.add_edge2( read(), read() );

	for( int i = 1; i < n; i ++ )
		B.add_edge2( read(), read() );

	for( int i = 1; i <= n; i ++ )
		ans = min( ans, calc_ans( i ) );

	for( int i = 1; i <= n; i ++ )
	{
		if( A.degree[i] != 1 ) continue;
		int old = A.e[ A.front[i] ].v;

		for( int j = 1; j <= n; j ++ )
		{
			if( j == i || j == old )
				continue;

			A.e[ A.front[i] ].v = j;
			calc_ans( i );
		}

		A.e[ A.front[i] ].v = old;
	}

	if( ans == INF ) ans = -1;
	printf( "%d\n", ans );
}

int main()
{
	int ttt = read();

	while( ttt -- )
		solve();

	return 0;
}

Score : 1900 points

Problem Statement

Snuke has found two trees A and B, each with N vertices numbered 1 to N.
The i-th edge of A connects Vertex a_i and b_i, and the j-th edge of B connects Vertex c_j and d_j.
Also, all vertices of A are initially painted white.

Snuke would like to perform the following operation on A zero or more times so that A coincides with B:

Choose a leaf vertex that is painted white. (Let this vertex be v.)

Remove the edge incident to v, and add a new edge that connects v to another vertex.

Paint v black.

Determine if A can be made to coincide with B, ignoring color. If the answer is yes, find the minimum number of operations required.

You are given T cases of this kind. Find the answer for each of them.

Constraints

1 \leq T \leq 20

3 \leq N \leq 50

1 \leq a_i,b_i,c_i,d_i \leq N

All given graphs are trees.

Input

Input is given from Standard Input in the following format:

T
case_1
:
case_{T}

Each case is given in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 d_1
:
c_{N-1} d_{N-1}

Output

For each case, if A can be made to coincide with B ignoring color, print the minimum number of operations required, and print -1 if it cannot.

Sample Input 1

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

Sample Output 1

1
-1

The graph in each case is shown below.

In case 1, A can be made to coincide with B by choosing Vertex 1, removing the edge connecting 1 and 2, and adding an edge connecting 1 and 3. Note that Vertex 2 is not a leaf vertex and thus cannot be chosen.

Sample Input 2

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

Sample Output 2

6
0
7

A may coincide with B from the beginning.


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

int main(){
  int h,w;
  cin>>h>>w;
  vector<vector<int>> c(h,vector<int>(w));
  vector<pair<int,P>> coin;
  rep(i,h){
    rep(j,w) cin>>c[i][j];
    if(i%2==1) sort(c[i].begin(),c[i].end());
  }
  rep(i,h)rep(j,w){
    if(i%2==0) coin.push_back(make_pair(c[i][j],make_pair(i+1,j+1)));
    else coin.push_back(make_pair(c[i][j],make_pair(i+1,w-j)));
  }
  vector<pair<P,P>> ans;
  rep(i,h*w-1){
    if(coin[i].first%2 == 1){
      coin[i+1].first++;
      ans.push_back(make_pair(make_pair(coin[i].second.first,coin[i].second.second),make_pair(coin[i+1].second.first,coin[i+1].second.second)));
    }
  }
  cout<<ans.size()<<endl;
  for(auto x : ans){
    cout<<x.first.first<<" "<<x.first.second<<" "<<x.second.first<<" "<<x.second.second<<endl;
  }
}

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 <bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < n; i++)
#define FOR(i, a, b) for(int i = a; i < b; i++)
using namespace std;

const int MAX_H = 510;

int main(){
    int H, W;  cin >> H >> W;
    int a[MAX_H][MAX_H] = {0};
    FOR(i, 1, H + 1){
        FOR(j, 1, W + 1){
            cin >> a[i][j];
        }
    }

    int cnt = 0;
    vector<vector<int>> ans;
    FOR(h, 1, H + 1){
        FOR(w, 1, W + 1){
            vector<int> tmp;
            if(a[h][w] % 2 == 1 && !(h == H && w == W)){
                cnt++;
                tmp.push_back(h);
                tmp.push_back(w);
                if(w + 1 <= W && a[h][w+1] % 2 == 1){
                    a[h][w+1]++;
                    tmp.push_back(h);
                    tmp.push_back(w+1);
                }else if(h + 1 <= H && a[h+1][w] % 2 == 1){
                    a[h+1][w]++;
                    tmp.push_back(h+1);
                    tmp.push_back(w);
                }else if(w + 1 <= W){
                    a[h][w+1]++;
                    tmp.push_back(h);
                    tmp.push_back(w+1);
                }else if(h + 1 <= H){
                    a[h+1][w]++;
                    tmp.push_back(h+1);
                    tmp.push_back(w);
                }
                ans.push_back(tmp);
            }
        }
    }
    cout << cnt << endl;

    rep(i, ans.size()){
        rep(j, 4){
            cout << ans[i][j];
            if(j != 3) cout << " ";
        }
        cout << endl;
    }
}


#include<iostream>

using namespace std;

int main(void) {
	int h, w;
	int n = 0;
	cin >> h >> w;
	int a[h][w];
	int AftermoveLogX[w];
	int AftermoveLogY[h];
	int BeforemoveLogX[w];
	int BeforemoveLogY[h];
	for (int i = 0; i < h; i++) {
		for (int j = 0; j < w; j++) {
			cin >> a[i][j];
		}
	}
	int moveindex;
	moveindex = 0;
	for (int i = 0; i < h - 1; i++) {
		for (int j = 0; j < w; j++) {
			if (a[i][j] % 2 == 1) {
				a[i + 1][j] += 1;
				a[i][j]--;
				n++;
				BeforemoveLogX[moveindex] = j + 1;
				BeforemoveLogY[moveindex] = i + 1;
				AftermoveLogX[moveindex] = j + 1;
				AftermoveLogY[moveindex] = i + 2;
				moveindex++;
			}
		}
	}

	for (int i = 0; i < w-1; i++) {
		if (a[h-1][i] % 2 == 1) {
			a[h-1][i + 1]++;
			a[h-1][i]--;
			BeforemoveLogX[moveindex] = i + 1;
			BeforemoveLogY[moveindex] = h;
			AftermoveLogX[moveindex] = i + 2;
			AftermoveLogY[moveindex] = h;
			moveindex++;
			n++;
		}
	}
	cout << n << endl;

	for (int i = 0; i < moveindex; i++) {
		cout << BeforemoveLogY[i] << " " << BeforemoveLogX[i] << " ";
		cout << AftermoveLogY[i] << " " << AftermoveLogX[i] << endl;
	}
	return 0;

}


#include <iostream>
using namespace std;

int main(){
    int x1, x2, y1, y2;
    cin >> x1 >> y1 >> x2 >> y2;

    int dx = x2 - x1;
    int dy = y2 - y1;
    int x3 = x2 - dy;
    int y3 = y2 + dx;
    int x4 = x3 - dx;
    int y4 = y3 - dy;
    cout << x3 << " " << y3 << " " << x4 << " " << y4 << endl;

    return 0;
}

Score : 200 points

Problem Statement

There is a square in the xy-plane. The coordinates of its four vertices are (x_1,y_1),(x_2,y_2),(x_3,y_3) and (x_4,y_4) in counter-clockwise order.
(Assume that the positive x-axis points right, and the positive y-axis points up.)

Takahashi remembers (x_1,y_1) and (x_2,y_2), but he has forgot (x_3,y_3) and (x_4,y_4).

Given x_1,x_2,y_1,y_2, restore x_3,y_3,x_4,y_4. It can be shown that x_3,y_3,x_4 and y_4 uniquely exist and have integer values.

Constraints

|x_1|,|y_1|,|x_2|,|y_2| \leq 100

(x_1,y_1) ≠ (x_2,y_2)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

x_1 y_1 x_2 y_2

Output

Print x_3,y_3,x_4 and y_4 as integers, in this order.

Sample Input 1

0 0 0 1

Sample Output 1

-1 1 -1 0

(0,0),(0,1),(-1,1),(-1,0) is the four vertices of a square in counter-clockwise order.
Note that (x_3,y_3)=(1,1),(x_4,y_4)=(1,0) is not accepted, as the vertices are in clockwise order.

Sample Input 2

2 3 6 6

Sample Output 2

3 10 -1 7

Sample Input 3

31 -41 -59 26

Sample Output 3

-126 -64 -36 -131


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define all(x) x.begin(),x.end()
#define pll  pair <long long,long long>
#define ss second
#define ff first
#define inf 9223372036854775807
#define maa 1000000007
#define ld long double
#define fast  ios_base::sync_with_stdio(false);cin.tie(NULL);
#define bug(x) cout << #x <<": " << x << '\n';
const ll N=3501 ;
int main()
{
   fast ;
   ll n,k ;
   cin>>n>>k ;
   ll ans=0 ;
   for(ll a=0;a<k;a++)
   {
       ll x=(n-a)/k ;
       if(x>=0)
       {
           ll b=k-a ;
           b%=k ;

           ll y=(n-b)/k ;
           if(y>=0)
           {
               if((b+b)%k==0)
               {
                   if(a!=0)
                   ans+=(x+1)*(y+1)*(y+1) ;
                   else
                    ans+=x*y*y ;

               }
           }
       }
   }
   cout<<ans ;

}

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;
#define inf 1000000000
#define INF 1000000000000000
#define ll long long
#define ull unsigned long long
#define M 998244353
#define P pair<int,int>
#define PLL pair<ll,ll>
#define FOR(i,m,n) for(int i=(int)m;i<(int)n;i++)
#define RFOR(i,m,n) for(int i=(int)m;i>=(int)n;i--)
#define rep(i,n) FOR(i,0,n)
#define rrep(i,n) RFOR(i,n,0)
#define all(a) a.begin(),a.end()
#define IN(a,n) rep(i,n){ cin>>a[i]; }
const int vx[4] = {0,1,0,-1};
const int vy[4] = {1,0,-1,0};
#define PI 3.14159265
#define F first
#define S second
#define PB push_back
#define EB emplace_back
#define int ll
void init(){
  cin.tie(0);
  ios::sync_with_stdio(false);
}

int fac[310000];

int inv(int x){
  if(x==1) return 1;
  return (M-M/x)*inv(M%x)%M;
}

int comb(int n,int k){
  int x=(fac[k]*fac[n-k])%M;
  return (fac[n]*inv(x))%M;
}

int fac_init(int n){
  fac[0]=1;
  FOR(i,1,n+1){
    fac[i]=fac[i-1]*i;
    fac[i]%=M;
  }
}

main(){

  int n,k;
  cin>>k>>n;
  fac_init(100000);

  FOR(i,2,2*k+1){
    int res=0;
    int q=i;
    if(q>k+1) q=(k+1)*2-q;
    int a=q/2;
    rep(i,a+1){
      if(!(k-a+n-i-1>=0&&n-i>=0)) continue;
      if(a<i||k-a-n-i-1<n-i) continue;

      int t=comb(a,i)*comb(k-a+n-i-1,n-i)%M;
      res+=t;
      res%=M;
    }

    cout<<res<<endl;
  }

}

Score : 700 points

Problem Statement

Takahashi throws N dice, each having K sides with all integers from 1 to K. The dice are NOT pairwise distinguishable.
For each i=2,3,...,2K, find the following value modulo 998244353:

The number of combinations of N sides shown by the dice such that the sum of no two different sides is i.

Note that the dice are NOT distinguishable, that is, two combinations are considered different when there exists an integer k such that the number of dice showing k is different in those two.

Constraints

1 \leq K \leq 2000

2 \leq N \leq 2000

K and N are integers.

Input

Input is given from Standard Input in the following format:

K N

Output

Print 2K-1 integers. The t-th of them (1\leq t\leq 2K-1) should be the answer for i=t+1.

Sample Input 1

3 3

Sample Output 1

7
7
4
7
7

For i=2, the combinations (1,2,2),(1,2,3),(1,3,3),(2,2,2),(2,2,3),(2,3,3),(3,3,3) satisfy the condition, so the answer is 7.

For i=3, the combinations (1,1,1),(1,1,3),(1,3,3),(2,2,2),(2,2,3),(2,3,3),(3,3,3) satisfy the condition, so the answer is 7.

For i=4, the combinations (1,1,1),(1,1,2),(2,3,3),(3,3,3) satisfy the condition, so the answer is 4.

Sample Input 2

4 5

Sample Output 2

36
36
20
20
20
36
36

Sample Input 3

6 1000

Sample Output 3

149393349
149393349
668669001
668669001
4000002
4000002
4000002
668669001
668669001
149393349
149393349


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

int main(){
  int N, i;
  cin >> N >> i;
  cout << N - i + 1 << endl;
}

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;
int main()
{
  int h, w;
  cin >> h >> w;
  vector<bool> row(h, false);
  vector<bool> col(w, false);
  vector<vector<char>> vec(h, vector<char>(w));
  for (int i = 0; i < h; i++)
  {
    for (int j = 0; j < w; j++)
    {
      cin >> vec.at(i).at(j);
    }
  }

  for (int i = 0; i < h; i++)
  {
    for (int j = 0; j < w; j++)
    {
      if (vec.at(i).at(j) == '#')
      {
        row.at(i) = true;
        col.at(j) = true;
      }
    }
  }
  for (int i = 0; i < h; i++)
  {
    if (row.at(i))
    {
      for (int j = 0; j < w; j++)
      {
        if (col.at(j))
        {
          cout << vec.at(i).at(j);
        }
      }
      cout << endl;
    }
  }
}

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;
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> l_l;
typedef vector<ll> vel;
typedef vector<int> vei;
typedef vector<char> vec;
typedef vector<bool> veb;
typedef vector<string> ves;
typedef vector<vector<int>> ve_vei;
typedef vector<vector<char>> ve_vec;
typedef vector<vector<string>> ve_ves;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep1(i,n) for(int i=1;i<(int)(n);i++)
#define rep2(i,n) for(int i=2;i<(int)(n);i++)
#define fs first
#define sc second
#define pub push_back
#define pob pop_back
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define maxel(a) max_element(all(a))
#define acc accumulate
#define EPS (1e-7)
#define INF (1e9)
#define PI (acos(-1))
#define mod (1000000007)

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

    int H,W; cin >> H >> W;
    ve_vec a(H,vec(W));
    rep(i,H) rep(j,W) cin >> a[i][j];

    rep(i,H) {
        rep(j,W) {
            bool check1 = false;
            bool check2 = false;
            rep(k,H) {
                if(a[k][j] == '#') {
                    check1 = true;
                    break;
                }
            }
            rep(k,W) {
                if(a[i][k] == '#') {
                    check2 = true;
                    break;
                }
            }
            if(check1 and check2) cout << a[i][j];
            if(j == W-1 and (check1 and check2)) cout << endl;
        }
    }
    cout << endl;
    return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define ll long long
#define ld long double
#define pb push_back
#define all(x) (x).begin(), (x).end()
template <typename T> using ord_set = tree <T, null_type, less <T>, rb_tree_tag, tree_order_statistics_node_update>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int N = 2e5 + 123;
int n, a[N], b[N], p[N], f[N];

void upd(int x, int y) {
	for (; x <= 2 * n; x |= (x + 1))
		f[x] += y;
}

int getsum(int x) {
	int res = 0;
	for (; x >= 0; x = (x & (x + 1)) - 1)
		res += f[x];
	return res;
}

ll get(int x) {
	for (int i = 1; i <= n; i++) {
		if (a[i] <= x) b[i] = 1;
		else b[i] = -1;
	}
	upd(n, 1);
	ll res = 0;
	for (int i = 1; i <= n; i++) {
		p[i] = p[i - 1] + b[i];
		res += getsum(p[i] + n - 1);
		upd(p[i] + n, 1);
	}
	upd(n, -1);
	for (int i = 1; i <= n; i++)
		upd(p[i] + n, -1);
	return res;
}

int main() {
	ios_base::sync_with_stdio(false), cin.tie(NULL);
	#ifdef LOCAL
		freopen("input.txt", "r", stdin);
	#endif

	cin >> n;
	for (int i = 1; i <= n; i++) cin >> a[i];
	int l = 0, r = 1e9 + 123;
	ll k = (ll)(n * (n + 1)) / 2;
	while (l < r - 1) {
		int mid = l + r >> 1;
		if (get(mid) >= k / 2 + 1)
			r = mid;
		else
			l = mid;
	}
	cout << r;
}

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>
using namespace std;

typedef long long ll;
const int maxn = 1e5 + 5;

struct num
{
	ll t;
	int a;
}m[maxn];

bool cmp(num x, num y)
{
	return x.a < y.a;
}

int main()
{
	int n;	cin >> n;
	for(int i = 0; i < n; i ++)
		cin >> m[i].a;
	ll l = 0, r = n - 1;
	ll tar = 0;
	while(l <= r)
	{
		m[l].t = m[r].t = 2 * l + 1;
		tar += m[l].t;
		if(l != r)	tar += m[r].t;
		l ++;	r --;
	}
	if(tar % 2)	tar += 1;
	tar /= 2;
	sort(m, m + n, cmp);
	ll cnt = 0;
	for(int i = 0; i < n; i ++)
	{
		cnt += m[i].t;
		if(cnt >= tar)
		{
			cout << m[i].a << endl;
			break;
		}
	}
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for (int i = (a); i <= (b); ++ i)
#define rrp(i,a,b) for (int i = (a); i >= (b); -- i)
#define gc() getchar()
#define fir first
#define sec second
typedef pair<int,int> pii;
typedef long double db;
typedef long long ll;
template <typename tp>
inline void read(tp& x) {
  x = 0; char tmp; bool key = 0;
  for (tmp = gc(); !isdigit(tmp); tmp = gc())
    key = (tmp == '-');
  for (; isdigit(tmp); tmp = gc())
    x = (x << 3) + (x << 1) + (tmp ^ '0');
  if (key) x = -x;
}
template <typename tp>
inline void ckmn(tp& x,tp y) {
  x = x < y ? x : y;
}
template <typename tp>
inline void ckmx(tp& x,tp y) {
  x = x < y ? y : x;
}

const int MOD = (int)(1e9 + 7);
inline void Add(int& x,int y) {
  x = x + y >= MOD ? x + y - MOD : x + y;
}
inline void Sub(int& x,int y) {
  x = x - y < 0 ? x - y + MOD : x - y;
}
int power(int a,int b) {
  int ret = 1;
  while (b) {
    if (b&1) ret = 1ll * ret * a % MOD;
    a = 1ll * a * a % MOD;
    b >>= 1;
  }
  return ret;
}

const int N = 5010;
struct edge {
  int la,b;
} con[N << 1];
int tot, fir[N];
void add_edge(int from,int to) {
  con[++tot] = (edge) {fir[from], to};
  fir[from] = tot;
}
int n;
int dp[N][N], sz[N], jc[N], ijc[N], ipw2[N], tmp[N];
int calc(int x) {
  int ret = 1ll * jc[x] * ijc[x / 2] % MOD;
  ret = 1ll * ret * ipw2[x / 2] % MOD;
  return ret;
}
void dfs(int pos,int fa) {
  dp[pos][1] = 1;
  sz[pos] = 1;
  for (int i = fir[pos]; i; i = con[i].la) {
    if (con[i].b == fa) continue;
    dfs(con[i].b, pos);
    memset(tmp, 0, sizeof tmp);
    rep (a, 0, sz[pos]) rep (b, 0, sz[con[i].b])
      Add(tmp[a + b], 1ll * dp[pos][a] * dp[con[i].b][b] % MOD);
    sz[pos] += sz[con[i].b];
    rep (a, 0, sz[pos]) dp[pos][a] = tmp[a];
  }
  rep (a, 1, sz[pos]) if (a % 2 == 0)
    Sub(dp[pos][0], 1ll * calc(a) * dp[pos][a] % MOD);
}
int main() {
  int x,y;
  read(n);
  rep (i, 1, n-1) {
    read(x), read(y);
    add_edge(x, y);
    add_edge(y, x);
  }
  jc[0] = 1;
  rep (i, 1, n) jc[i] = 1ll * jc[i-1] * i % MOD;
  ijc[n] = power(jc[n], MOD - 2);
  ipw2[0] = 1;
  ipw2[1] = power(2, MOD - 2);
  rep (i, 2, n) ipw2[i] = 1ll * ipw2[1] * ipw2[i-1] % MOD;
  rrp (i, n-1, 0) ijc[i] = 1ll * ijc[i+1] * (i+1) % MOD;
  dfs(1, 0);
  int ans = MOD - dp[1][0];
  ans = (ans % MOD + MOD) % MOD;
  cout << ans << endl;
  return 0;
}

Score : 900 points

Problem Statement

Let N be an even number.

There is a tree with N vertices.
The vertices are numbered 1, 2, ..., N.
For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.

Snuke would like to decorate the tree with ribbons, as follows.

First, he will divide the N vertices into N / 2 pairs.
Here, each vertex must belong to exactly one pair.
Then, for each pair (u, v), put a ribbon through all the edges contained in the shortest path between u and v.

Snuke is trying to divide the vertices into pairs so that the following condition is satisfied: "for every edge, there is at least one ribbon going through it."
How many ways are there to divide the vertices into pairs, satisfying this condition?
Find the count modulo 10^9 + 7.
Here, two ways to divide the vertices into pairs are considered different when there is a pair that is contained in one of the two ways but not in the other.

Constraints

N is an even number.

2 \leq N \leq 5000

1 \leq x_i, y_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of the ways to divide the vertices into pairs, satisfying the condition, modulo 10^9 + 7.

Sample Input 1

4
1 2
2 3
3 4

Sample Output 1

2

There are three possible ways to divide the vertices into pairs, as shown below, and two satisfy the condition: the middle one and the right one.

Sample Input 2

4
1 2
1 3
1 4

Sample Output 2

3

There are three possible ways to divide the vertices into pairs, as shown below, and all of them satisfy the condition.

Sample Input 3

6
1 2
1 3
3 4
1 5
5 6

Sample Output 3

10

Sample Input 4

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

Sample Output 4

672


#include<iostream>
using namespace std;

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

  cout << (A-1)*(B-1) << endl;

  return 0;
}

Score: 100 points

Problem Statement

There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.)

What is the area of this yard excluding the roads? Find it.

Note

It can be proved that the positions of the roads do not affect the area.

Constraints

A is an integer between 2 and 100 (inclusive).

B is an integer between 2 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

A B

Output

Print the area of this yard excluding the roads (in square yards).

Sample Input 1

2 2

Sample Output 1

1

In this case, the area is 1 square yard.

Sample Input 2

5 7

Sample Output 2

24

In this case, the area is 24 square yards.


Score: 200 points

Problem Statement

The number 105 is quite special - it is odd but still it has eight divisors.
Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?

Constraints

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

Input

Input is given from Standard Input in the following format:

N

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

Among the numbers between 1 and 105, the only number that is odd and has exactly eight divisors is 105.

Sample Input 2

7

Sample Output 2

0

1 has one divisor. 3, 5 and 7 are all prime and have two divisors. Thus, there is no number that satisfies the condition.


#include <bits/stdc++.h>
using namespace std;
#define itn int
#define nibu(K,x) binary_search(K.begin(),K.end(),x)
#define rep(i,n) for(ll i=0;i<n;i++)
#define all(x) x.begin(),x.end()
#define sz(x) x.size()
#define pb push_back
#define mp make_pair
#define Fi first
#define Se second
#define out(x) cout<<x<<endl
#define put(x) out(x)
#define in(x) cin>>x
#define maxx(a,b,c) max(a,max(b,c))
#define minn(a,b,c) min(a,min(b,c))
using ll = long long;
using vl = vector<ll>;
using vs = vector<string>;
const double pi = 3.14159265358979;
const ll mod = 1000000007;

int main() {
 string S;
  in(S);
  ll K;
  in(K);
  ll N =  sz(S);
  ll a=-100;
  rep(i,N){
   if(S[i]!='1'){
     a=i;
     break;
   }
   }
  if(a<0) out(1);
 else if(K<=a) out(1);
  else out(S[a]);
}

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 <iostream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <queue>
#include <stack>
#include <vector>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <set>
#include <deque>
#include <utility>

int hit[504][200004];
int sum[504][200004];
int main() {
  int N, M, Q;
  scanf("%d", &N);
  scanf("%d", &M);
  scanf("%d", &Q);
  std::vector<int > L(M), R(M), p(Q), q(Q);
  for (int i=0; i<M; i++){
    scanf("%d", &L[i]);
    scanf("%d", &R[i]);
  }
  for (int i=0; i<Q; i++){
    scanf("%d", &p[i]);
    scanf("%d", &q[i]);
  }
  for (int i=0; i<M;i++){
    hit[L[i]][R[i]]++;
  }
  for (int i=1; i<=N; i++){
    for (int j=1; j<=N; j++){
      sum[i][j]=hit[i][j]-sum[i-1][j-1]+sum[i][j-1]+sum[i-1][j];
    }
  }
  for (int i=0; i<Q; i++){
    int ans = sum[q[i]][q[i]]-sum[p[i]-1][q[i]]-sum[q[i]][p[i]-1]+sum[p[i]-1][p[i]-1];
    std::cout << ans << std::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<bits/stdc++.h>
using namespace std;
int main(){
  int n,k;
  cin>>n>>k;
  if(n%k==0)
    cout<<0<<endl;
  else
    cout<<1<<endl;
  }

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<bits/stdc++.h>
using namespace std;
map<int,int> p={{0,1}};
long long s,n,m,a,b;
int main() {
	cin>>n>>m;
	for(int i=0;i<n;i++){
		cin>>a;
		b+=a;
		s+=p[b%=m]++;
	}
	cout<<s;
	return 0;
}

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 <iostream>
#include <unordered_map>

int main()
{
    int n, m;
    int sum = 0;
    std::unordered_map<int, int> countMap;

    std::cin >> n >> m;

    for (int i = 0; i < n; i++) {
        int a;
        std::cin >> a;
        sum = (sum + a) % m;
        auto itr = countMap.find(sum);
        if (itr != countMap.end()) {
            countMap[sum]++;
        } else {
            countMap[sum] = 1;
        }
    }

    long long ans = 0;
    for (auto itr = countMap.begin(); itr != countMap.end(); ++itr) {
        long long x = itr->second;
        ans += x * (x-1) / 2;
        if (itr->first == 0) {
            ans += x;
        }
    }

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


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

int main() {

  int r;
  cin >> r;

  if (r < 1200) cout << "ABC" << endl;
  else if (r < 2800) cout << "ARC" << endl;
  else cout << "AGC" << endl;
}

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


#ifdef LOCAL
    #define _GLIBCXX_DEBUG
    #define __clock__
#else
    #pragma GCC optimize("Ofast")
#endif
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using VI = vector<ll>;
using VV = vector<VI>;
using VS = vector<string>;
using PII = pair<ll, ll>;

// tourist set
template <typename A, typename B>
string to_string(pair<A, B> p);

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p);

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p);

string to_string(const string& s) {
  return '"' + s + '"';
}

string to_string(const char* s) {
  return to_string((string) s);
}

string to_string(bool b) {
  return (b ? "true" : "false");
}

string to_string(vector<bool> v) {
  bool first = true;
  string res = "{";
  for (int i = 0; i < static_cast<int>(v.size()); i++) {
    if (!first) {
      res += ", ";
    }
    first = false;
    res += to_string(v[i]);
  }
  res += "}";
  return res;
}

template <size_t N>
string to_string(bitset<N> v) {
  string res = "";
  for (size_t i = 0; i < N; i++) {
    res += static_cast<char>('0' + v[i]);
  }
  return res;
}

template <typename A>
string to_string(A v) {
  bool first = true;
  string res = "{";
  for (const auto &x : v) {
    if (!first) {
      res += ", ";
    }
    first = false;
    res += to_string(x);
  }
  res += "}";
  return res;
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
  return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A, typename B, typename C>
string to_string(tuple<A, B, C> p) {
  return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")";
}

template <typename A, typename B, typename C, typename D>
string to_string(tuple<A, B, C, D> p) {
  return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}

void debug_out() { cerr << '\n'; }

template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
  cerr << " " << to_string(H);
  debug_out(T...);
}

#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif
// tourist set end

template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }

#define FOR(i,a,b) for(ll i=(a);i<(b);++i)
#define rep(i,b) FOR(i, 0, b)
#define ALL(v) (v).begin(), (v).end()
#define p(s) cout<<(s)<<'\n'
#define p2(s, t) cout << (s) << " " << (t) << '\n'
#define br() p("")
#define pn(s) cout << (#s) << " " << (s) << '\n'
#define SZ(x) ((int)(x).size())
#define SORT(A) sort(ALL(A))
#define RSORT(A) sort(ALL(A), greater<ll>())
#define MP make_pair
#define p_yes() p("AC")
#define p_no() p("WA")

ll SUM(VI& V){
  return accumulate(ALL(V), 0LL);
}

ll MIN(VI& V){return *min_element(ALL(V));}
ll MAX(VI& V){return *max_element(ALL(V));}

void print_vector(VI& V){
  ll n = V.size();
  rep(i, n){
    if(i) cout << ' ';
    cout << V[i];
  }
  cout << endl;
}

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

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

// long double
using ld = long double;
#define EPS (1e-14)
#define equals(a,b) (fabs((a)-(b)) < EPS)

void no(){p_no(); exit(0);}
void yes(){p_yes(); exit(0);}

const ll mod = 1e9 + 7;
const ll inf = 1e18;
const double PI = acos(-1);

// for codeforces
void solve(){
  ll a;
  cin>>a;
}

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

    // input
    string s;cin>>s;
    ll L = s.size();

    // 条件１
    if(s[0]!='A') no();

    // 条件３
    ll lower_cnt=0;
    for(char c : s){
      if(islower(c)) lower_cnt++;
    }
    if(lower_cnt!=L-2) no();

    // 条件２
    ll C_cnt=0;
    FOR(i, 2, L-1){
      if(s[i]=='C') C_cnt++;
    }
    if(C_cnt!=1) no();

    yes();

    return 0;
}

Score : 200 points

Problem Statement

You are given a string S. Each character of S is uppercase or lowercase English letter.
Determine if S satisfies all of the following conditions:

The initial character of S is an uppercase A.

There is exactly one occurrence of C between the third character from the beginning and the second to last character (inclusive).

All letters except the A and C mentioned above are lowercase.

Constraints

4 ≤ |S| ≤ 10 (|S| is the length of the string S.)

Each character of S is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

If S satisfies all of the conditions in the problem statement, print AC; otherwise, print WA.

Sample Input 1

AtCoder

Sample Output 1

AC

The first letter is A, the third letter is C and the remaining letters are all lowercase, so all the conditions are satisfied.

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.


#include <iostream>
#include<cmath>
#include<vector>
#include<string>
using namespace std;
int main() {
    int cnt=0,cnt_C=0;
 string s;
 cin>>s;
for(int i=0;i<s.length();i++){
    if( s[i]=='C'){
        cnt_C++;
    }
}
for(int j=0;j<s.length();j++){
    if(islower(s[j])){
      cnt++  ;
    }
}
if(s[0]=='A' && s[2]=='C' && cnt_C==1 && cnt==s.length()-2){
    cout<<"AC";
}else{
    cout<<"WA";
}
}


#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<int>())
#define vunique(v) v.erase(unique(v.begin(), v.end()), v.end())
#define mp make_pair
#define ts(x) to_string(x)
#define rep(i, a, b) for(int i = (int)a; i < (int)b; i++)
#define repm(i, a, b) for(int i = (int)a; i > (int)b; i--)
#define bit(a) bitset<8>(a)
#define des_priority_queue priority_queue<int, vector<int>, greater<int> >
typedef long long ll;
typedef pair<int, int> P;
const ll INF = 1e18;

#define MAX_V 1000000

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

	int D, G;
	cin >> D >> G;
	vector<int> p, c;
	int problem_num = 0;
	rep(i, 0, D) {
		int tmp_p, tmp_c;
		cin >> tmp_p >> tmp_c;
		p.push_back(tmp_p);
		c.push_back(tmp_c);
		problem_num += tmp_p;
	}

	int dp[D + 1][problem_num + 1];
	rep(i, 0, D + 1) rep(j, 0, problem_num + 1) dp[i][j] = 0;

	rep(i, 0, D) rep(j, 0, problem_num + 1) {
		rep(k, 0, p[i]) {
			if(j - k >= 0 and j - k <= problem_num) {
				dp[i + 1][j] = max(dp[i + 1][j], dp[i][j - k] + 100 * (i + 1) * k);
			}
		}
		if(0 <= j - p[i] and j - p[i] <= problem_num) {
			dp[i + 1][j] = max(dp[i + 1][j], dp[i][j - p[i]] + 100 * (i + 1) * p[i] + c[i]);
		}
	}

	rep(i, 0, problem_num + 1) {
		if(dp[D][i] >= G) {
			cout << i << endl;
			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 <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
  int d, g;
  cin >> d >> g;
  g /= 100;
  vector<int> p(d), c(d);
  for (int i = 0; i < d; i++) {
    cin >> p[i] >> c[i];
    c[i] /= 100;
  }
  int ans = 1e9;
  for (int i = 0; i < 1 << d; i++) {
    int cnt = 0;
    int score = 0;
    for (int j = 0; j < d; j++) {
      if (i >> j & 1) {
        cnt += p[j];
        score += p[j] * (j + 1);
        score += c[j];
      }
    }
    for (int j = d - 1; j >= 0; j--) {
      if (~i >> j & 1) {
        for (int k = 0; k < p[j] && score < g; k++) {
          score += j + 1;
          cnt++;
        }
      }
    }
    if (score >= g) {
      ans = min(ans, cnt);
    }
  }
  cout << ans << endl;
}


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

using namespace std;

const int mod = 1000000007;

int main() {
  string s; cin >> s;
  // dp[i][x] := i文字までみたとき,
  // dp[i][0]: Aが何個あるか?
  // dp[i][1]: ABが何個あるか?
  // dp[i][2]: ABCが何個あるか?
  vector<vector<long long>> dp(s.length()+10, vector<long long>(3, 0));
  // mul: 現時点で文字列として考えられる種類. "?" が出現するたび3倍される
  long long mul = 1;
  for (int i = 0; i < s.length(); i++) {
    if (s[i] == 'A') {
      dp[i+1][0] = dp[i][0] + mul;
      dp[i+1][1] = dp[i][1];
      dp[i+1][2] = dp[i][2];
    }
    if (s[i] == 'B') {
      dp[i+1][0] = dp[i][0];
      dp[i+1][1] = dp[i][1] + dp[i][0];
      dp[i+1][2] = dp[i][2];
    }
    if (s[i] == 'C') {
      dp[i+1][0] = dp[i][0];
      dp[i+1][1] = dp[i][1];
      dp[i+1][2] = dp[i][2] + dp[i][1];
    }
    if (s[i] == '?') {
      // ?のときは, 3つの構成可能文字列に分岐するので, 3倍する
      dp[i+1][0] = dp[i][0] * 3 + mul;
      dp[i+1][1] = dp[i][1] * 3 + dp[i][0];
      dp[i+1][2] = dp[i][2] * 3 + dp[i][1];
      mul = (mul * 3) % mod;
    }
    dp[i+1][0] %= mod;
    dp[i+1][1] %= mod;
    dp[i+1][2] %= mod;
  }
  cout << dp[s.length()][2] << endl;
  return 0;
}

Score : 400 points

Problem Statement

The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions:

1 ≤ i < j < k ≤ |T| (|T| is the length of T.)

T_i = A (T_i is the i-th character of T from the beginning.)

T_j = B

T_k = C

For example, when T = ABCBC, there are three triples of integers (i, j, k) that satisfy the conditions: (1, 2, 3), (1, 2, 5), (1, 4, 5). Thus, the ABC number of T is 3.

You are given a string S. Each character of S is A, B, C or ?.

Let Q be the number of occurrences of ? in S. We can make 3^Q strings by replacing each occurrence of ? in S with A, B or C. Find the sum of the ABC numbers of all these strings.

This sum can be extremely large, so print the sum modulo 10^9 + 7.

Constraints

3 ≤ |S| ≤ 10^5

Each character of S is A, B, C or ?.

Input

Input is given from Standard Input in the following format:

S

Output

Print the sum of the ABC numbers of all the 3^Q strings, modulo 10^9 + 7.

Sample Input 1

A??C

Sample Output 1

8

In this case, Q = 2, and we can make 3^Q = 9 strings by by replacing each occurrence of ? with A, B or C. The ABC number of each of these strings is as follows:

AAAC: 0

AABC: 2

AACC: 0

ABAC: 1

ABBC: 2

ABCC: 2

ACAC: 0

ACBC: 1

ACCC: 0

The sum of these is 0 + 2 + 0 + 1 + 2 + 2 + 0 + 1 + 0 = 8, so we print 8 modulo 10^9 + 7, that is, 8.

Sample Input 2

ABCBC

Sample Output 2

3

When Q = 0, we print the ABC number of S itself, modulo 10^9 + 7. This string is the same as the one given as an example in the problem statement, and its ABC number is 3.

Sample Input 3

????C?????B??????A???????

Sample Output 3

979596887

In this case, the sum of the ABC numbers of all the 3^Q strings is 2291979612924, and we should print this number modulo 10^9 + 7, that is, 979596887.


#pragma warning(disable:4996)
#include <bits/stdc++.h>

using namespace std;

#define REP(i,n) for (ll i = 0; i<n; i++)
#define ALL(a) begin(a), end(a)
#define TPL template
#define TNM typename

using ll = long long;
using ull = unsigned long long;
TPL<TNM T> using vec = vector<T>;
TPL<TNM T> using vec2 = vec<vec<T>>;
TPL<TNM T> using vec3 = vec<vec2<T>>;
TPL<TNM T> using vec4 = vec<vec3<T>>;
TPL<TNM T> using vec5 = vec<vec4<T>>;

TPL<TNM K, TNM V> using umap = unordered_map<K, V>;
TPL<TNM K, TNM V> using uset = unordered_set<K, V>;

TPL<class T> inline void OUT(const T &x) { cout << x << "\n"; }
struct pre_ { pre_() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(6); } } pre__;

TPL<TNM V, TNM H> void resize(vector<V>& v, const H h) { v.resize(h); }
TPL<TNM V, TNM H, TNM ... T> void resize(vector<V>& v, const H& h, const T ... t) { v.resize(h); for (auto& _v : v) resize(_v, t ...); }
TPL<TNM V, TNM T> void fill(V& x, const T& val) { x = val; }
TPL<TNM V, TNM T> void fill(vector<V>& vec, const T& val) { for (auto& v : vec) fill(v, val); }

int main(void) {
	vec<int> A(3);
	REP(i, 3)cin >> A[i];
	sort(ALL(A));
	cout << abs(A[0] - A[1]) + abs(A[1] - A[2]) << 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 <iostream>
using namespace std;

int main() {
    int n, b;
    cin >> n;
    unsigned long long res = 0;
    for (int i = 0; i < n; ++i) {
        cin >> b;
        res += b - 1;
    }
    cout << res;
}

Score : 300 points

Problem Statement

You are given N positive integers a_1, a_2, ..., a_N.

For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N).

Here, X\ mod\ Y denotes the remainder of the division of X by Y.

Find the maximum value of f.

Constraints

All values in input are integers.

2 \leq N \leq 3000

2 \leq a_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the maximum value of f.

Sample Input 1

3
3 4 6

Sample Output 1

10

f(11) = (11\ mod\ 3) + (11\ mod\ 4) + (11\ mod\ 6) = 10 is the maximum value of f.

Sample Input 2

5
7 46 11 20 11

Sample Output 2

90

Sample Input 3

7
994 518 941 851 647 2 581

Sample Output 3

4527


#include <cstdio>
#include <algorithm>
using namespace std;
struct me{
    int x,y;
}v[100005];
bool com(struct me a, struct me b){
    return a.x<b.x;
}
int main(){
    int n,q;
    scanf("%d%d",&n,&q);
    for(int i=1;i<=q;i++){
        scanf("%d%d",&v[i].x,&v[i].y);
        if(v[i].x>v[i].y)
            swap(v[i].x,v[i].y);
    }
    sort(v+1,v+1+q,com);
    int s=0;
    int p=0xfffffff,j=1;
    for(int i=1;i<=n;i++){
        if(i==p) {
            s++;
            p=0xfffffff;
        }
        for(j;v[j].x==i;j++){
            p=min(v[j].y,p);
        }

    }
    if(p!=0xfffffff)
        s++;
    printf("%d\n",s);
}

Score : 400 points

Problem Statement

There are N islands lining up from west to east, connected by N-1 bridges.

The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west.

One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands:

Request i: A dispute took place between the a_i-th island from the west and the b_i-th island from the west. Please make traveling between these islands with bridges impossible.

You decided to remove some bridges to meet all these M requests.

Find the minimum number of bridges that must be removed.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq a_i < b_i \leq N

All pairs (a_i, b_i) are distinct.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the minimum number of bridges that must be removed.

Sample Input 1

5 2
1 4
2 5

Sample Output 1

1

The requests can be met by removing the bridge connecting the second and third islands from the west.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

5 10
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5

Sample Output 3

4


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

using namespace std;

int a[102];

int main(){
  int n;cin>>n;
  for(int i=0;i<n;i++)cin>>a[i];
  int cnt = 0;
  for(int i=1;i<n;i++){
    if(a[i] == a[i-1]){
      cnt++;
      i++;
    }
  }
  cout<<cnt<<endl;

  return 0;
}

Score : 200 points

Problem Statement

Takahashi lives in another world. There are slimes (creatures) of 10000 colors in this world. Let us call these colors Color 1, 2, ..., 10000.

Takahashi has N slimes, and they are standing in a row from left to right. The color of the i-th slime from the left is a_i.
If two slimes of the same color are adjacent, they will start to combine themselves. Because Takahashi likes smaller slimes, he has decided to change the colors of some of the slimes with his magic.

Takahashi can change the color of one slime to any of the 10000 colors by one spell.
How many spells are required so that no slimes will start to combine themselves?

Constraints

2 \leq N \leq 100

1 \leq a_i \leq N

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 number of spells required.

Sample Input 1

5
1 1 2 2 2

Sample Output 1

2

For example, if we change the color of the second slime from the left to 4, and the color of the fourth slime to 5, the colors of the slimes will be 1, 4, 2, 5, 2, which satisfy the condition.

Sample Input 2

3
1 2 1

Sample Output 2

0

Although the colors of the first and third slimes are the same, they are not adjacent, so no spell is required.

Sample Input 3

5
1 1 1 1 1

Sample Output 3

2

For example, if we change the colors of the second and fourth slimes from the left to 2, the colors of the slimes will be 1, 2, 1, 2, 1, which satisfy the condition.

Sample Input 4

14
1 2 2 3 3 3 4 4 4 4 1 2 3 4

Sample Output 4

4


// finish date: 2018/07/14
#include <bits/stdc++.h>

using namespace std;

#define FOR(i, a, b) for(int (i)=a;(i)<(b);(i)++)
#define rep(i, n)  FOR(i,0,n)
typedef long long ll;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<vector<vector<int>>>
        vvvi;
typedef vector<ll> vl;
typedef vector<vector<ll>> vvl;
typedef vector<double> vd;
typedef vector<vector<double>> vvd;
typedef vector<vector<vector<double>>>
        vvvd;
typedef vector<bool> vb;
typedef vector<vector<bool>> vvb;
typedef vector<string> vs;
typedef vector<char> vc;
typedef vector<vector<char>> vvc;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, pair<int, int>> plii;
const int bigmod = 1000000007;
const int INF = 1050000000;
const long long INFll = 100000000000000000;

//最大公約数
ll gcd(ll a, ll b) {
    if (a < 0) a = -a;
    if (b < 0) b = -b;
    if (a < b) {
        swap(a, b);
    }
    ll r = 1; //0以外であれば何でも
    while (r != 0) {
        r = a % b;
        a = b;
        b = r;
    }
    return a;
}

int main() {
    int T;
    cin >> T;
    rep(i, T) {
        ll A, B, C, D;
        cin >> A >> B >> C >> D;
        if (A < B || A % B > C || B > D) {
            cout << "No" << endl;
            continue;
        }
        if (B == D) {
            cout << "Yes" << endl;
            continue;
        }
        if (B - C <= 1 || D % B == 0) {
            cout << "Yes" << endl;
            continue;
        }

        ll G = gcd(D % B, B);
        if (G == 1) {
            cout << "No" << endl;
            continue;
        } else {
            if (A > C) {
                A = A % B;
            }
            ll n = (ceil(((double)C+1 - A) / G));
            ll check = A + n * G;
            if (check < B) {
                cout << "No" << endl;
            } else {
                cout << "Yes" << endl;
            }
        }
    }

    return 0;
}

Score : 600 points

Problem Statement

Ringo Mart, a convenience store, sells apple juice.

On the opening day of Ringo Mart, there were A cans of juice in stock in the morning.
Snuke buys B cans of juice here every day in the daytime.
Then, the manager checks the number of cans of juice remaining in stock every night.
If there are C or less cans, D new cans will be added to the stock by the next morning.

Determine if Snuke can buy juice indefinitely, that is, there is always B or more cans of juice in stock when he attempts to buy them.
Nobody besides Snuke buy juice at this store.

Note that each test case in this problem consists of T queries.

Constraints

1 \leq T \leq 300

1 \leq A, B, C, D \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

T
A_1 B_1 C_1 D_1
A_2 B_2 C_2 D_2
:
A_T B_T C_T D_T

In the i-th query, A = A_i, B = B_i, C = C_i, D = D_i.

Output

Print T lines. The i-th line should contain Yes if Snuke can buy apple juice indefinitely in the i-th query; No otherwise.

Sample Input 1

14
9 7 5 9
9 7 6 9
14 10 7 12
14 10 8 12
14 10 9 12
14 10 7 11
14 10 8 11
14 10 9 11
9 10 5 10
10 10 5 10
11 10 5 10
16 10 5 10
1000000000000000000 17 14 999999999999999985
1000000000000000000 17 15 999999999999999985

Sample Output 1

No
Yes
No
Yes
Yes
No
No
Yes
No
Yes
Yes
No
No
Yes

In the first query, the number of cans of juice in stock changes as follows: (D represents daytime and N represents night.)

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 6
→D x

In the second query, the number of cans of juice in stock changes as follows:

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 15
→D 8
→N 8
→D 1
→N 10
→D 3
→N 12
→D 5
→N 14
→D 7
→N 7
→D 0
→N 9
→D 2
→N 11
→D …

and so on, thus Snuke can buy juice indefinitely.

Sample Input 2

24
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1

Sample Output 2

No
No
No
No
No
No
Yes
Yes
No
No
No
No
Yes
Yes
Yes
No
No
No
Yes
Yes
Yes
No
No
No


#include <iostream>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <map>
#include <set>
#include <algorithm>
#include <queue>
typedef long long LL;
using namespace std;

int main()
{
	//freopen("data_in.txt", "r", stdin);
	int n = 0;
	cin >> n;
	LL a = 0, b = 0, c = 0, d = 0;
	for (int i = 0; i < n; ++i) {
		cin >> a >> b >> c >> d;
		if (a < b || d < b) {
			cout << "No" << endl;
			continue;
		}
		else if (b == d) {
			if (a %b > c) cout << "No" << endl;
			else cout << "Yes\n";
		}
		else if (c >= b - 1) {
			cout << "Yes" << endl;
			continue;
		}
		else {
			LL x = a % b;
			LL t = d % b;
			if (b-c > t || (b-c == t && (b-x)%t != 0)) cout << "No\n";
			else if(x > c && x < b) cout << "No\n";
			else cout << "Yes\n";
		}

	}
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define all(x) (x).begin(), (x).end()
typedef long double ld;
typedef long long ll;

const int A = 20;

int bit(int mask, int i) {
  return (mask >> i) & 1;
}

int main() {
#ifdef LOCAL
  assert(freopen("c.in", "r", stdin));
#endif

  ios_base::sync_with_stdio(false);

  int n;
  cin >> n;
  string s;
  cin >> s;

  vector<string> a[A];

  for (int mask = 0; mask < (1 << n); ++mask) {
    string t(n, 'z');
    int l = 0, r = n - 1;
    int sz = __builtin_popcount(mask);
    for (int i = 0; i < n; ++i) {
      if (bit(mask, i))
        t[l++] = s[i];
      else
        t[r--] = s[i];
    }
    //cerr << sz << ": " << t << "\n";
    a[sz].push_back(t);
  }

  for (int i = 0; i <= n; ++i)
    sort(all(a[i]));

  auto cnt = [&](int k, const string &t) {
    return upper_bound(all(a[k]), t) - lower_bound(all(a[k]), t);
  };

  ll ans = 0;
  for (int mask = 0; mask < (1 << n); ++mask) {
    string t(n, 'z');
    int l = 0, r = n - 1;
    int sz = __builtin_popcount(mask);
    for (int i = 0; i < n; ++i)
      if (bit(mask, i))
        t[l++] = s[2 * n - 1 - i];
      else
        t[r--] = s[2 * n - 1 - i];

    //if (cnt(n - sz, t)) {
      //cerr << n - sz << ", " << t << "\n";
    //}
    ans += cnt(sz, t);
  }

  cout << ans << "\n";
}

Score : 600 points

Problem Statement

You are given a string S of length 2N consisting of lowercase English letters.

There are 2^{2N} ways to color each character in S red or blue. Among these ways, how many satisfy the following condition?

The string obtained by reading the characters painted red from left to right is equal to the string obtained by reading the characters painted blue from right to left.

Constraints

1 \leq N \leq 18

The length of S is 2N.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of ways to paint the string that satisfy the condition.

Sample Input 1

4
cabaacba

Sample Output 1

4

There are four ways to paint the string, as follows:

cabaacba

cabaacba

cabaacba

cabaacba

Sample Input 2

11
mippiisssisssiipsspiim

Sample Output 2

504

Sample Input 3

4
abcdefgh

Sample Output 3

0

Sample Input 4

18
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Sample Output 4

9075135300

The answer may not be representable as a 32-bit integer.


#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <queue>
#include <set>
#include <numeric>
#include <cmath>

using namespace std;

typedef long long int ll;

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

const ll mod = 1e9+7;
const ll INF = 1e9;
const ll MAXN = 1e9;

int main()
{
	int n;
	cin >> n;
	if(n%2 == 0) cout << n;
	else cout << 2*n << endl;

	return 0;
}

Score : 100 points

Problem Statement

You are given a positive integer N.
Find the minimum positive integer divisible by both 2 and N.

Constraints

1 \leq N \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum positive integer divisible by both 2 and N.

Sample Input 1

3

Sample Output 1

6

6 is divisible by both 2 and 3.
Also, there is no positive integer less than 6 that is divisible by both 2 and 3.
Thus, the answer is 6.

Sample Input 2

10

Sample Output 2

10

Sample Input 3

999999999

Sample Output 3

1999999998


#include <bits/stdc++.h>

using namespace std;
typedef long long int ll;
typedef pair<int, int> ii;
#define DEBUG freopen("in.txt", "r", stdin);

struct fastio {
    fastio() {
        ios::sync_with_stdio(false);
        cout << setprecision(10) << fixed;
        cin.tie(0);
    }
};

fastio _fast_io;

int n, t;

int main() {
    cin >> n;
    int mi = 1e9;
    int mx = 1;
    for (int i = 0; i < n; ++i) {
        cin >> t;
        mi = min(mi, t);
        mx = max(mx, t);
    }
    cout << mx - mi << 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 <bits/stdc++.h>
#define MOD 1000000007
#define INF 1000000000
#define LINF 1000000000000000000
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define bit(n) (1LL<<(n))
using namespace std;

typedef pair<int, int> P;
typedef pair<long long, long long> LLP;

int main() {
    int N;
    cin >> N;
    vector<int> A(N), B(N);
    rep(i,N) {
        cin >> A[i];
        B[i] = A[i] - i;
    }

    sort(B.begin(), B.end());

    int b = N % 2 == 1 ? B[N / 2] : (B[N / 2 - 1] + B[N / 2]) / 2;
    long long ans = 0;
    rep(i,N) ans += abs(B[i] - b);

    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


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

int main(){
  int n;
  cin >> n ;
  int a[n];
  for (int i=0; i<n; i++){
      cin >> a[i];
  }
  for (int i=0; i<n; i++){
      a[i]=a[i]-i-1;
  }
  sort(a,a+n);
  int b=a[n/2];
  int ans=0;
  for (int i=0; i<n; i++){
      ans+=abs(b-a[i]);
  }
  cout << ans <<endl;
}


/* Dsingh_24 */

#include<bits/stdc++.h>
#define ll          long long
#define pb          push_back
#define	endl		'\n'
#define pii         pair<ll int,ll int>
#define vi          vector<ll int>
#define all(a)      (a).begin(),(a).end()
#define F           first
#define S           second
#define sz(x)       (ll int)x.size()
#define hell        1000000007
#define rep(i,a,b)	for(ll int i=a;i<b;i++)
#define lbnd        lower_bound
#define ubnd        upper_bound
#define bs          binary_search
#define mp          make_pair
#define ios	    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;

#define N  100005
ll p[1<<19],q[1<<19];
int main()
{
	ios
	ll n,i,j;
	cin>>n;
	ll a[(1<<18)+1];
	for(i=0;i<(1<<n);i++){
		cin>>a[i];
		p[i]=a[i],q[i]=0;
	}
	for(i=0;i<n;i++){
		for(j=0;j<(1<<n);j++){
			if(j&(1<<i)){
				ll x[4];
				x[0]=p[j],x[1]=q[j],x[2]=p[j^(1<<i)],x[3]=q[j^(1<<i)];
				sort(x,x+4);
				p[j]=x[3],q[j]=x[2];
			}
		}
	}
	ll ans=0;
	for(i=1;i<(1<<n);i++){
		ans=max(ans,p[i]+q[i]);
		cout<<ans<<"\n";
	}
	return 0;
}

Score : 700 points

Problem Statement

There is an integer sequence of length 2^N: A_0, A_1, ..., A_{2^N-1}. (Note that the sequence is 0-indexed.)

For every integer K satisfying 1 \leq K \leq 2^N-1, solve the following problem:

Let i and j be integers. Find the maximum value of A_i + A_j where 0 \leq i < j \leq 2^N-1 and (i or j) \leq K.
Here, or denotes the bitwise OR.

Constraints

1 \leq N \leq 18

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_0 A_1 ... A_{2^N-1}

Output

Print 2^N-1 lines.
In the i-th line, print the answer of the problem above for K=i.

Sample Input 1

2
1 2 3 1

Sample Output 1

3
4
5

For K=1, the only possible pair of i and j is (i,j)=(0,1), so the answer is A_0+A_1=1+2=3.

For K=2, the possible pairs of i and j are (i,j)=(0,1),(0,2).
When (i,j)=(0,2), A_i+A_j=1+3=4. This is the maximum value, so the answer is 4.

For K=3, the possible pairs of i and j are (i,j)=(0,1),(0,2),(0,3),(1,2),(1,3),(2,3) .
When (i,j)=(1,2), A_i+A_j=2+3=5. This is the maximum value, so the answer is 5.

Sample Input 2

3
10 71 84 33 6 47 23 25

Sample Output 2

81
94
155
155
155
155
155

Sample Input 3

4
75 26 45 72 81 47 97 97 2 2 25 82 84 17 56 32

Sample Output 3

101
120
147
156
156
178
194
194
194
194
194
194
194
194
194


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

int main() {
    string S;
    cin >> S;
    int ans = 0;
    for(auto e:S){
      if(e== '+')ans++;
      else ans--;
    }
    cout << ans << endl;
}

Score : 100 points

Problem Statement

There is always an integer in Takahashi's mind.

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

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

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

Constraints

The length of S is 4.

Each character in S is + or -.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

+-++

Sample Output 1

2

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

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

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

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

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

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

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4


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

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

  int ans = 0;

  rep(i, 4){
    if(str.at(i) == '+'){
      ans++;
    }
    else{
      ans--;
    }
  }

  cout << ans << endl;
}


/*
g++ -std=c++11 -o2 -Wall ABC101D.cpp -o ./out/ABC101D.out
./out/ABC101D.out
*/

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

#define all(c) (c).begin(), (c).end()
#define iter(c) __typeof((c).begin())
#define present(c, e) ((c).find((e)) != (c).end())
#define cpresent(c, e) (find(all(c), (e)) != (c).end())
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define tr(c, i) for (iter(c) != (c).begin(); i != (c).end(); ++i)
#define pb push_back
#define mp make_pair

typedef long long ll;

ll sum(ll n)
{
  ll s = 0;
  while (n > 0)
  {
    s += n % 10;
    n /= 10;
  }
  return s;
}

int main(){
//    freopen("./input/input.txt", "r", stdin);
    ios::sync_with_stdio(0);
    cin.tie(0);
    ll k;
    cin >> k;
    ll n = 1, d = 1;
    cout << 1 << endl;
    for (ll i = 1; i < k; ++i)
    {
      if (sum(n + d) * (n + d * 10) < sum(n + d * 10) * (n + d))
        d *= 10;
      n += d;
      cout << n << endl;
    }

    return 0;
}

Score : 500 points

Problem Statement

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

We will call an integer n a Snuke number when, for all positive integers m such that m > n, \frac{n}{S(n)} \leq \frac{m}{S(m)} holds.

Given an integer K, list the K smallest Snuke numbers.

Constraints

1 \leq K

The K-th smallest Snuke number is not greater than 10^{15}.

Input

Input is given from Standard Input in the following format:

K

Output

Print K lines. The i-th line should contain the i-th smallest Snuke number.

Sample Input 1

10

Sample Output 1

1
2
3
4
5
6
7
8
9
19