#include <bits/stdc++.h>
#define MOD 1000000007LL
using namespace std;
typedef long long ll;
typedef pair<int,int> P;

string str;

int main(void){
	cin >> str;
	int cnt=0;
	for(int i=1;i<str.size();i++){
		if(str[i]!=str[i-1])cnt++;
	}
	printf("%d\n",cnt);
	return 0;
}

Score : 300 points

Problem Statement

Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones between the new white stone and another white stone, turn into white stones, and vice versa.

In the middle of a game, something came up and Saburo has to leave the game. The state of the board at this point is described by a string S. There are |S| (the length of S) stones on the board, and each character in S represents the color of the i-th (1 ≦ i ≦ |S|) stone from the left. If the i-th character in S is B, it means that the color of the corresponding stone on the board is black. Similarly, if the i-th character in S is W, it means that the color of the corresponding stone is white.

Jiro wants all stones on the board to be of the same color. For this purpose, he will place new stones on the board according to the rules. Find the minimum number of new stones that he needs to place.

Constraints

1 ≦ |S| ≦ 10^5

Each character in S is B or W.

Input

The input is given from Standard Input in the following format:

S

Output

Print the minimum number of new stones that Jiro needs to place for his purpose.

Sample Input 1

BBBWW

Sample Output 1

1

By placing a new black stone to the right end of the row of stones, all white stones will become black. Also, by placing a new white stone to the left end of the row of stones, all black stones will become white.

In either way, Jiro's purpose can be achieved by placing one stone.

Sample Input 2

WWWWWW

Sample Output 2

0

If all stones are already of the same color, no new stone is necessary.

Sample Input 3

WBWBWBWBWB

Sample Output 3

9


#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<string>

using namespace std;
const int INF = 1<<30;
typedef long long int ll;

int main(){
	int n;cin>>n;
	string s, t;cin>>s>>t;
	int ans=int(s.size()+t.size());
	for(int i=0;i<n;i++){
		string tmp = s.substr(i, n-i);
		bool match=true;
		for(int j=0;j<n-i;j++){
			if(t[j]!=tmp[j]){match=false;break;}
		}
		if(match){ans=int(t.size())+i;break;}
	}
	cout<<ans<<endl;
}

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

Score : 200 points

Problem Statement

Snuke is interested in strings that satisfy the following conditions:

The length of the string is at least N.

The first N characters equal to the string s.

The last N characters equal to the string t.

Find the length of the shortest string that satisfies the conditions.

Constraints

1≤N≤100

The lengths of s and t are both N.

s and t consist of lowercase English letters.

Input

The input is given from Standard Input in the following format:

N
s
t

Output

Print the length of the shortest string that satisfies the conditions.

Sample Input 1

3
abc
cde

Sample Output 1

5

The shortest string is abcde.

Sample Input 2

1
a
z

Sample Output 2

2

The shortest string is az.

Sample Input 3

4
expr
expr

Sample Output 3

4

The shortest string is expr.

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;
typedef long long ll;
typedef pair<ll,ll> P;
#define rep(i,n) for(int i=0;i<(int)n;i++)
const ll INF = (1LL<<31)-1;

int main(){
    int N, x; cin >> N >> x;
    vector<int> X(2*N-1,INF);

    if(x==1 || x==2*N-1){ cout << "No" << endl;}
    else {
        X[N-2] = x-1; X[N-1] = x; X[N] = x+1;
        set<int> num;
        for(int i=1;i<=2*N-1;i++){
            if(abs(x-i)>1) num.insert(i);
        }
        rep(i,2*N-1){
            int xi = *num.begin();
            if(X[i]==INF){
                X[i] = xi;
                num.erase(xi);
            }
        }
        cout << "Yes" << endl;
        rep(i,2*N-1) cout << X[i] << endl;
    }

}

Score : 400 points

Problem Statement

We have a pyramid with N steps, built with blocks.
The steps are numbered 1 through N from top to bottom.
For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally.
The pyramid is built so that the blocks at the centers of the steps are aligned vertically.

A pyramid with N=4 steps

Snuke wrote a permutation of (1, 2, ..., 2N-1) into the blocks of step N.
Then, he wrote integers into all remaining blocks, under the following rule:

The integer written into a block b must be equal to the median of the three integers written into the three blocks directly under b, or to the lower left or lower right of b.

Writing integers into the blocks

Afterwards, he erased all integers written into the blocks.
Now, he only remembers that the integer written into the block of step 1 was x.

Construct a permutation of (1, 2, ..., 2N-1) that could have been written into the blocks of step N, or declare that Snuke's memory is incorrect and such a permutation does not exist.

Constraints

2≤N≤10^5

1≤x≤2N-1

Input

The input is given from Standard Input in the following format:

N x

Output

If no permutation of (1, 2, ..., 2N-1) could have been written into the blocks of step N, print No.

Otherwise, print Yes in the first line, then print 2N-1 lines in addition.

The i-th of these 2N-1 lines should contain the i-th element of a possible permutation.

Sample Input 1

4 4

Sample Output 1

Yes
1
6
3
7
4
5
2

This case corresponds to the figure in the problem statement.

Sample Input 2

2 1

Sample Output 2

No

No matter what permutation was written into the blocks of step N, the integer written into the block of step 1 would be 2.


#include<algorithm>
#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<utility>
#include<queue>
using namespace std;
#define REP(i, a,b) for(i=a;i<b;i++)
#define REP1(i,b,a) for(i=b-1;i>=a;i--)
#define output(x) cout<<x<<endl;
#define pb(x) push_back(x);
typedef long long int ll;
const int MAX = 510000;
const int MOD = 1000000007;

long long fac[MAX], finv[MAX], inv[MAX];

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

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

int main()
{
	ll  i, j, k, l, m, sum, flag, N, x, y, M, K, H, W, A, B;
	cin >> N>>x;
	flag = 0;
	vector<ll>a(N*2-1);
	vector<ll>b;
	REP(i, 1, 2 * N ) {
		b.pb(i);
	}
	if (N == 2) {
		if (x == 2) {
			output("Yes");
			output(1);
			output(2);
			output(3);
			return 0;
		}
		output("No");
		return 0;
	}
	if (x >= 2 && x <=2*N - 2) {
		flag = 1;
		if (x < 2*N - 2) {
			a[N - 1] = x;
			a[N] = 1;
			a[N - 2] = x + 2;
			a[N + 1] = x + 1;
			b.erase(b.begin());
			b.erase(b.begin() + x - 2);
			b.erase(b.begin() + x - 2);
			b.erase(b.begin() + x - 2);
			REP(i, 0, N - 2) {
				a[i] = b[i];
			}
			REP(i, N + 2, 2 * N - 1) {
				a[i] = b[i- 4];
			}
			output("Yes");
			REP(i, 0, 2 * N - 1) {
				output(a[i]);
			}
			return 0;
		}
		a[N - 1] = x;
		a[N] = x+1;
		a[N - 2] = x - 2;
		a[N + 1] = x - 1;
		b.erase(b.begin() + x - 3);
		b.erase(b.begin() + x - 3);
		b.erase(b.begin() + x - 3);
		b.erase(b.begin() + x - 3);
		REP(i, 0, N - 2) {
			a[i] = b[i];
		}
		REP(i, N + 2, 2 * N - 1) {
			a[i] = b[i - 4];
		}
		output("Yes");
		REP(i, 0, 2 * N - 1) {
			output(a[i]);
		}
		return 0;

	}
	output("No");
	return 0;

}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ii pair <int, int>
#define app push_back
#define all(a) a.begin(), a.end()
#define bp __builtin_popcountll
#define ll long long
#define mp make_pair
#define f first
#define s second
#define Time (double)clock()/CLOCKS_PER_SEC
#define debug(x) std::cout << #x << ": " << x << '\n';

const int N = 307, INF = 1e18;
int n, m;
string a[N];

int p[2 * N][N];
int dp[N][N];

signed main() {
    #ifdef HOME
    freopen("input.txt", "r", stdin);
    #else
    #define endl '\n'
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    cout.setf(ios::fixed); cout.precision(20);
    #endif
    cin >> n >> m;
    for (int i = 0; i < n; ++i)
        cin >> a[i];

    function <int(string, string)> solve = [&](string s, string t) {

        for (int i = 0; i <= n; ++i) for (int j = 0; j <= n; ++j) dp[i][j] = INF;

        for (int sh = -n; sh <= n; ++sh) {
            for (int i = 0; i < n; ++i) {
                p[sh + n][i + 1] = p[sh + n][i] + (0 <= i + sh && i + sh < n && s[i] == t[i + sh]);
            }
        }

        dp[0][0] = 0;
        for (int i = 0; i <= n; ++i) {
            for (int j = 0; j <= n; ++j) {
                int add = p[i - j + n][n - i];
                if (i < n) {
                    dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + add);
                }
                if (j < n) {
                    dp[i][j + 1] = min(dp[i][j + 1], dp[i][j] + add);
                }
            }
        }
        return dp[n][n];

    };

    int ans = 0;
    for (int j = 0; j < m - 1; ++j) {
        string s, t;
        for (int i = 0; i < n; ++i) {
            s += a[i][j];
            t += a[i][j + 1];
        }
        ans += solve(s, t);
    }
    cout << ans << endl;
}

Score : 800 points

Problem Statement

Mr. Takahashi has in his room an art object with H rows and W columns, made up of H \times W blocks.
Each block has a color represented by a lowercase English letter (a-z).
The color of the block at the i-th row and j-th column is c_{i,j}.

Mr. Takahashi would like to dismantle the object, finding it a bit kitschy for his tastes.
The dismantling is processed by repeating the following operation:

Choose one of the W columns and push down that column one row.
The block at the bottom of that column disappears.

Each time the operation is performed, a cost is incurred.
Since blocks of the same color have a property to draw each other together, the cost of the operation is the number of the pairs of blocks (p, q) such that:

The block p is in the selected column.

The two blocks p and q are horizontally adjacent (before pushing down the column).

The two blocks p and q have the same color.

Mr. Takahashi dismantles the object by repeating the operation H \times W times to get rid of all the blocks.
Compute the minimum total cost to dismantle the object.

Constraints

1 ≤ H ≤ 300

2 ≤ W ≤ 300

All characters c_{i,j} are lowercase English letters (a-z).

Partial Score

In test cases worth 300 points, W = 3.

Input

The input is given from Standard Input in the following format:

H W
c_{1,1}c_{1,2}..c_{1,W}
c_{2,1}c_{2,2}..c_{2,W}
:
c_{H,1}c_{H,2}..c_{H,W}

Output

Print the minimum total cost to dismantle the object.

Sample Input 1

2 3
rrr
brg

Sample Output 1

2

For example, the total cost of 2 can be achieved by performing the operation as follows and this is the minimum value.

Sample Input 2

6 3
xya
xya
ayz
ayz
xaz
xaz

Sample Output 2

0

The total cost of 0 can be achieved by first pushing down all blocks of the middle column, then all of the left column, and all of the right column.

Sample Input 3

4 2
ay
xa
xy
ay

Sample Output 3

0

The total cost of 0 can be achieved by the following operations:

pushing down the right column one row;

pushing down the left column one row;

pushing down all of the right column;

and pushing down all of the left column.

Sample Input 4

5 5
aaaaa
abbba
ababa
abbba
aaaaa

Sample Output 4

24

Sample Input 5

7 10
xxxxxxxxxx
ccccxxffff
cxxcxxfxxx
cxxxxxffff
cxxcxxfxxx
ccccxxfxxx
xxxxxxxxxx

Sample Output 5

130


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

int main()
{
	ios_base :: sync_with_stdio(0);
	ll n, k;
	cin >> n >> k;
	ll res = 1;
	for(ll i = 1; i < n; i++, k--) {
		res *= k;
	}
	cout << res << "\n";
	return 0;
}

Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

The input is given from Standard Input in the following format:

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


#define _CRT_SECURE_NO_WARNINGS
#pragma comment(linker, "/STACK:256000000")
#define _USE_MATH_DEFINES
#include<iostream>
#include<vector>
#include<string>
#include<stack>
#include<algorithm>
#include<cmath>
#include<set>
#include<queue>
#include<sstream>
#include<utility>
#include<map>
#include<ctime>
#include<cstdio>
#include<cassert>
#include<functional>
#include<unordered_map>
#include<deque>
#include<cmath>

using namespace std;

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

#define show(x) cerr << x
#define debug(x) show(#x << ": " << (x) << endl)

const long double PI = 3.14159265358979323846;
const long double eps = 1e-5;
const ll INF = numeric_limits<int>::max();
const ll LINF = numeric_limits<ll>::max();
//const ll mod = 1000 * 1000 * 1000 + 7;

void solve() {
    int n;
    cin >> n;
    int x, y;
    x = 1, y = 1;
    int a, b;
    for (int i = 0; i < n; ++i) {
        cin >> a >> b;
        int q = max((x + a - 1) / a, (y + b - 1) / b);
        x = a * q, y = b * q;
    }
    cout << x + y << endl;

}

//#define LOCAL

int main() {
    ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr);
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    solve();

#ifdef LOCAL
    cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
    return 0;
}

Score : 300 points

Problem Statement

AtCoDeer the deer is seeing a quick report of election results on TV.
Two candidates are standing for the election: Takahashi and Aoki.
The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes.
AtCoDeer has checked the report N times, and when he checked it for the i-th (1≦i≦N) time, the ratio was T_i:A_i.
It is known that each candidate had at least one vote when he checked the report for the first time.

Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the N-th time.
It can be assumed that the number of votes obtained by each candidate never decreases.

Constraints

1≦N≦1000

1≦T_i,A_i≦1000 (1≦i≦N)

T_i and A_i (1≦i≦N) are coprime.

It is guaranteed that the correct answer is at most 10^{18}.

Input

The input is given from Standard Input in the following format:

N
T_1 A_1
T_2 A_2
:
T_N A_N

Output

Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the N-th time.

Sample Input 1

3
2 3
1 1
3 2

Sample Output 1

10

When the numbers of votes obtained by the two candidates change as 2,3 → 3,3 → 6,4, the total number of votes at the end is 10, which is the minimum possible number.

Sample Input 2

4
1 1
1 1
1 5
1 100

Sample Output 2

101

It is possible that neither candidate obtained a vote between the moment when he checked the report, and the moment when he checked it for the next time.

Sample Input 3

5
3 10
48 17
31 199
231 23
3 2

Sample Output 3

6930


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

template<typename T, typename VAL_TYPE>
struct trie{
	typedef function<int(T)> To_Int;
	int SIGMA;
	To_Int to_int;

	struct node{
		vector<VAL_TYPE> val;
		int cnt;
		vector<node *> nexts;
	};

	node *root;

	trie(int SIGMA, To_Int to_int) : SIGMA(SIGMA), to_int(to_int), root(NULL) {}

	int ret_cnt(node *nd){
		if(nd == NULL) return 0;
		else return nd->cnt;
	}

	vector<VAL_TYPE> ret_val(node *nd){
		if(nd == NULL) return vector<VAL_TYPE>(0);
		else return nd->val;
	}

	//ndにSの[l,r)を追加したノードを返す
	node *add(node *nd, string &S, int l, int r, VAL_TYPE v){
		node *ans;
		if(nd == NULL){
			ans = new node;
			ans->val.assign(0, v);
			ans->cnt = 0;
			ans->nexts.assign(SIGMA, NULL);
		}
		else{
			ans = nd;
		}
		ans->cnt++;
		if(l == r){
			ans->val.push_back(v);
		}
		else{
			ans->nexts[to_int(S[l])] = add(ans->nexts[to_int(S[l])], S, l + 1, r, v);
		}
		return ans;
	}

	//(S,v)を追加する
	void add(string &S, VAL_TYPE v){
		root = add(root, S, 0, S.size(), v);
	}

	//ndからSの[l,r)を辿ったノードを返す(無いときはNULL)
	node *search(node *nd, string &S, int l, int r){
		if(nd == NULL){
			return NULL;
		}
		else if(l == r){
			return nd;
		}
		else{
			return search(nd->nexts[to_int(S[l])], S, l + 1, r);
		}
	}

	//Sをprefixに含む文字列の個数
	int prefix_count(string &S){
		return ret_cnt(search(root, S, 0, S.size()));
	}

	//Sの値
	vector<VAL_TYPE> value(string &S){
		return ret_val(search(root, S, 0, S.size()));
	}

	void junp_check(node *nd, string &S, vector<int> &junp, int l, int r){
		if(l < r && nd != NULL && nd->nexts[to_int(S[l])] != NULL){
			if(nd->cnt == nd->nexts[to_int(S[l])]->cnt){
				junp[l] = 1;
			}
			junp_check(nd->nexts[to_int(S[l])], S, junp, l + 1, r);
		}
	}

	void junp_check(string &S, vector<int> &junp){
		junp_check(root, S, junp, 0, S.size());
	}

	node *compression(node *nd){
		if(nd == NULL || ret_cnt(nd) == 0){
			return NULL;
		}
		for(int i = 0; i < SIGMA; i++){
			node *ndi = nd->nexts[i];
			if(nd->cnt == ret_cnt(ndi)){
				return compression(ndi);
			}
			nd->nexts[i] = compression(ndi);
		}
		return nd;
	}

	void compression(){
		root = compression(root);
	}

	int solve(node *nd, string &S, int l, int r, string &p){
		if(l == r || nd == NULL){
			return 0;
		}
		else{
			int ans = ret_val(nd).size();
			for(int i = 0; i < SIGMA; i++){
				if(p[i] == S[l]){
					return ans + solve(nd->nexts[to_int(p[i])], S, l + 1, r, p);
				}
				else{
					ans += ret_cnt(nd->nexts[to_int(p[i])]);
				}
			}
		}
	}

	int solve(string &S, string &p){
		return solve(root, S, 0, S.size(), p);
	}
};

int char_to_int(char c){
	return (int)(c - 'a');
}

int main(){
	int N, Q, i, j;
	scanf("%d", &N);
	vector<string> S(N);
	for(i = 0; i < N; i++){
		cin >> S[i];
	}
	trie<char, int> t(26, char_to_int);
	for(i = 0; i < N; i++){
		t.add(S[i], i);
	}
	vector<vector<int>> junp(N);
	vector<string> Scomp(N, "");
	for(i = 0; i < N; i++){
		junp[i] = vector<int>(S[i].size(), 0);
		t.junp_check(S[i], junp[i]);
		for(j = 0; j < S[i].size(); j++){
			if(junp[i][j] == 0){
				Scomp[i].push_back(S[i][j]);
			}
		}
	}
	t.compression();
/*	printf("compression!\n");
	for(i = 0; i < N; i++){
		cout << Scomp[i] << endl;
	}
	while(1){
		int ins;
		string T;
		scanf("%d", &ins);
		cin >> T;
		if(ins == 0){
			printf("%d\n", t.prefix_count(T));
		}
		else{
			vector<int> ids = t.value(T);
			for(i = 0; i < ids.size(); i++){
				printf("%d ", ids[i]);
			}
			printf("\n");
		}
	}
*/	scanf("%d", &Q);
	for(i = 0; i < Q; i++){
		int k;
		string p;
		scanf("%d", &k);
		cin >> p;
		printf("%d\n", t.solve(Scomp[k - 1], p) + 1);
	}
	return 0;
}

Score : 1100 points

Problem Statement

There are N strings of lowercase alphabet only. The i-th string is S_i. Every string is unique.

Provide answers for the Q queries below. The i-th query has the following format:

Query: An integer k_i and a string p_{i,1}p_{i,2}...p_{i,26} that results from permuting {a,b,...,z} are given. Output the sequence of the string S_{k_i} among the N strings in lexicographical order when the literal sequence is p_{i,1}<p_{i,2}<...<p_{i,26}.

Constraints

1 ≦ N,Q ≦ 100000

1 ≦ |S_i| (1 ≦ i ≦ N)

S_i (1 ≦ i ≦ N) is a string of lowercase alphabet.

The sum of |S_i| is no more than 400000.

Every S_i is unique.

1 ≦ k_i ≦ N (1 ≦ i ≦ Q)

For all 1 ≦ i ≦ Q, p_{i,1}p_{i,2}...p_{i,26} is a permutation of abcd...z.

Input

Inputs are provided from standard inputs in the following form.

N
S_1
:
S_N
Q
k_1 p_{1,1}p_{1,2}...p_{1,26}
:
k_Q p_{Q,1}p_{Q,2}...p_{Q,26}

Output

Output Q lines.

On line i, for the i-th query, output an integer indicating the sequence of the string S_{k_i} among the N strings in lexicographical order.

Sample Input 1

5
aa
abbaa
abbba
aaab
aaaaaba
5
1 abcdefghijklmnopqrstuvwxyz
2 bacdefghijklmnopqrstuvwxyz
3 abcdefghijklmnopqrstuvwxyz
4 bacdefghijklmnopqrstuvwxyz
5 abcdefghijklmnopqrstuvwxyz

Sample Output 1

1
2
5
4
2

When the literal sequence is a < b, sorting the input strings in lexicographical order yields aa, aaaaaba, aaab, abbaa, abbba. The answers to queries 1, 3, and 5 are thus 1, 5, and 2, respectively.

When the literal sequence is b < a, sorting the input strings in lexicographical order yields abbba, abbaa, aa, aaab, aaaaaba. The answers to queries 2 and 4 are thus 2 and 4, respectively.

Sample Input 2

8
abrakatabra
abadaba
abracadabra
atcoder
grand
contest
ababa
a
6
3 abcdefghijklmnopqrstuvwxyz
6 qwertyuiopasdfghjklzxcvbnm
8 poiuytrewqlkjhgfdsamnbvcxz
2 qazwsxedcrfvtgbyhnujmikolp
1 plokmijnuhbygvtfcrdxeszwaq
4 mnbvcxzasdfghjklpoiuytrewq

Sample Output 2

4
8
2
3
4
7


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

int main(){
		string x;
		cin >> x;
		int s = 0;
		int ans = x.size();

		for(int i=0;i<x.size();i++) {
				if(x[i]=='S') s++;
				if(x[i]=='T') {
						if(s>0){
								ans -= 2;
								s--;
						}
				}
		}

		cout << ans << endl;
}

Score : 300 points

Problem Statement

We have a string X, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation 10^{10000} times:

Among the occurrences of ST in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

Half the characters in X are S, and the other half are T.

Partial Scores

In test cases worth 200 points, |X| ≦ 200.

Input

The input is given from Standard Input in the following format:

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

In the 1-st operation, the 2-nd and 3-rd characters of TSTTSS are removed.
X becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining 10^{10000}-1 operations.
Thus, the answer is 4.

Sample Input 2

SSTTST

Sample Output 2

0

X will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.


#include <cstdio>
#include <cstring>
using namespace std;

const int N = 200500;
char st[N];

char buf[N];

int main() {
    scanf("%s", buf);
    int len = strlen(buf);
    int pt = 0;
    for (int i = 0; i < len; i++) {
        char c = buf[i];
        if (pt != 0 && st[pt - 1] == 'S' && c == 'T')
            --pt;
        else
            st[pt++] = c;
    }
    printf("%d\n", pt);
}


/*
 * src.cpp
 *
 *  Created on: 2016/10/01
 *      Author: joi
 */

#include <bits/stdc++.h>

using namespace std;

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

const int MAX_N=2e5;

typedef long long ll;
int N;
int A[MAX_N];
ll dp[MAX_N];

int main(){
	scanf("%d",&N);
	REP(i,N){
		scanf("%d",&A[i]);
	}
	ll res=A[0];
	int mi=A[0];
	dp[0]=A[0];
	FOR(i,1,N){
		ll d=0;
		res+=A[i];
		d=A[i];
		if (A[i]<mi){
			mi=A[i];
			res+=mi*i;
			d+=mi*i;
		}else{
			int j=i-1;
			while (A[j]>A[i]){
				res+=A[i];
				d+=A[i];
				j--;
			}
			res+=dp[j];
			d+=dp[j];
		}
		dp[i]=d;
	}
	printf("%lld\n",res);
	return 0;
}

Score : 400 points

Problem Statement

One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.

Find the following:

Constraints

1 ≦ N ≦ 200,000

(a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the answer.

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

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85


#include<bits/stdc++.h>
#define N (1001)
using namespace std;
int n,a[N],Keg[N],maxn;
int main()
{
	scanf("%d",&n);
	for (int i=1; i<=n; ++i)
	{
		scanf("%d",&a[i]);
		Keg[a[i]]++; maxn=max(maxn,a[i]);
	}
//	for (int i=(maxn+1)/2; i<=maxn; ++i)
//	{
//		if (maxn%2==0 && i==(maxn+1)/2) Keg[i]-=1;
//		else Keg[i]-=2;
//		if (Keg[i]<0){puts("Impossible"); return 0;}
//	}
//	for (int i=1; i<=maxn/2; ++i)
//		if (Keg[i]) {puts("Impossible"); return 0;}
	puts("Impossible"); return 0;
}

Score : 700 points

Problem Statement

Aoki loves numerical sequences and trees.

One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree.

Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1.

Determine whether such a tree exists.

Constraints

2 ≦ N ≦ 100

1 ≦ a_i ≦ N-1

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If there exists a tree that satisfies the condition, print Possible. Otherwise, print Impossible.

Sample Input 1

5
3 2 2 3 3

Sample Output 1

Possible

The diagram above shows an example of a tree that satisfies the conditions. The red arrows show paths from each vertex to the farthest vertex from it.

Sample Input 2

3
1 1 2

Sample Output 2

Impossible

Sample Input 3

10
1 2 2 2 2 2 2 2 2 2

Sample Output 3

Possible

Sample Input 4

10
1 1 2 2 2 2 2 2 2 2

Sample Output 4

Impossible

Sample Input 5

6
1 1 1 1 1 5

Sample Output 5

Impossible

Sample Input 6

5
4 3 2 3 4

Sample Output 6

Possible


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

int main(){
  string s;cin >> s;
  int k; cin >> k;
  for(int i=0; i<s.size()-1; i++){
    //cout << k << endl;
    if(((int)s.at(i) - 96)==1||k==0){
      continue;
    }else if((27-((int)s.at(i) - 96))<=k){

      //cout << (int)s.at(i) << endl;
      k -= 27-((int)s.at(i)-96);
      s.at(i) = 'a';
    }
  }
  //cout << k << endl;
  k = k%26;
  if(k!=0){
    if(122<s.at(s.size()-1)+k){
      s.at(s.size()-1) = (char)96+(s.at(s.size()-1)+k-122);
    }else{
      s.at(s.size()-1) = (char)s.at(s.size()-1)+k;
    }
  }
  cout << s << endl;
}

Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap


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

int main(){
  string s;
  ll n;
  cin>>s>>n;
  ll len = s.size();
  for(ll i=0;i<len-1;i++){
    if(s[i]=='a')continue;
    if('z'-s[i]+1<=n) {n=n-('z'-s[i]+1);s[i]='a';}
    //cout<<n<<endl;
  }
  if(n>0) s[len-1] = 'a'+((s[len-1]-'a')+n)%26;
  cout<<s<<endl;
  return 0;
}


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

int main(){
    int a,b,h;
    cin>>a>>b>>h;
    cout<<(a+b)*h/2<<endl;
    return 0;
}

Score : 100 points

Problem Statement

You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.

An example of a trapezoid

Find the area of this trapezoid.

Constraints

1≦a≦100

1≦b≦100

1≦h≦100

All input values are integers.

h is even.

Input

The input is given from Standard Input in the following format:

a
b
h

Output

Print the area of the given trapezoid. It is guaranteed that the area is an integer.

Sample Input 1

3
4
2

Sample Output 1

7

When the lengths of the upper base, lower base, and height are 3, 4, and 2, respectively, the area of the trapezoid is (3+4)×2/2 = 7.

Sample Input 2

4
4
4

Sample Output 2

16

In this case, a parallelogram is given, which is also a trapezoid.


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

int main( void ) {

    int a, b, h;
    cin >> a >> b >> h;

    cout << (a + b) * h / 2;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef pair<int, int> P;
typedef vector< vector<P> > graph;

const int INF = 10000000;
const int NONE = -1;

struct Node {
    int at;
    int cost;
    int prev;
    Node(int at, int cost, int prev) : at(at), cost(cost), prev(prev) {}
    bool operator>(const Node &s) const {
        return cost > s.cost;
    }
};

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n, m;
    scanf("%d %d", &n, &m);
    graph e(n);
    for (int i = 0; i < m; i++) {
        int p, q, c;
        scanf("%d %d %d", &p, &q, &c);
        p--;
        q--;
        e[p].emplace_back(q, c);
        e[q].emplace_back(p, c);
    }
    set<P> memo;
    vector<int> minc(n, INF);
    priority_queue<Node, vector<Node>, greater<Node> > pq;
    pq.push(Node(0, 0, NONE));
    //P g(n - 1, NONE);
    while (!pq.empty()) {
        Node x = pq.top();
        pq.pop();
        P key(x.at, x.prev);
        if (memo.find(key) != memo.end()) continue;
        if (x.cost > minc[x.at]) continue;
        if (x.at == n - 1) {
            cout << x.cost << "\n";
            return 0;
        }
        memo.insert(key);
        minc[x.at] = x.cost;
        for (auto i = e[x.at].begin(), f = e[x.at].end(); i != f; ++i) {
            if (memo.find(*i) != memo.end()) continue;
            int to = i->first;
            int c = (*i).second;
            int cost = x.cost + (x.prev != c);
            if (cost < minc[to]) pq.push(Node(to, cost, c));
        }
    }
    cout << "-1\n";
    return 0;
}

Score : 600 points

Problem Statement

Snuke's town has a subway system, consisting of N stations and M railway lines. The stations are numbered 1 through N. Each line is operated by a company. Each company has an identification number.

The i-th ( 1 \leq i \leq M ) line connects station p_i and q_i bidirectionally. There is no intermediate station. This line is operated by company c_i.

You can change trains at a station where multiple lines are available.

The fare system used in this subway system is a bit strange. When a passenger only uses lines that are operated by the same company, the fare is 1 yen (the currency of Japan). Whenever a passenger changes to a line that is operated by a different company from the current line, the passenger is charged an additional fare of 1 yen. In a case where a passenger who changed from some company A's line to another company's line changes to company A's line again, the additional fare is incurred again.

Snuke is now at station 1 and wants to travel to station N by subway. Find the minimum required fare.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq 2×10^5

1 \leq p_i \leq N (1 \leq i \leq M)

1 \leq q_i \leq N (1 \leq i \leq M)

1 \leq c_i \leq 10^6 (1 \leq i \leq M)

p_i \neq q_i (1 \leq i \leq M)

Input

The input is given from Standard Input in the following format:

N M
p_1 q_1 c_1
:
p_M q_M c_M

Output

Print the minimum required fare. If it is impossible to get to station N by subway, print -1 instead.

Sample Input 1

3 3
1 2 1
2 3 1
3 1 2

Sample Output 1

1

Use company 1's lines: 1 → 2 → 3. The fare is 1 yen.

Sample Input 2

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

Sample Output 2

2

First, use company 1's lines: 1 → 3 → 2 → 5 → 6. Then, use company 5's lines: 6 → 7 → 8. The fare is 2 yen.

Sample Input 3

2 0

Sample Output 3

-1


/*input
5 3 5
*/
#include <bits/stdc++.h>
#pragma GCC optimize("unroll-loops,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<double,double> pdd;
#define IOS ios_base::sync_with_stdio(0); cin.tie(0)
#define ALL(a) a.begin(),a.end()
#define SZ(a) ((int)a.size())
#define F first
#define S second
#define REP(i,n) for(int i=0;i<((int)n);i++)
#define pb push_back
#define MP(a,b) make_pair(a,b)
#define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end()))))
#define GET_POS(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin())
template<typename T1,typename T2>
ostream& operator<<(ostream& out,pair<T1,T2> P){
	out<<'('<<P.F<<','<<P.S<<')';
	return out;
}

//}}}
const ll maxn=300005;
const ll maxlg=__lg(maxn)+2;
const ll INF64=8000000000000000000LL;
const int INF=0x3f3f3f3f;
const ll MOD=ll(1e9+7);
const double PI=acos(-1);
//const ll p=880301;
//const ll P=31;

ll mypow(ll a,ll b){
	ll res=1LL;
	while(b){
		if(b&1) res=res*a%MOD;
		a=a*a%MOD;

		b>>=1;
	}
	return res;
}
set<char> st;
int main()
{
	IOS;
	ll a,b,c;
	cin>>a>>b>>c;
	if(a%2&&b%2&&c%2){
		cout<<min({a*b,a*c,b*c});
	}
	else cout<<0;
	return 0;
}

Score : 200 points

Problem Statement

We have a rectangular parallelepiped of size A×B×C, built with blocks of size 1×1×1. Snuke will paint each of the A×B×C blocks either red or blue, so that:

There is at least one red block and at least one blue block.

The union of all red blocks forms a rectangular parallelepiped.

The union of all blue blocks forms a rectangular parallelepiped.

Snuke wants to minimize the difference between the number of red blocks and the number of blue blocks. Find the minimum possible difference.

Constraints

2≤A,B,C≤10^9

Input

The input is given from Standard Input in the following format:

A B C

Output

Print the minimum possible difference between the number of red blocks and the number of blue blocks.

Sample Input 1

3 3 3

Sample Output 1

9

For example, Snuke can paint the blocks as shown in the diagram below.
There are 9 red blocks and 18 blue blocks, thus the difference is 9.

Sample Input 2

2 2 4

Sample Output 2

0

For example, Snuke can paint the blocks as shown in the diagram below.
There are 8 red blocks and 8 blue blocks, thus the difference is 0.

Sample Input 3

5 3 5

Sample Output 3

15

For example, Snuke can paint the blocks as shown in the diagram below.
There are 45 red blocks and 30 blue blocks, thus the difference is 9.


#include <bits/stdc++.h>
typedef long long ll;
const int INF = 1e9,MOD = 1e9+7,ohara = 1e6;
const ll LINF = 1e18;
using namespace std;

#define rep(i,n) for(ll (i)=0;(i)<(int)(n);(i)++)
#define rrep(i,a,b) for(ll i=(a);i<(b);i++)
#define rrrep(i,a,b) for(ll i=(a);i>=(b);i--)
#define all(v) (v).begin(), (v).end()
#define pb(q) push_back(q)
#define Size(n) (n).size()
#define Cout(x) cout<<(x)<<endl

ll n,cnt=0,ans=LINF,a[ohara],b,c,d,cmp,cmpp,m,h,w,x,y,sum=0,pos,hozon[2000+10][2000+10];
int dy[]={1,0,-1,0};
int dx[]={0,1,0,-1};
//int dy[]={-1,0,1,-1,1,-1,0,1};
//int dx[]={-1,-1,-1,0,0,1,1,1};
string alph("abcdefghijklmnopqrstuvwxyz"),s;
bool fl;
struct edge{int to,cost;};

//-------------------------↓↓↓↓↓↓------------------------

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

    cin>>n>>x;
    rep(i,n)cin>>a[i],a[i+n]=a[i];
    rrep(i,n,2*n){
        cnt=0;
        rrrep(j,i,i-n+1){
            if(cnt!=0)hozon[i-n][cnt]=min(hozon[i-n][cnt-1],a[j]);
            else hozon[i-n][cnt]=a[j];
            cnt++;
        }
    }
    rep(mahou,n+1){
        cnt=mahou*x;
        rrep(i,n,2*n){
            cnt+=hozon[i-n][mahou];
        }
         ans=min(ans,cnt);
    }
    Cout(ans);
    return 0;
}

Score : 400 points

Problem Statement

Snuke lives in another world, where slimes are real creatures and kept by some people.
Slimes come in N colors. Those colors are conveniently numbered 1 through N.
Snuke currently has no slime. His objective is to have slimes of all the colors together.

Snuke can perform the following two actions:

Select a color i (1≤i≤N), such that he does not currently have a slime in color i, and catch a slime in color i. This action takes him a_i seconds.

Cast a spell, which changes the color of all the slimes that he currently has. The color of a slime in color i (1≤i≤N-1) will become color i+1, and the color of a slime in color N will become color 1. This action takes him x seconds.

Find the minimum time that Snuke needs to have slimes in all N colors.

Constraints

2≤N≤2,000

a_i are integers.

1≤a_i≤10^9

x is an integer.

1≤x≤10^9

Input

The input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Find the minimum time that Snuke needs to have slimes in all N colors.

Sample Input 1

2 10
1 100

Sample Output 1

12

Snuke can act as follows:

Catch a slime in color 1. This takes 1 second.

Cast the spell. The color of the slime changes: 1 → 2. This takes 10 seconds.

Catch a slime in color 1. This takes 1 second.

Sample Input 2

3 10
100 1 100

Sample Output 2

23

Snuke can act as follows:

Catch a slime in color 2. This takes 1 second.

Cast the spell. The color of the slime changes: 2 → 3. This takes 10 seconds.

Catch a slime in color 2. This takes 1 second.

Cast the soell. The color of each slime changes: 3 → 1, 2 → 3. This takes 10 seconds.

Catch a slime in color 2. This takes 1 second.

Sample Input 3

4 10
1 2 3 4

Sample Output 3

10

Snuke can act as follows:

Catch a slime in color 1. This takes 1 second.

Catch a slime in color 2. This takes 2 seconds.

Catch a slime in color 3. This takes 3 seconds.

Catch a slime in color 4. This takes 4 seconds.


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

int main()
{
  long long n, x;
  long long count = 0;
  cin >> n >> x;

  vector<long long> v(n, 0);

  for (int i = 0; i < n; i++)
  {
    cin >> v[i];
  }

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

  for (int i = 0; i < n; i++)
  {
    if (v[0] + x < v[i])
    {
      count += v[0] + x;
    }
    else
      count += v[i];
  }

  cout << count << endl;

}


Score : 700 points

Problem Statement

Snuke and Ciel went to a strange stationery store. Each of them got a transparent graph paper with H rows and W columns.

Snuke painted some of the cells red in his paper. Here, the cells painted red were 4-connected, that is, it was possible to traverse from any red cell to any other red cell, by moving to vertically or horizontally adjacent red cells only.

Ciel painted some of the cells blue in her paper. Here, the cells painted blue were 4-connected.

Afterwards, they precisely overlaid the two sheets in the same direction. Then, the intersection of the red cells and the blue cells appeared purple.

You are given a matrix of letters a_{ij} (1≤i≤H, 1≤j≤W) that describes the positions of the purple cells. If the cell at the i-th row and j-th column is purple, then a_{ij} is #, otherwise a_{ij} is .. Here, it is guaranteed that no outermost cell is purple. That is, if i=1, H or j = 1, W, then a_{ij} is ..

Find a pair of the set of the positions of the red cells and the blue cells that is consistent with the situation described. It can be shown that a solution always exists.

Constraints

3≤H,W≤500

a_{ij} is # or ..

If i=1,H or j=1,W, then a_{ij} is ..

At least one of a_{ij} is #.

Input

The input is given from Standard Input in the following format:

H W
a_{11}...a_{1W}
:
a_{H1}...a_{HW}

Output

Print a pair of the set of the positions of the red cells and the blue cells that is consistent with the situation, as follows:

The first H lines should describe the positions of the red cells.

The following 1 line should be empty.

The following H lines should describe the positions of the blue cells.

The description of the positions of the red or blue cells should follow the format of the description of the positions of the purple cells.

Sample Input 1

5 5
.....
.#.#.
.....
.#.#.
.....

Sample Output 1

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

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

One possible pair of the set of the positions of the red cells and the blue cells is as follows:

Sample Input 2

7 13
.............
.###.###.###.
.#.#.#...#...
.###.#...#...
.#.#.#.#.#...
.#.#.###.###.
.............

Sample Output 2

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

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

One possible pair of the set of the positions of the red cells and the blue cells is as follows:


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

typedef long long ll;

ll SumSubsets(int * set, int n, int k)
{
    unsigned int pow_set_size = pow(2, n);
    int counter, j;

    ll result = 0;

    for(counter = 0; counter < pow_set_size; counter++)
    {
        ll temp_result = 0, temp_cnt = 0;

        for(j = 0; j < n; j++)
        {
            if(counter & (1 << j)) {
                temp_cnt++;
                temp_result += set[j];

                cout << "in here .." << endl;

            }
        }

        if  (temp_cnt > 0 && temp_result > 0 && ((float)temp_result / (float)temp_cnt) == (float)k ){

            cout << temp_result << " " << temp_cnt << endl;

            result++;
        }
        cout << endl; cout << endl;
    }

    return result;
}

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

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

    ll result = SumSubsets(set, n, k);
    cout << result << endl;

    return 0;
}

Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

The input is given from Standard Input in the following format:

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a 32-bit integer.


#include <iostream> // cout, endl, cin
#include <string> // string, to_string, stoi
#include <vector> // vector
#include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound
#include <utility> // pair, make_pair
#include <tuple> // tuple, make_tuple
#include <cstdint> // int64_t, int*_t
#include <cstdio> // printf
#include <map> // map
#include <queue> // queue, priority_queue
#include <set> // set
#include <stack> // stack
#include <deque> // deque
#include <unordered_map> // unordered_map
#include <unordered_set> // unordered_set
#include <bitset> // bitset
#include <cctype> // isupper, islower, isdigit, toupper, tolower
#include <cmath> // sqrt
#define _GLIBCXX_DEBUG // check []
#define DIVISOR 1000000007

using namespace std;
typedef pair<int,int> pii;
typedef pair<int64_t, int64_t> pII;

template<typename T>
void cins(vector<T>& arr) { for(T& e: arr) cin >> e; }

#ifdef DEBUG
#define debug(fmt, ...) \
    printf("[debug: %s] " fmt, __func__, __VA_ARGS__)
#define ps(arr) \
    debug("size %ld: ", arr.size()); \
    for(auto e: arr) cout << e << " "; \
    cout << endl;
#else
#define debug(fmt, ...)
#define ps(arr)
#endif

int main(void) {
    int num;
    cin >> num;
    vector<int> arr(num);
    cins(arr);

    stack<int> stack;
    int64_t ans = 0;
    stack.push(arr[0]);
    // make even as many as possible
    for(int i = 1; i < num; i++) {
        int cur = arr[i];
        int prev = stack.top(); stack.pop();
        if(prev%2 && cur != 0) {
            ans++;
            prev--;
            cur--;
        }
        stack.push(prev); stack.push(cur);
    }

    while(!stack.empty()) {
        int val = stack.top(); stack.pop();
        debug("%d\n", val);
        ans += (val/2);
    }

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

Score : 400 points

Problem Statement

Snuke has a large collection of cards. Each card has an integer between 1 and N, inclusive, written on it.
He has A_i cards with an integer i.

Two cards can form a pair if the absolute value of the difference of the integers written on them is at most 1.

Snuke wants to create the maximum number of pairs from his cards, on the condition that no card should be used in multiple pairs. Find the maximum number of pairs that he can create.

Constraints

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

All input values are integers.

Input

The input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the maximum number of pairs that Snuke can create.

Sample Input 1

4
4
0
3
2

Sample Output 1

4

For example, Snuke can create the following four pairs: (1,1),(1,1),(3,4),(3,4).

Sample Input 2

8
2
0
1
6
0
8
2
1

Sample Output 2

9


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

#define d(x) cerr << #x ":" << x << endl;
#define dd(x, y) cerr << "(" #x "," #y "):(" << x << "," << y << ")" << endl
#define rep(i, n) for (int i = (int)(0); i < (int)(n); i++)
#define repp(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define all(v) v.begin(), v.end()
#define dump(v)                  \
    cerr << #v ":[ ";            \
    for (auto macro_vi : v) {    \
        cerr << macro_vi << " "; \
    }                            \
    cerr << "]" << endl;
#define ddump(v)                           \
    cerr << #v ":" << endl;                \
    for (auto macro_row : v) {             \
        cerr << "[";                       \
        for (auto macro__vi : macro_row) { \
            cerr << macro__vi << " ";      \
        }                                  \
        cerr << "]" << endl;               \
    }
using lint       = long long;
const int INF    = 1e9;
const lint LINF  = 1e18;
const lint MOD   = 1e9 + 7;
const double EPS = 1e-10;

int main() {
    int N;
    cin >> N;
    vector<lint> A(N, 0);
    lint ans = 0;
    rep(i, N) {
        cin >> A[i];
        ans += A[i] / 2;
        A[i] = A[i] % 2;
    }
    dump(A);
    for (int i = 0; i < N - 1; i++) {
        int gen = min(A[i], A[i + 1]);
        ans += gen;
        A[i] -= gen;
        A[i + 1] -= gen;
    }
    cout << ans << endl;
    return 0;
}


#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<map>
#define _USE_MATH_DEFINES
#include<math.h>
#include<queue>
#include<deque>
#include<stack>
#include<cstdio>
#include<utility>
#include<set>
#include<list>
#include<cmath>
#include<stdio.h>
#include<string.h>
#include<iomanip>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
#define FOR(i, a, b) for (ll i = (a); i <= (b); i++)
#define REP(i, n) FOR(i, 0, n - 1)
#define NREP(i, n) FOR(i, 1, n)
using ll = long long;
using pii = pair<int, int>;
using piii = pair<pii, pii>;
const ll dx[4] = { 0,1,0,-1 };
const ll dy[4] = { -1, 0, 1,0 };
const int INF = 1e9 + 7;
int gcd(int x, int y) {
	if (x < y)swap(x, y);
	if (y == 0)return x;
	return gcd(y, x%y);
}
void mul(ll a, ll b) {
	a = a * b % INF;
}
double mysqrt(double x) {
	double l = 0, r = x;
	for (int i = 0; i < 64; ++i) {
		double m = (l + r) / 2.0;
		if (m*m < x)l = m;
		else r = m;
	}
	return l;
}
///////////////////////////////////////

int main() {
	int N; cin >> N;
	int a[100100];
	REP(i, N)cin >> a[i];
	ll ans = 0;
	for (int i = 0; i < N-1; ++i) {
		if (a[i + 1] > a[i]) {
			ans += a[i];
			a[i + 1] -= a[i];
		}
		else {
			ans += a[i + 1];
			a[i] -= a[i + 1];
			a[i + 1] = 0;
			ans += a[i] / 2;
		}
	}
	cout << ans << endl;
	return 0;
}


#include <algorithm>
#include <iterator>
#include <vector>
#include <iomanip>
#include <iostream>
#include <stack>
#include <queue>
#include <list>
#include <utility>

#include <string>
#include <cstring>

#include <cstdio>
#include <cassert>

// M_PI for pi
#define _USE_MATH_DEFINES
#include <cmath>

using namespace std;

static const int MAX = 100005;

int v[MAX];
int n;

int main(int argc, char* argv[]) {

    cin >> n;

    for (int i = 0; i < n; ++i) {
        cin >> v[i];
    }

    int S = 0;
    int s = 0;

    for (int i = 0; i < n; ++i) {
        s = v[i] / 2;
        S += s;

        v[i] = v[i] / 2;
    }

    for (int i = 1; i < n; ++i) {
        if (v[i] == 1 && v[i-1] == 1) {
            S += 1;
            v[i] = 0;
            v[i-1] = 0;
        }
    }

    cout << S << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int N;
vector<pair<int, int>> A;
int x[101010];

int main() {
  cin >> N;
  A.assign(N + 1, pair<int, int>());
  int a;
  A[0] = make_pair(0, 0);
  for (int i = 1; i <= N; i++) {
    cin >> a;
    A[i] = make_pair(a, i);
  }
  sort(A.begin(), A.end());

  int res = 0;
  for (int i = 2; i <= N; i += 2) {
    if (A[i].second % 2) res++;
  }

  cout << res << endl;

  return 0;
}

Score : 600 points

Problem Statement

Snuke got an integer sequence of length N from his mother, as a birthday present. The i-th (1 ≦ i ≦ N) element of the sequence is a_i. The elements are pairwise distinct.
He is sorting this sequence in increasing order.
With supernatural power, he can perform the following two operations on the sequence in any order:

Operation 1: choose 2 consecutive elements, then reverse the order of those elements.

Operation 2: choose 3 consecutive elements, then reverse the order of those elements.

Snuke likes Operation 2, but not Operation 1. Find the minimum number of Operation 1 that he has to perform in order to sort the sequence in increasing order.

Constraints

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9

If i ≠ j, then A_i ≠ A_j.

All input values are integers.

Input

The input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the minimum number of times Operation 1 that Snuke has to perform.

Sample Input 1

4
2
4
3
1

Sample Output 1

1

The given sequence can be sorted as follows:

First, reverse the order of the last three elements. The sequence is now: 2,1,3,4.

Then, reverse the order of the first two elements. The sequence is now: 1,2,3,4.

In this sequence of operations, Operation 1 is performed once. It is not possible to sort the sequence with less number of Operation 1, thus the answer is 1.

Sample Input 2

5
10
8
5
3
2

Sample Output 2

0


//khodaya khodet komak kon
#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back
#define all(x) x.begin(), x.end()
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
#define int long long

using namespace std;

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

const int N = 20000000 + 10;
const ll MOD = 1000000000 + 7;
const ll INF = 1000000010;
const ll LOG = 25;

int n, m, a[1010][1010], ans[N];
ll k;

int mul(int a, int b){
	return a * 1ll * b % MOD;
}

int add(int a, int b){
	a += b;
	if (a >= MOD) a -= MOD;
	return a;
}

int minu(int a, int b){
	a -= b;
	if (a < 0) a += MOD;
	return a;
}

int POW(int a, int b){
	int res = 1;
	while (b){
		if (b & 1) res = mul(res, a);
		b >>= 1;
		a = mul(a, a);
	}
	return res;
}

int inv(int a){
	return POW(a, MOD - 2);
}

int32_t main(){
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> n >> m >> k;
	if (k >= 20000000) assert(0);
	ans[0] = 1;
	bool R = 0, C = 0;
	for (int i = 1; i <= n; i++){
		for (int j = 1; j <= m; j++){
			char c;
			cin >> c;
			a[i][j] = (c == '#');
		}
	}
	for (int i = 1; i <= n; i++) if (a[i][1] == a[i][m] && a[i][1] == 1) R = 1;
	for (int j = 1; j <= m; j++) if (a[1][j] == a[n][j] && a[1][j] == 1) C = 1;
	if (R & C) return cout << 1, 0;
	if (!(R | C)){
		int cnt = 0;
		for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cnt += a[i][j];
		cout << POW(cnt, k);
		return 0;
	}
	ans[1] = 1;
	int moj = 0, kol = 0, cnt = 0;
	if (R){
		for (int i = 1; i <= n; i++) if (a[i][1] == a[i][m] && a[i][1] == 1) cnt++;
		for (int i = 1; i <= n; i++) for (int j = 1; j < m; j++) if (a[i][j] == 1 && a[i][j + 1] == 1) moj++;
		for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) kol += a[i][j];
	}else{
		for (int j = 1; j <= m; j++) if (a[1][j] == a[n][j] && a[1][j] == 1) cnt++;
		for (int i = 1; i < n; i++) for (int j = 1; j <= m; j++) if (a[i][j] == a[i + 1][j] && a[i][j] == 1) moj++;
		for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) kol += a[i][j];
	}
//	cout << POW(4, 2) << '\n';
	if (k == 1 || k == 0) return cout << 1, 0;
	if (k == 2) return cout << kol - moj, 0;
	ans[2] = kol - moj;
	for (int i = 3; i <= k; i++){
		ans[i] = ans[i - 1] * 1ll * kol % MOD;
		ans[i] -= POW(cnt, i - 2) * 1ll * moj % MOD;
		ans[i] %= MOD;
		ans[i] += MOD;
		ans[i] %= MOD;
	}
//	int ans2 = kol - moj;
//	int x = cnt * moj;
//	int A = minu(POW(kol, k - 2), 1);
//	A = mul(A, inv(kol - 1));
//	ans2 = mul(ans2, POW(kol, k - 2));
//	ans2 = minu(ans2, mul(x, A));
//	cout << ans2;
	cout << ans[k];

	return 0;
}

Score : 1700 points

Problem Statement

Snuke got a grid from his mother, as a birthday present. The grid has H rows and W columns. Each cell is painted black or white. All black cells are 4-connected, that is, it is possible to traverse from any black cell to any other black cell by just visiting black cells, where it is only allowed to move horizontally or vertically.

The color of the cell at the i-th row and j-th column (1 ≦ i ≦ H, 1 ≦ j ≦ W) is represented by a character s_{ij}. If s_{ij} is #, the cell is painted black. If s_{ij} is ., the cell is painted white. At least one cell is painted black.

We will define fractals as follows.
The fractal of level 0 is a 1 × 1 grid with a black cell.
The fractal of level k+1 is obtained by arranging smaller grids in H rows and W columns, following the pattern of the Snuke's grid.
At a position that corresponds to a black cell in the Snuke's grid, a copy of the fractal of level k is placed.
At a position that corresponds to a white cell in the Snuke's grid, a grid whose cells are all white, with the same dimensions as the fractal of level k, is placed.

You are given the description of the Snuke's grid, and an integer K. Find the number of connected components of black cells in the fractal of level K, modulo 10^9+7.

Constraints

1 ≦ H,W ≦ 1000

0 ≦ K ≦ 10^{18}

Each s_{ij} is either # or ..

All black cells in the given grid are 4-connected.

There is at least one black cell in the given grid.

Input

The input is given from Standard Input in the following format:

H W K
s_{11} .. s_{1W}
:
s_{H1} .. s_{HW}

Output

Print the number of connected components of black cells in the fractal of level K, modulo 10^9+7.

Sample Input 1

3 3 3
.#.
###
#.#

Sample Output 1

20

The fractal of level K=3 in this case is shown below. There are 20 connected components of black cells.

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

Sample Input 2

3 3 3
###
#.#
###

Sample Output 2

1

Sample Input 3

11 15 1000000000000000000
.....#.........
....###........
....####.......
...######......
...#######.....
..##.###.##....
..##########...
.###.....####..
.####...######.
###############
#.##..##..##..#

Sample Output 3

301811921


#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int a[N];
int n,Max,Min;

int Find(int Max,int Min)
{
	int MinMoney=INT_MAX,NowMoney=0;
	for(int i=Min;i<=Max;i++)
	{
		NowMoney=0;
		for(int j=1;j<=n;j++)
			NowMoney+=((a[j]-i)*(a[j]-i));
		MinMoney=min(NowMoney,MinMoney);
	}
	return MinMoney;
}
int main()
{
	Max=INT_MIN;
	Min=INT_MAX;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		Max=max(Max,a[i]);
		Min=min(Min,a[i]);
	}
	int money=Find(Max,Min);
	cout<<money<<"\n";
}

Score : 200 points

Problem Statement

Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.

He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).

Find the minimum total cost to achieve his objective.

Constraints

1≦N≦100

-100≦a_i≦100

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum total cost to achieve Evi's objective.

Sample Input 1

2
4 8

Sample Output 1

8

Transforming the both into 6s will cost (4-6)^2+(8-6)^2=8 dollars, which is the minimum.

Sample Input 2

3
1 1 3

Sample Output 2

3

Transforming the all into 2s will cost (1-2)^2+(1-2)^2+(3-2)^2=3 dollars. Note that Evi has to pay (1-2)^2 dollar separately for transforming each of the two 1s.

Sample Input 3

3
4 2 5

Sample Output 3

5

Leaving the 4 as it is and transforming the 2 and the 5 into 4s will achieve the total cost of (2-4)^2+(5-4)^2=5 dollars, which is the minimum.

Sample Input 4

4
-100 -100 -100 -100

Sample Output 4

0

Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 0.


#include<bits/stdc++.h>
using namespace std;
#define arep(i,x,n) for(int i=int(x);i<(int)(n);i++)
#define rep(i,n) for(long long i = 0;i < n;++i)
#define pi 3.141592653589793
#define eps 0.00000001
#define INF 1e9+7
using ll = long long;
using P=pair<int,int>;
using lP=pair<ll,ll>;
using fP=pair<double,double>;
ll const mod=998244353;
const ll MAX=300000;
using vi=vector<int>;
using vc=vector<char>;
using vs=vector<string>;
using vvi =vector<vector<int>>;
using vvc=vector<vector<char>>;
using vvp =vector<vector<P>>;

int main(){
    string s;
    cin>>s;
    int n=s.size();
    rep(i,n-1){
        if(i+2<n&&s[i]==s[i+2]){
            cout<<i+1<<" "<<i+3<<endl;
            return 0;
        }
        if(s[i]==s[i+1]){
            cout<<i+1<<" "<<i+2<<endl;
            return 0;
        }
    }
    cout<<-1<<" "<<-1<<endl;
    return 0;
}

Score : 400 points

Problem Statement

Given a string t, we will call it unbalanced if and only if the length of t is at least 2, and more than half of the letters in t are the same. For example, both voodoo and melee are unbalanced, while neither noon nor a is.

You are given a string s consisting of lowercase letters. Determine if there exists a (contiguous) substring of s that is unbalanced. If the answer is positive, show a position where such a substring occurs in s.

Constraints

2 ≦ |s| ≦ 10^5

s consists of lowercase letters.

Partial Score

200 points will be awarded for passing the test set satisfying 2 ≦ N ≦ 100.

Input

The input is given from Standard Input in the following format:

s

Output

If there exists no unbalanced substring of s, print -1 -1.

If there exists an unbalanced substring of s, let one such substring be s_a s_{a+1} ... s_{b} (1 ≦ a < b ≦ |s|), and print a b. If there exists more than one such substring, any of them will be accepted.

Sample Input 1

needed

Sample Output 1

2 5

The string s_2 s_3 s_4 s_5 = eede is unbalanced. There are also other unbalanced substrings. For example, the output 2 6 will also be accepted.

Sample Input 2

atcoder

Sample Output 2

-1 -1

The string atcoder contains no unbalanced substring.


#include<cstdio>
#include<cstring>
const int N=100000;

char s[N+5];
int P[256],len;
bool f;

bool Pan(int k,int d)
{
	return k>(d>>1);
}

bool Find(int d)
{
	memset(P,0,sizeof(P));
	for(int i=1;i<=d;i++)
		if(Pan(++P[s[i]],d))
		{
			printf("1 %d\n",d);
			f=1; return true;
		}

	for(int i=d+1;i<=len;i++)
	{
		P[s[i-d]]--;
		if(Pan(++P[s[i]],d))
		{
			printf("%d %d\n",i,i+d-1);
			f=1; return true;
		}
	}
	return false;
}

int main()
{
	scanf("%s",s+1);
	len=strlen(s+1);

	int depth=3;
	while(depth<=len&&!Find(depth)) depth++;

	if(!f) puts("-1 -1");
	return 0;
}


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

#define INF 2000000010
#define mod7 1000000007
#define YJ 1145141919
#define INF_INT_MAX 2147483647
#define INF_LL_MAX 9223372036854775807
#define INF_LL 9223372036854775
#define EPS 1e-10
#define Pi acos(-1)
#define LL long long
#define ULL unsigned long long
#define LD long double

using namespace std;

#define MAX_S

string S;

int main(){

  cin >> S;
  for(int i = 0; i < (int)S.length()-1; i++){
    if(S[i] == S[i+1]){
      cout << i+1 << " " << i+2 << endl;
      return 0;
    }
  }

  for(int i = 0; i < (int)S.length()-2; i++){
    if(S[i] == S[i+2]){
      cout << i+1 << " " << i+3 << endl;
      return 0;
    }
  }

  cout << -1 << " " << -1 << endl;

  return 0;

}


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

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

Score : 100 points

Problem Statement

There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?

Constraints

1≦N≦100

Input

The input is given from Standard Input in the following format:

N

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is 1+2+3=6.

Sample Input 2

10

Sample Output 2

55

The sum of the integers from 1 to 10 is 55.

Sample Input 3

1

Sample Output 3

1

Only one child. The answer is 1 in this case.


#include<bits/stdc++.h>
using namespace std;
int main()
{
  string s;
  cin>>s;
  vector<char>ans(s.size());
  int j=-1;
  for(int i=0;i<s.size();i++)
  {
      if(s[i]=='B')
      {
        if(j==-1)
          continue;
        else
          j--;
      }
      else
      {
        ans[j+1]=s[i];
        j++;
      }
  }
  for(int i=0;i<=j;i++)
  {
    cout<<ans[i];
  }

  return 0;
}

Score : 200 points

Problem Statement

Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.

To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:

The 0 key: a letter 0 will be inserted to the right of the string.

The 1 key: a letter 1 will be inserted to the right of the string.

The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.

Sig has launched the editor, and pressed these keys several times. You are given a string s, which is a record of his keystrokes in order. In this string, the letter 0 stands for the 0 key, the letter 1 stands for the 1 key and the letter B stands for the backspace key. What string is displayed in the editor now?

Constraints

1 ≦ |s| ≦ 10 (|s| denotes the length of s)

s consists of the letters 0, 1 and B.

The correct answer is not an empty string.

Input

The input is given from Standard Input in the following format:

s

Output

Print the string displayed in the editor in the end.

Sample Input 1

01B0

Sample Output 1

00

Each time the key is pressed, the string in the editor will change as follows: 0, 01, 0, 00.

Sample Input 2

0BB1

Sample Output 2

1

Each time the key is pressed, the string in the editor will change as follows: 0, (empty), (empty), 1.


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

int main()
{
	string s;
	string buf;
	cin >> s;
	for (char c : s)
	{
		if (c == 'B')
		{
			if (!buf.empty())buf.pop_back();
		}
		else
		{
			buf.push_back(c);
		}
	}
	cout << buf << endl;
	return 0;
}


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

int main()
{
    int n,i,j,p=0;
    int x[105];
    int y[1005];
    long long sum;
    int minone=99999;
    int maxone=0;
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>x[i];
        minone=min(minone,x[i]);
        maxone=max(maxone,x[i]);
    }
    for(i=minone;i<=maxone;i++)
    {
        sum=0;
        for(j=0;j<n;j++)
        {
            sum += pow(( x[j]-i),2 );
        }
        y[p++]=sum;
    }
    sort(y,y+p);
    cout<<y[0]<<endl;
    return 0;
}


#include<stdio.h>
#include<string.h>
int main(){
int a;
char b[10005];
scanf("%s",b);
a=strlen(b);
for(int i=0;i<a-2;i++){
if(b[i]==b[i+1]){
printf("%d %d",i+1,i+2);
return 0;
}
if(b[i]==b[i+2]){
printf("%d %d",i+1,i+3);
return 0;
}
}
if(b[a-2]==b[a-1]){
printf("%d %d",a-1,a);
return 0;
}

printf("%d  %d",-1,-1);
return 0;
}


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

int a, b;

int main() {
    scanf("%d%d", &a, &b);
    if(a <= 0 && b >= 0) printf("Zero\n");
    else if(a < 0 && b < 0) {
        if(b - a + 1 % 2 == 0) printf("Positive\n");
        else printf("Negative\n");
    } else printf("Positive\n");
}

Problem Statement

You are given two integers a and b (a≤b). Determine if the product of the integers a, a+1, …, b is positive, negative or zero.

Constraints

a and b are integers.

-10^9≤a≤b≤10^9

Partial Score

In test cases worth 100 points, -10≤a≤b≤10.

Input

The input is given from Standard Input in the following format:

a b

Output

If the product is positive, print Positive. If it is negative, print Negative. If it is zero, print Zero.

Sample Input 1

1 3

Sample Output 1

Positive

1×2×3=6 is positive.

Sample Input 2

-3 -1

Sample Output 2

Negative

(-3)×(-2)×(-1)=-6 is negative.

Sample Input 3

-1 1

Sample Output 3

Zero

(-1)×0×1=0.


#include<bits/stdc++.h>
using namespace std;
int main()
{
  int a,b;
  cin>>a>>b;
  if(a>0 && b>0)
    cout<<"Positive"<<endl;
  else
    if(a<0 && b<0)
    {
      if(b==a)
        cout<<"Positive"<<endl;
      else
      if(b-a%2==0)
        cout<<"Negative"<<endl;
      else
        cout<<"Positive"<<endl;
    }
  else
    cout<<"Zero"<<endl;

  return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pii;
#define FOR(i, j, k, in) for (ll i=j ; i<k ; i+=in)
#define REP(i, j) FOR(i, 0, j, 1)
#define ALL(_a) _a.begin(),_a.end()
#define mp make_pair
#define eb emplace_back
#define X first
#define Y second

const ll MOD=1000000007;
const ll INF=0x3f3f3f3f3f3f3f3f;
const ll MAXN=1e5+5;
const ll MAXLG=__lg(MAXN)+2;

struct QUERY {
    ll x,y,z;
};

struct SOLVER {
    vector<ll> qid;
    ll L,R;
};

ll n,m,q,ans[MAXN];
vector<pii> edge;
vector<QUERY> Q;
ll djs[MAXN],sz[MAXN];

void init() {
    REP (i,MAXN) {
        djs[i] = i;
        sz[i] = 1;
    }
}

ll fnd(ll x) {
    return djs[x] == x ? x : djs[x] = fnd(djs[x]);
}

void uni(ll x,ll y) {
    if (sz[x=fnd(x)] < sz[y=fnd(y)]) swap(x,y);
    djs[y] = x;
    sz[x] += sz[y];
}

/********** Good Luck :) **********/
int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> n >> m;

    edge.eb(-1,-1);
    REP (i,m) {
        ll u,v;
        cin >> u >> v;
        edge.eb(u,v);
    }

    cin >> q;
    REP (i,q) {
        ll x,y,z;
        cin >> x >> y >> z;
        Q.push_back({x,y,z});
    }

    vector<ll> qid;
    REP (i,q) {
        qid.eb(i);
    }

    queue<SOLVER> BFS;
    BFS.push({qid,0,m+1});

    ll state = INF;
    while (BFS.size()) {
        SOLVER cur = BFS.front();BFS.pop();
        if (cur.L == cur.R - 1) {
            for (auto v:cur.qid) {
                ans[v] = cur.L;
            }
            continue;
        }

        ll mid = (cur.L + cur.R) / 2;
        if (mid - 1 < state) {
            init();
            state = 0;
        }

        while (state < mid - 1) {
            state++;
            if (fnd(edge[state].X) != fnd(edge[state].Y)) {
                uni(edge[state].X,edge[state].Y);
            }
        }

        vector<ll> lV,rV;
        for (auto v:cur.qid) {
            ll siz = (fnd(Q[v].x) == fnd(Q[v].y) ? sz[fnd(Q[v].x)]:sz[fnd(Q[v].x)] + sz[fnd(Q[v].y)]);
            if (siz >= Q[v].z) {
                lV.eb(v);
            } else {
                rV.eb(v);
            }
        }

        BFS.push({lV,cur.L,mid});
        BFS.push({rV,mid,cur.R});
    }

    REP (i,q) {
        cout << ans[i] << endl;
    }

    return 0;
}


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

int main(){
	int a, b;
	cin>>a>>b;
	if(a <= 0 and b >= 0)	cout<<"Zero\n";
	else{
		if(a > 0)	cout<<"Positive\n";
		else{
			int diff = (b - a) + 1;
			if((diff % 2) == 0)	cout<<"Positive\n";
			else cout<<"Negative\n";
		}
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main(){
  int n,m;cin>>n>>m;
  int ball[n+1];
  for(int i=0;i<n;i++) ball[i]=1;
  bool red[n+1];
  for(int i=0;i<n+1;i++) red[i]=false;
  red[0]=true;
  for(int i=0;i<m;i++){
      int x,y;cin>>x>>y;
      x--;y--;
      ball[x]--;ball[y]++;
      if(red[x]){
          red[y]=true;
      }
      if(ball[x]==0) red[x]=false;
  }
  int res=0;
  for(int i=0;i<n;i++) if(red[i]) res++;
  cout<<res<<endl;
}

Problem Statement

We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball.

Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i.

Find the number of boxes that may contain the red ball after all operations are performed.

Constraints

2≤N≤10^5

1≤M≤10^5

1≤x_i,y_i≤N

x_i≠y_i

Just before the i-th operation is performed, box x_i contains at least 1 ball.

Input

The input is given from Standard Input in the following format:

N M
x_1 y_1
:
x_M y_M

Output

Print the number of boxes that may contain the red ball after all operations are performed.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

2

Just after the first operation, box 1 is empty, box 2 contains one red ball and one white ball, and box 3 contains one white ball.

Now, consider the second operation. If Snuke picks the red ball from box 2, the red ball will go into box 3. If he picks the white ball instead, the red ball will stay in box 2.
Thus, the number of boxes that may contain the red ball after all operations, is 2.

Sample Input 2

3 3
1 2
2 3
2 3

Sample Output 2

1

All balls will go into box 3.

Sample Input 3

4 4
1 2
2 3
4 1
3 4

Sample Output 3

3


//DPするけど、遷移を節約する. DPするとO(N^2)なんて思ったのが間違いだったorz

#include <iostream>
using namespace std;

int n, m;
int x[100000], y[100000];
bool dp[100000];	//dp[i] = 箱iに赤いキャンディーがある状態(0, 1)
int cnt[100000];	//cnt[i] = 箱iにある飴の総数

int main() {
	int i;

	cin >> n >> m;
	for (i = 0; i < m; i++) { cin >> x[i] >> y[i]; x[i]--; y[i]--; }

	for (i = 0; i < n; i++) { dp[i] = false; cnt[i] = 1; }
	dp[0] = true;

	for (i = 0; i < m; i++) {
		if (!dp[x[i]]) { }
		else if (cnt[x[i]] == 1) { dp[x[i]] = false; dp[y[i]] = true; }
		else { dp[x[i]] = true; dp[y[i]] = true; }
		cnt[x[i]]--;
		cnt[y[i]]++;
	}

	int ans = 0;
	for (i = 0; i < n; i++) {
		if (dp[i]) {
			ans++;
		}
	}
	cout << ans << endl;
	return 0;
}


#include <bits/stdc++.h>
#include <ext/rope>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#pragma GCC optimize("Ofast")
//#pragma GCC optimize("unroll-loops")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define ll long long
//#define int long long
#define pb push_back
#define x first
#define ld long double
#define y second
#define mk(a,b) make_pair(a,b)
#define rr return 0
#define sqr(a) ((a)*(a))
#define all(a) a.begin(),a.end()

using namespace std;
using namespace __gnu_cxx;
using namespace __gnu_pbds;
template<class value, class cmp = less<value> >
using ordered_set = tree<value, null_type, cmp, rb_tree_tag, tree_order_statistics_node_update>;
template<class value, class cmp = less_equal<value> >
using ordered_multiset = tree<value, null_type, cmp, rb_tree_tag, tree_order_statistics_node_update>;
template<class key, class value, class cmp = less<key> >
using ordered_map = tree<key, value, cmp, rb_tree_tag, tree_order_statistics_node_update>;

/// find_by_order()
/// order_of_key()
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
inline int randll(int l = INT_MIN, int r = INT_MAX) {
    return uniform_int_distribution<int>(l, r)(rng);
}
const int MOD = 1e9 + 7;
inline int mul (int a, int b) {
    return ((ll)a * b) % MOD;
}
inline void add (int &a, int x) {
    a += x;
    if (a < 0) a += MOD;
    if (a >= MOD) a -= MOD;
}
inline int binpow (int a, int n) {
    int ans = 1;
    while (n) {
        if (n & 1) {
            ans = mul(ans, a);
        }
        a = mul(a, a);
        n >>= 1;
    }
    return ans;
}
inline int inv (int x) {
    return binpow(x, MOD - 2);
}
const int N = 2e5 + 11;
int f[N] = {}, fi[N] = {};
inline int C (int n, int k) {
    return mul(f[n], mul(fi[k], fi[n - k]));
}
inline int cnt_way (int n, int m) {
    return C(n + m - 2, n - 1);
}
main()
{
    ios::sync_with_stdio(0);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    f[0] = 1;
    for (int i = 1; i < N; i++) f[i] = mul(f[i - 1], i);
    fi[N - 1] = inv(f[N - 1]);
    for (int i = N - 2; i >= 0; i--) {
        fi[i] = mul(fi[i + 1], i + 1);
    }
    int n, m, a, b, ans = 0;
    cin >> n >> m >> a >> b;
    for (int i = 0; i < n - a; i++) {
        add(ans, mul(cnt_way(i + 1, b), cnt_way(n - i, m - b)));
    }
    cout << ans << '\n';
}

Score : 400 points

Problem Statement

We have a large square grid with H rows and W columns.
Iroha is now standing in the top-left cell.
She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.

However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there are A×B forbidden cells.) There is no restriction on entering the other cells.

Find the number of ways she can travel to the bottom-right cell.

Since this number can be extremely large, print the number modulo 10^9+7.

Constraints

1 ≦ H, W ≦ 100,000

1 ≦ A < H

1 ≦ B < W

Input

The input is given from Standard Input in the following format:

H W A B

Output

Print the number of ways she can travel to the bottom-right cell, modulo 10^9+7.

Sample Input 1

2 3 1 1

Sample Output 1

2

We have a 2×3 grid, but entering the bottom-left cell is forbidden. The number of ways to travel is two: "Right, Right, Down" and "Right, Down, Right".

Sample Input 2

10 7 3 4

Sample Output 2

3570

There are 12 forbidden cells.

Sample Input 3

100000 100000 99999 99999

Sample Output 3

1

Sample Input 4

100000 100000 44444 55555

Sample Output 4

738162020


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+10,p=1e9+7;
int inc(int x,int y){x+=y;return x>=p?x-p:x;}
int mul(int x,int y){return (ll)x*y%p;}
int power(int x,int y){
	int ans=1;
	for (;y;y>>=1,x=mul(x,x))
		if (y&1) ans=mul(ans,x);
	return ans;
}
int n,m,a,b,fac[N],ifac[N];
int C(int n,int m){
	return mul(fac[n],mul(ifac[m],ifac[n-m]));
}
int main()
{
	cin>>n>>m>>a>>b;
	fac[0]=1;
	for (int i=1;i<N;i++) fac[i]=mul(fac[i-1],i);
	ifac[N-1]=power(fac[N-1],p-2);
	for (int i=N-1;i;i--) ifac[i-1]=mul(ifac[i],i);
	int ans=0;
	for (int i=b+1;i<=m;i++) ans=inc(ans,mul(C(n-a+i-2,n-a-1),C(a-1+m-i,a-1)));
	cout<<ans<<endl;
	return 0;
}


#include<cstdio>
#include<algorithm>
#include<iostream>
#include<queue>
#include<set>
#define rep(i,s,t) for(register int i=s;i<=t;++i)
#define _rep(i,s,t) for(register int i=s;i>=t;--i)
#define Rep(i,s,t) for(register int i=s;i<t;++i)
#define go(x) for(register int e=las[x];e;e=nxt[e])
#define re register
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define pii pair<int,int>
#define gi(x) read(x)
#define gii(x,y) read(x),read(y)
#define giii(x,y,z) read(x),read(y),read(z)
#define ms(f,x) memset(f,x,sizeof f)
#define open(x) freopen(#x".in","r",stdin),freopen(#x".out","w",stdout)
namespace IO{
    #define gc getchar()
    #define pc(x) putchar(x)
    template<typename T>inline void read(T &x){
        x=0;int f=1;char ch=gc;while(ch>'9'||ch<'0'){if(ch=='-')f=-1;ch=gc;}
        while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+ch-'0',ch=gc;x*=f;return;
    }
    template<typename T>inline void write(T x=0){
        T wr[51];wr[0]=0;if(x<0)pc('-'),x=-x;if(!x)pc(48);
        while(x)wr[++wr[0]]=x%10,x/=10;while(wr[0])pc(48+wr[wr[0]--]);
		putchar('\n');
		return;
    }
}
using IO::read;
using IO::write;
using namespace std;
#define gi(x) read(x)
int a[233333];
long long sum;
int n;
int main(){
    gi(n);
    rep(i,1,n+n)
        gi(a[i]);
    sort(a+1,a+n+n+1);
    for(int i=1;i<=n+n;i+=2)
        sum+=a[i];
    cout<<sum<<endl;
    return 0;
}

Score : 200 points

Problem Statement

Snuke is having a barbeque party.

At the party, he will make N servings of Skewer Meal.

Example of a serving of Skewer Meal

He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i.
Also, he has an infinite supply of ingredients.

To make a serving of Skewer Meal, he picks 2 skewers and threads ingredients onto those skewers.
Let the length of the shorter skewer be x, then the serving can hold the maximum of x ingredients.

What is the maximum total number of ingredients that his N servings of Skewer Meal can hold, if he uses the skewers optimally?

Constraints

1≦N≦100

1≦L_i≦100

For each i, L_i is an integer.

Input

The input is given from Standard Input in the following format:

N
L_1 L_2 ... L_{2N}

Output

Print the maximum total number of ingredients that Snuke's N servings of Skewer Meal can hold.

Sample Input 1

2
1 3 1 2

Sample Output 1

3

If he makes a serving using the first and third skewers, and another using the second and fourth skewers, each serving will hold 1 and 2 ingredients, for the total of 3.

Sample Input 2

5
100 1 2 3 14 15 58 58 58 29

Sample Output 2

135


// luogu-judger-enable-o2
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define ez(i,x) for(int i = h[x]; i; i = e[i].next)
using namespace std;
const int N = 2005;
int h[N], dis[N], vis[N];
int fa[N];
int n, cnt, k;
int ans;
struct edge{
	int from,to, next;
}e[N<<1];

void add(int u, int v) {
	e[++cnt] = (edge){u, v, h[u]}; h[u] = cnt;
	e[++cnt] = (edge){v, u, h[v]}; h[v] = cnt;
}

void dfs(int x){
	ez(i,x) {
		int v = e[i].to;
		if (dis[v]) continue;
		dis[v] = dis[x] + 1;
		dfs(v);
	}
}
int main() {
	scanf("%d %d", &n, &k);
	for (int i = 1; i < n; i++) {
		int u, v;
		scanf("%d %d", &u, &v);
		add(u, v);
	}
	ans = 0x7fffffff;
	if (k & 1){
		for (int i = 1; i <= n; i += 2) {
			int u = e[i].from, v = e[i].to;
			memset(dis, 0, sizeof(dis));
			dis[v] = 1; dis[u] = 1;
			dfs(v); dfs(u);
			cnt = 0;
			for (int i = 1; i <= n; i++) if (dis[i] > (k + 1) / 2) ++cnt;
			ans = min(ans, cnt);
		}
	}
	else {
		for (int i = 1; i <= n; i++) {
			memset(dis, 0, sizeof(dis));
			dis[i] = 1;
			dfs(i);
			cnt = 0;
			for (int i = 1; i <= n; i++) if (dis[i] > k / 2 + 1) ++cnt ;
			ans = min(ans, cnt);
		}

	}
	cout << ans << endl;

}

Score : 600 points

Problem Statement

Given an undirected tree, let the distance between vertices u and v be the
number of edges on the simple path from u to v.
The diameter of a tree is the maximum among the distances between any two vertices.
We will call a tree good if and only if its diameter is at most K.

You are given an undirected tree with N vertices numbered 1 through N.
For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i.

You want to remove zero or more vertices from the tree, so that the resulting tree is good.
When a vertex is removed, all incident edges will also be removed.
The resulting graph must be connected.

Find the minimum number of vertices that you need to remove in order to produce a good tree.

Constraints

2≦N≦2000

1≦K≦N-1

1≦A_i≦N, 1≦B_i≦N

The graph defined by A_i and B_i is a tree.

Input

The input is given from Standard Input in the following format:

N K
A_1 B_1
A_2 B_2
:
A_{N-1} B_{N-1}

Output

Print the minimum number of vertices that you need to remove in order to produce a good tree.

Sample Input 1

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

Sample Output 1

2

The tree is shown below. Removing vertices 5 and 6 will result in a good tree with the diameter of 2.

Sample Input 2

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

Sample Output 2

0

Since the given tree is already good, you do not need to remove any vertex.


#include <bits/stdc++.h>

using namespace std;

//#define FILE_IO

int main()
{
    #ifdef FILE_IO
    freopen("1.in", "r", stdin);
    freopen("1.out", "w", stdout);
    #endif

    int N, M;
    int v[100005];
    scanf("%d%d", &N, &M);
    int cnt = 0;
    for(int i = 1; i <= M; i++)
    {
        scanf("%d", &v[i]);
        cnt += (v[i] & 1);
    }
    if(cnt > 1)
    {
        printf("Impossible\n");
        return 0;
    }

    for(int i = 1; i <= M; i++)
        printf("%d ", v[i]);
    printf("\n");

    vector <int> r;
    r.push_back(v[1] - 1);
    for(int i = 2; i < M; i++)
        r.push_back(v[i]);
    r.push_back(v[M] + 1);

    if(M == 1)
    {
        r.pop_back();
        r.push_back(1);
    }
    if(r[0] == 0)
        r.erase(r.begin());

    printf("%d\n", (int)r.size());
    for(auto x: r)
        printf("%d ", x);

    return 0;
}

Score : 1000 points

Problem Statement

Snuke got a present from his mother on his birthday.
The present was a pair of two sequences a and b, consisting of positive integers.
They satisfied all of the following properties:

The sum of all elements of a is N.

The sum of all elements of b is N.

Any string of length N that satisfies the following two conditions (1) and (2) will also satisfy the condition (3).

(1) Any of the following forms a palindrome: the first a_1 letters, the following a_2 letters, the following a_3 letters and so on.

(2) Any of the following forms a palindrome: the first b_1 letters, the following b_2 letters, the following b_3 letters and so on.

(3) All N letters are the same.

He was happy, until one day he lost both of the sequences.
Now, he only remembers that the sequence a was a permutation of another sequence A of length M.

To bring him happiness again, his mother has decided to give him another pair of sequences a and b that satisfies his favorite properties and is consistent with his memory.

Constraints

1≦N≦10^5

1≦M≦100

1≦A_i≦10^5

The sum of all A_i equals N.

Input

The input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

If there exists a pair of sequences a and b that satisfies the properties and is consistent with Snuke's memory, print three lines. The first line must contain the sequence a, the second line must contain the length of the sequence b, and the third line must contain the sequence b.

If such a pair does not exist (because Snuke's memory is wrong or some other reason), print a single line containing the word Impossible (case-sensitive).

Sample Input 1

3 2
2 1

Sample Output 1

1 2
1
3

Sample Input 2

6 1
6

Sample Output 2

6
3
1 2 3

Sample Input 3

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

Sample Output 3

Impossible