# include <iostream>
# include <cmath>
# include <algorithm>
# include <stdio.h>
# include <cstdint>
# include <cstring>
# include <string>
# include <cstdlib>
# include <vector>
# include <bitset>
# include <map>
# include <queue>
# include <ctime>
# include <stack>
# include <set>
# include <list>
# include <random>
# include <deque>
# include <functional>
# include <iomanip>
# include <sstream>
# include <fstream>
# include <complex>
# include <numeric>
# include <immintrin.h>
# include <cassert>
# include <array>
# include <tuple>
# include <unordered_map>
# include <unordered_set>
# include <thread>

using namespace std;

using ll = long long;
using ull = unsigned long long;
using ld = long double;
using ui32 = unsigned int;
constexpr ll INFLL = 1e18;

#define CHECK_IMPL1(cond)              \
if (!(cond)) {                         \
    DEBUG("expected cond: " << #cond); \
    assert(cond);                      \
}

#define CHECK_IMPL2(cond, message)                                            \
if (!(cond)) {                                                                \
    DEBUG("expected cond: " << #cond << " failed with message: " << message); \
    assert(cond);                                                             \
}
#define CHECK_IMPL(_1, _2, NAME, ...) NAME
#define CHECK(...) CHECK_IMPL(__VA_ARGS__, CHECK_IMPL2, CHECK_IMPL1, CHECK_IMPL0)(__VA_ARGS__)

#ifdef __APPLE__
#define DEBUG(message) std::cerr << message << "\n";
#else
#define DEBUG(message)
#endif

pair<int, int> dfs(int v, const vector<vector<int>>& g) {
  int mx = 0;
  int sz = 1;
  for (auto u : g[v]) {
    auto temp = dfs(u, g);
    mx = max(mx, temp.first + 1);
    sz += temp.second;
  }
  while ((1 << mx) < sz) {
    ++mx;
  }
  return {mx, sz};
}

void solve() {
  int n;
  cin >> n;
  vector<int> a(n);
  vector<vector<int>> g(n);
  for (int i = 1; i < n; i++) {
    cin >> a[i];
    --a[i];
    g[a[i]].push_back(i);
  }
  cout << dfs(0, g).first << "\n";
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
#ifdef __APPLE__
  freopen("input.txt", "r", stdin);
  // freopen("output.txt", "w", stdout);
#endif
  int t = 1;
//  cin >> t;
  for (int i = 1; i <= t; i++) {
    solve();
  }
  return 0;
}

Score : 800 points

Problem Statement

N contestants participated in a competition. The total of N-1 matches were played in a knockout tournament.
For some reasons, the tournament may not be "fair" for all the contestants.
That is, the number of the matches that must be played in order to win the championship may be different for each contestant. The structure of the tournament is formally described at the end of this statement.

After each match, there were always one winner and one loser. The last contestant standing was declared the champion.

Figure: an example of a tournament

For convenience, the contestants were numbered 1 through N. The contestant numbered 1 was the champion, and the contestant numbered i(2 ≦ i ≦ N) was defeated in a match against the contestant numbered a_i.

We will define the depth of the tournament as the maximum number of the matches that must be played in order to win the championship over all the contestants.

Find the minimum possible depth of the tournament.

The formal description of the structure of the tournament is as follows. In the i-th match, one of the following played against each other:

Two predetermined contestants

One predetermined contestant and the winner of the j-th match, where j(j<i) was predetermined

The winner of the j-th match and the winner of the k-th match, where j and k (j,k<i, j ≠ k) were predetermined

Such structure is valid structure of the tournament, if and only if no contestant who has already been defeated in a match will never play in a match, regardless of the outcome of the matches.

Constraints

2 ≦ N ≦ 10^5

1 ≦ a_i ≦ N(2 ≦ i ≦ N)

It is guaranteed that the input is consistent (that is, there exists at least one tournament that matches the given information).

Input

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

N
a_2
:
a_N

Output

Print the minimum possible depth of the tournament.

Sample Input 1

5
1
1
2
4

Sample Output 1

3

The following tournament and the result of the matches are consistent with the given information:

In the first match, contestants 4 and 5 played against each other, and contestant 4 won.

In the second match, contestants 2 and 4 played against each other, and contestant 2 won.

In the third match, contestants 1 and 3 played against each other, and contestant 1 won.

In the fourth match, contestants 1 and 2 played against each other, and contestant 1 won.

The depth of this tournament is 3, since contestant 5 must play three matches in order to win the championship.
There is no tournament with depth 2 or less that is consistent with the given information, thus the output should be 3.

Sample Input 2

7
1
2
1
3
1
4

Sample Output 2

3

Sample Input 3

4
4
4
1

Sample Output 3

3


#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
//#define MOD 998244353
#define INF 1145141919810893364
//#define INF 810114514
//#define PI 3.141592653589
typedef pair<int,int> PP;
typedef long long ll;
#define int ll
#define setdouble setprecision
#define REP(i,n) for(int i=0;i<(n);++i)
#define OREP(i,n) for(int i=1;i<=(n);++i)
#define RREP(i,n) for(int i=(n)-1;i>=0;--i)
#define GOODBYE do { cout << "No" << endl; return 0; } while (false)
#define MM <<" "<<
#define Endl endl

signed main(void){
    int N;
    string S;
    cin >> N;
    cin >> S;
    int Ans=0;
    int now=0;
    REP(i,N-1){
        if(S[i]=='I'){
            now++;
        }else{
            now--;
        }
        Ans=max(Ans,now);
    }
    cout << Ans << endl;
    return 0;
}

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

Score : 200 points

Problem Statement

You have an integer variable x.
Initially, x=0.

Some person gave you a string S of length N, and using the string you performed the following operation N times.
In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D.

Find the maximum value taken by x during the operations (including before the first operation, and after the last operation).

Constraints

1≤N≤100

|S|=N

No characters except I and D occur in S.

Input

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

N
S

Output

Print the maximum value taken by x during the operations.

Sample Input 1

5
IIDID

Sample Output 1

2

After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.

Sample Input 2

7
DDIDDII

Sample Output 2

0

The initial value x=0 is the maximum value taken by x, thus the output should be 0.

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;
long long n,a,b,ans;
long long x[100005];
int main(){
    cin>>n>>a>>b;
    for(int i=1;i<=n;i++){
    	cin>>x[i];
	}
    for(int i=1;i<n;i++){
    	ans+=min(a*(x[i+1]-x[i]),b);
	}
    cout<<ans<<endl;
    return 0;
}

Score : 500 points

Problem Statement

There are N towns on a line running east-west.
The towns are numbered 1 through N, in order from west to east.
Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value.
The coordinate of town i is X_i.

You are now at town 1, and you want to visit all the other towns.
You have two ways to travel:

Walk on the line.
Your fatigue level increases by A each time you travel a distance of 1, regardless of direction.

Teleport to any location of your choice.
Your fatigue level increases by B, regardless of the distance covered.

Find the minimum possible total increase of your fatigue level when you visit all the towns in these two ways.

Constraints

All input values are integers.

2≤N≤10^5

1≤X_i≤10^9

For all i(1≤i≤N-1), X_i<X_{i+1}.

1≤A≤10^9

1≤B≤10^9

Input

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

N A B
X_1 X_2 ... X_N

Output

Print the minimum possible total increase of your fatigue level when you visit all the towns.

Sample Input 1

4 2 5
1 2 5 7

Sample Output 1

11

From town 1, walk a distance of 1 to town 2, then teleport to town 3, then walk a distance of 2 to town 4.
The total increase of your fatigue level in this case is 2×1+5+2×2=11, which is the minimum possible value.

Sample Input 2

7 1 100
40 43 45 105 108 115 124

Sample Output 2

84

From town 1, walk all the way to town 7.
The total increase of your fatigue level in this case is 84, which is the minimum possible value.

Sample Input 3

7 1 2
24 35 40 68 72 99 103

Sample Output 3

12

Visit all the towns in any order by teleporting six times.
The total increase of your fatigue level in this case is 12, which is the minimum possible value.


#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <queue>
#include <utility>
#include <map>
#include <numeric>
#include <iomanip>
#define ll long long
#define pi 3.14159265358979323846
using namespace std;
using p = pair<ll, ll>;
ll dx[4] = {-1, 0, 1, 0};
ll dy[4] = {0, 1, 0, -1};
/*
 vector<vector<ll>> g(n+1);
    for(ll i = 0; i < m; i++){
        ll a, b;
        cin >> a >> b;
        g[a].push_back(b);
        g[b].push_back(a);
    }
    vector<ll> dist(n+1, -1);
    queue<ll> que;
    que.push(1);
    dist[1] = 0;
    while(!que.empty()){
        ll v = que.front();
        que.pop();
        for(ll nv : g[v]){
            if(dist[nv]!=-1) continue;
            dist[nv] = dist[v]+1;
            que.push(nv);
        }
    }
*/

int main(){
    ll a, b, c, d;
    cin >> a >> b >> c >> d;
    string s;
    for(ll i = 0; i < c-a; i++)
        s+='R';
    for(ll i = 0; i < d-b; i++)
        s+='U';
    for(ll i = 0; i < c-a; i++)
        s+='L';
    for(ll i = 0; i < d-b+1; i++)
        s+='D';
    for(ll i = 0; i < c-a+1; i++)
        s+='R';
    for(ll i = 0; i < d-b+1; i++)
        s+='U';
    s+="LU";
    for(ll i = 0; i < c-a+1; i++)
        s+='L';
    for(ll i = 0; i < d-b+1; i++)
        s+='D';
    s+='R';
    cout << s << endl;
    return 0;
}

Score : 300 points

Problem Statement

Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.

Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.

Here, both the x- and y-coordinates before and after each movement must be integers.

He will first visit the point (tx,ty) where sx < tx and sy < ty, then go back to the point (sx,sy), then visit the point (tx,ty) again, and lastly go back to the point (sx,sy).

Here, during the whole travel, he is not allowed to pass through the same point more than once, except the points (sx,sy) and (tx,ty).

Under this condition, find a shortest path for him.

Constraints

-1000 ≤ sx < tx ≤ 1000

-1000 ≤ sy < ty ≤ 1000

sx,sy,tx and ty are integers.

Input

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

sx sy tx ty

Output

Print a string S that represents a shortest path for Dolphin.

The i-th character in S should correspond to his i-th movement.

The directions of the movements should be indicated by the following characters:

U: Up

D: Down

L: Left

R: Right

If there exist multiple shortest paths under the condition, print any of them.

Sample Input 1

0 0 1 2

Sample Output 1

UURDDLLUUURRDRDDDLLU

One possible shortest path is:

Going from (sx,sy) to (tx,ty) for the first time: (0,0) → (0,1) → (0,2) → (1,2)

Going from (tx,ty) to (sx,sy) for the first time: (1,2) → (1,1) → (1,0) → (0,0)

Going from (sx,sy) to (tx,ty) for the second time: (0,0) → (-1,0) → (-1,1) → (-1,2) → (-1,3) → (0,3) → (1,3) → (1,2)

Going from (tx,ty) to (sx,sy) for the second time: (1,2) → (2,2) → (2,1) → (2,0) → (2,-1) → (1,-1) → (0,-1) → (0,0)

Sample Input 2

-2 -2 1 1

Sample Output 2

UURRURRDDDLLDLLULUUURRURRDDDLLDL


#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
#include<deque>
using namespace std;
#define rep(i,s,n) for(int i = s;i<n;i++)
#define repe(i,s,n) for(int i = s;i<=n;i++)
#define pb push_back
#define fi first
#define se second
typedef long long ll;
typedef pair<int,int>pint;
typedef vector<int>vint;
typedef vector<pint>vpint;
static const ll maxLL = (ll)1 << 62;
const int mod=1000000007;
int dy[]={-1,0,1,0};
int dx[]={0,1,0,-1};
int dyy[]={0,-1,0,1};
int dxx[]={-1,0,1,0};

//#define int ll

int n,m;
int a[1001],b[1001],c[1001];
int d[1001][1001];
int dd[1001][1001];
int cnt;

void warshall_floyd(int n){
  rep(i,0,n)rep(j,0,n)rep(k,0,n){
    if(d[j][k]>d[j][i]+d[i][k] )d[j][k]=d[j][i]+d[i][k];
  }
}

signed main(){
    cin>>n>>m;
    rep(i,0,1000)rep(j,0,1000){
        if(i!=j)d[i][j]=1<<28;
        else d[i][j]=0;
    }
    rep(i,0,m){
        cin>>a[i]>>b[i]>>c[i];
        a[i]--,b[i]--;
        d[a[i]][b[i]]=c[i];
        d[b[i]][a[i]]=c[i];
        dd[a[i]][b[i]]=dd[b[i]][a[i]]=c[i];
    }
    warshall_floyd(n);

    cnt=0;
    rep(i,0,n){
        rep(j,i+1,n){
            if(dd[i][j]>d[i][j])cnt++;
        }
    }

    cout<<cnt<<endl;

    return 0;
}

Score : 400 points

Problem Statement

You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.

The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

A connected graph is a graph where there is a path between every pair of different vertices.

Find the number of the edges that are not contained in any shortest path between any pair of different vertices.

Constraints

2≤N≤100

N-1≤M≤min(N(N-1)/2,1000)

1≤a_i,b_i≤N

1≤c_i≤1000

c_i is an integer.

The given graph contains neither self-loops nor double edges.

The given graph is connected.

Input

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

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M

Output

Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.

Sample Input 1

3 3
1 2 1
1 3 1
2 3 3

Sample Output 1

1

In the given graph, the shortest paths between all pairs of different vertices are as follows:

The shortest path from vertex 1 to vertex 2 is: vertex 1 → vertex 2, with the length of 1.

The shortest path from vertex 1 to vertex 3 is: vertex 1 → vertex 3, with the length of 1.

The shortest path from vertex 2 to vertex 1 is: vertex 2 → vertex 1, with the length of 1.

The shortest path from vertex 2 to vertex 3 is: vertex 2 → vertex 1 → vertex 3, with the length of 2.

The shortest path from vertex 3 to vertex 1 is: vertex 3 → vertex 1, with the length of 1.

The shortest path from vertex 3 to vertex 2 is: vertex 3 → vertex 1 → vertex 2, with the length of 2.

Thus, the only edge that is not contained in any shortest path, is the edge of length 3 connecting vertex 2 and vertex 3, hence the output should be 1.

Sample Input 2

3 2
1 2 1
2 3 1

Sample Output 2

0

Every edge is contained in some shortest path between some pair of different vertices.


#include <cstdio>
#include <cstring>
#include <cmath>
#include <utility>
#include <iostream>
#include <functional>
#include <bitset>
#include <algorithm>
#include <vector>
#include <forward_list>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <numeric>
#include <iomanip>  //setprecision(桁)
using namespace std;
#define pb push_back
#define ll long long int
#define rep(i,n) for(int i = 0;i < (n);i++)
ll INF = 1000000010;
const ll MOD = 1000000007;

int main(){
    ll x, y; cin >> x >> y;
    ll ans = 0;

    if(abs(x) == abs(y)){
        if(x==y) ans = 0;
        else ans = 1;      //ok
    }else if(abs(x) < abs(y)){
        if(x<0 && y<0) ans = 2 + x - y;       //ok
        else if(x<0 && y>=0) ans = 1 + y + x;
        else if(x >=0 && y<0) ans = 1 - x - y;
        else ans = y - x;                        //ok
    }else{
        if(x<0 && y<0) ans = y - x;
        else if(x<0 && y>=0) ans = y - x;
        else if(x >=0 && y<0) ans = 1 + y + x;
        else ans = 1 + y + x;
    }

    cout << ans << endl;

}

Score : 300 points

Problem Statement

Snuke has a calculator. It has a display and two buttons.

Initially, the display shows an integer x.
Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:

Button A: When pressed, the value on the display is incremented by 1.

Button B: When pressed, the sign of the value on the display is reversed.

Find the minimum number of times Snuke needs to press the buttons to achieve his objective.
It can be shown that the objective is always achievable regardless of the values of the integers x and y.

Constraints

x and y are integers.

|x|, |y| ≤ 10^9

x and y are different.

Input

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

x y

Output

Print the minimum number of times Snuke needs to press the buttons to achieve his objective.

Sample Input 1

10 20

Sample Output 1

10

Press button A ten times.

Sample Input 2

10 -10

Sample Output 2

1

Press button B once.

Sample Input 3

-10 -20

Sample Output 3

12

Press the buttons as follows:

Press button B once.

Press button A ten times.

Press button B once.


#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <stack>
#include <list>
#include <utility>
#include <vector>
#include <set>
#include <algorithm>
#include <cmath>
#include <climits>
#include <map>
#include <unordered_map>
#include <string.h>
#include<iomanip>
#include <iterator>
#include <locale>

#define all(a) a.begin(),a.end()
#define VV(T) vector<vector< T > >
#define rep(i,N) for(int i = 0; i <N; i++)
#define repsg(i,s,g) for(int i = s; i <g; i++)
#define name(x) #x
using namespace std;

const int INF = INT_MAX;
const long long INFL =LONG_LONG_MAX;
const double PI = atan(1)*4;
const int MOD = pow(10,9)+7;
int dy[]={0, 0, 1, -1, 0};
int dx[]={1, -1, 0, 0, 0};

typedef long long ll,LL;
typedef vector<int> vint;
typedef vector<vector<int> > vvint;
typedef vector<long long> vll, vLL;
typedef vector<vector<long long> > vvll, vvLL;
typedef pair<int,int> pii;
typedef pair<LL, LL> pLL;

// vector入力
template<typename T>
istream& operator >> (istream& is, vector<T>& vec){
    for(T& x: vec) is >> x;
    return is;
}
// vector出力
template<typename T>
ostream& operator << (ostream& os, vector<T>& vec){
    for(int i=0; i<vec.size(); i++){
        os << vec[i] << ( i+1 == vec.size() ? "" : " " );
    }
    return os;
}

int main() {
    ll x,y;cin>>x>>y;
    ll ans;

    if(x>=y){
        ans = INFL;
        ans = min(ans, 2+abs(x)-abs(y));
        ans = min(ans, 1 + abs(y+x));
    }else{
        ans = y-x;

        ans = min(ans,1+abs(y+x));

        ans = min(ans,abs(abs(y)-abs(x))+1);

    }
    cout<<ans<<endl;

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(ll i = (a); i < (ll)(b); i++)
#define REP(i,n) FOR(i,0,n)
#define YYS(x,arr) for(auto& x:arr)
#define PW(x) (1LL<<(x))
#define SZ(x) ((ll)(x).size())

#define pb emplace_back
#define fi first
#define se second
using ll = long long;
using P = pair<ll ,ll>;
using Tu = tuple<ll, ll, ll>;
const ll INFLL = 1LL<<60LL;
const ll INF = 1LL<<60LL;
const ll MOD = 1e9+7;

using ld = long double;

template<class T> T &chmin( T &a , const T &b ){ return a = min(a,b); }
template<class T> T &chmax( T &a , const T &b ){ return a = max(a,b); }
template<class T> void UNIQUE(vector<T> &a){ a.erase(unique(a.begin(), a.end()), a.end()); }

template<class S, class T> ostream& operator << (ostream& os, const pair<S, T> v){
  os << "(" << v.first << ", " << v.second << ")"; return os;
}
template<class T> ostream& operator << (ostream& os, const vector<T> v){
  for(int i = 0; i < v.size(); i++){if(i > 0){os << " ";} os << v[i];} return os;
}
template<class T> ostream& operator << (ostream& os, const vector<vector<T>> v){
  for(int i = 0; i < v.size(); i++){if(i > 0){os << endl;} os << v[i];} return os;
}

ll in(){long long int x; assert(scanf("%lld", &x) == 1); return x;}
ld fin(){double x; assert(scanf("%lf", &x) == 1); return x;}
char yuyushiki[1000010]; string stin(){assert(scanf("%s", yuyushiki) == 1); return yuyushiki;}

int main(){
  ll a,b,c,d,e,f,g;
  cin >> a >> b >> c >> d >> e >> f >> g;
  ll ans = a / 2 * 4 + b * 2 + min(d, e) * 4;
  if(a % 2 && min(d, e) > 0)
    ans += 2;
  cout << ans / 2 << endl;
}

Score : 600 points

Problem Statement

A tetromino is a figure formed by joining four squares edge to edge.
We will refer to the following seven kinds of tetromino as I-, O-, T-, J-, L-, S- and Z-tetrominos, respectively:

Snuke has many tetrominos. The number of I-, O-, T-, J-, L-, S- and Z-tetrominos in his possession are a_I, a_O, a_T, a_J, a_L, a_S and a_Z, respectively.
Snuke will join K of his tetrominos to form a rectangle that is two squares tall and 2K squares wide.
Here, the following rules must be followed:

When placing each tetromino, rotation is allowed, but reflection is not.

Each square in the rectangle must be covered by exactly one tetromino.

No part of each tetromino may be outside the rectangle.

Snuke wants to form as large a rectangle as possible.
Find the maximum possible value of K.

Constraints

0≤a_I,a_O,a_T,a_J,a_L,a_S,a_Z≤10^9

a_I+a_O+a_T+a_J+a_L+a_S+a_Z≥1

Input

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

a_I a_O a_T a_J a_L a_S a_Z

Output

Print the maximum possible value of K. If no rectangle can be formed, print 0.

Sample Input 1

2 1 1 0 0 0 0

Sample Output 1

3

One possible way to form the largest rectangle is shown in the following figure:

Sample Input 2

0 0 10 0 0 0 0

Sample Output 2

0

No rectangle can be formed.


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

int main(){
  int A,B,x;
  char op;
  cin >> A;
  cin >> op;
  cin >> B;
  if(op=='+')
    x=A+B;
  else
    x=A-B;
  cout << x << endl;
}

Score : 100 points

Problem Statement

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

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

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


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

#define pb push_back
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define REP(i,n) for(int _n=n, i=0;i<_n;++i)
#define FOR(i,a,b) for(int i=(a),_b=(b);i<=_b;++i)
#define FORD(i,a,b) for(int i=(a),_b=(b);i>=_b;--i)
#define trav(a, x) for (auto& a : x)
using ull = uint64_t;
using ll = int64_t;
using PII = pair<int, int>;
using VI = vector<int>;
#define INF (1ll<<60)

string to_string(string s) { return '"' + s + '"'; }
string to_string(const char* s) { return to_string((string) s); }
string to_string(bool b) { return (b ? "true" : "false"); }
template <typename A, typename B> string to_string(pair<A, B> p) {
  return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; }
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; }
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) {
  cerr << " " << to_string(H); debug_out(T...); }
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)

const ll MOD = 1000000007;

int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    int N;
    cin >> N;
    VI V(N);
    VI A(N/2 + 1, 0);
    REP(i, N) {
        cin >> V[i];
        A[V[i]/2]++;
    }
    int ans = 0;
    if (N % 2 == 0) {
        REP(i, N/2) {
            if (A[i] != 2) {
                cout << "0\n";
                return 0;
            }
        }

    } else {
        if (A[0] != 1) {
            cout << ans << '\n';
            return 0;
        }
        FOR(i, 1, N/2 - 1) {
            if (A[i] != 2) {
                cout << 0 << '\n';
                return 0;
            }
        }
    }
    int k = N / 2;
    ans = 1;
    REP(i, k) {
        ans = (ans * 2) % MOD;
    }
    cout << ans << endl;

}

Score : 300 points

Problem Statement

There are N people, conveniently numbered 1 through N.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person i is A_i.

Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo 10^9+7.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print 0.

Constraints

1≦N≦10^5

0≦A_i≦N-1

Input

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

N
A_1 A_2 ... A_N

Output

Print the number of the possible orders in which they were standing, modulo 10^9+7.

Sample Input 1

5
2 4 4 0 2

Sample Output 1

4

There are four possible orders, as follows:

2,1,4,5,3

2,5,4,1,3

3,1,4,5,2

3,5,4,1,2

Sample Input 2

7
6 4 0 2 4 0 2

Sample Output 2

0

Any order would be inconsistent with the reports, thus the answer is 0.

Sample Input 3

8
7 5 1 1 7 3 5 3

Sample Output 3

16


#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <map>

#define rep(i, N) for (int i = 0; i < (int)N; i++)
using namespace std;
typedef long long ll;
const ll LLINF = 9223372036854775807;
const int MOD = 1000000007;

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

  map<int, int> num; rep(i,N) num[A[i]]++;
  bool ok = true;
  if (N%2==0) { rep(i, N/2) if (num[2*i+1]!=2) ok = false; }
  else {
    rep(i,(N+1)/2) {
      if (i==0) if (num[2*i]!=1) ok = false;
      else if (num[2*i]!=2) ok = false;
    }
  }

  ll result = 0;
  if (ok) {result=1; rep(i,N/2) result = (result*2)%MOD; }
  cout << result << endl;
  return 0;
}


#include<bits/stdc++.h>
#include<tr1/unordered_map>
#define CLR(a,x) memset(a,x,sizeof(a))
#define MP make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int,int> pa;
const int maxn=1e5+10,P=1e9+7;

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

int N,a[maxn];

int main(){
    //freopen("","r",stdin);
	N=rd();
	for(int i=1;i<=N;i++) a[rd()]++;
	int ans=1;
	if(N&1){
		for(int i=2;i<=N-1;i+=2) if(a[i]!=2) ans=0;
		if(a[0]!=1) ans=0;
	}else{
		for(int i=1;i<=N-1;i+=2) if(a[i]!=2) ans=0;
	}
	for(int i=1;i<=N/2;i++) ans=ans*2%P;
	printf("%d\n",ans);
    return 0;
}


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

int main() {
  char s ;
  cin >> s;

  if (s == 'a' || s == 'i' || s == 'u' || s == 'e' || s == 'o') {
     cout << "vowel" << endl;
   }
  else {
     cout << "consonant" << endl;
   }

}

Score : 100 points

Problem Statement

Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: a, e, i, o and u.

Constraints

c is a lowercase English letter.

Input

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

c

Output

If c is a vowel, print vowel. Otherwise, print consonant.

Sample Input 1

a

Sample Output 1

vowel

Since a is a vowel, print vowel.

Sample Input 2

z

Sample Output 2

consonant

Sample Input 3

s

Sample Output 3

consonant


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
#include <queue>
#include <set>
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define rep1(i,n) for(int i=1;i<=(int)(n);i++)

using namespace std;
typedef long long int lli;

int main(){
	char c;
	cin>>c;
	if(c=='a'||c=='i'||c=='u'||c=='e'||c=='o') cout<<"vowel";
	else cout<<"consonant";
}


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

int main(){
    int h,w;
    cin >> h >> w;
    rep(i, h){
        string c;
        cin >> c;
        cout << c << endl;
        cout << c << endl;
    }
}


#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <functional>
#include <map>
#include <iomanip>
#include<iostream>

using namespace std;
struct UnionFind {
	vector<int> data;
	UnionFind(int size) : data(size, -1) { }
	bool unionSet(int x, int y) {
		x = root(x); y = root(y);
		if (x != y) {
			if (data[y] < data[x]) swap(x, y);
			data[x] += data[y]; data[y] = x;
		}
		return x != y;
	}
	bool findSet(int x, int y) {
		return root(x) == root(y);
	}
	int root(int x) {
		return data[x] < 0 ? x : data[x] = root(data[x]);
	}
	int size(int x) {
		return -data[root(x)];
	}
};
int main() {
	int N, K, L, p, q;
	cin >> N >> K >> L;
	UnionFind uf1{ N }, uf2{ N };
	for (int i = 0; i < K; ++i) {
		cin >> p >> q;
		uf1.unionSet(p, q);
	}
	for (int i = 0; i < L; ++i) {
		cin >> p >> q;
		uf2.unionSet(p, q);
	}
	map<pair<int, int>, int> cnt;
	for (int i = 0; i < N; i++) {
		cnt[make_pair(uf1.root(i), uf2.root(i))]++;
	}
	for (int i = 0; i < N; i++) {
		printf("%d\n", cnt[make_pair(uf1.root(i), uf2.root(i))]);
	}
}

Score : 400 points

Problem Statement

There are N cities. There are also K roads and L railways, extending between the cities.
The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities.
No two roads connect the same pair of cities. Similarly, no two railways connect the same pair of cities.

We will say city A and B are connected by roads if city B is reachable from city A by traversing some number of roads. Here, any city is considered to be connected to itself by roads.
We will also define connectivity by railways similarly.

For each city, find the number of the cities connected to that city by both roads and railways.

Constraints

2 ≦ N ≦ 2*10^5

1 ≦ K, L≦ 10^5

1 ≦ p_i, q_i, r_i, s_i ≦ N

p_i < q_i

r_i < s_i

When i ≠ j, (p_i, q_i) ≠ (p_j, q_j)

When i ≠ j, (r_i, s_i) ≠ (r_j, s_j)

Input

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

N K L
p_1 q_1
:
p_K q_K
r_1 s_1
:
r_L s_L

Output

Print N integers. The i-th of them should represent the number of the cities connected to the i-th city by both roads and railways.

Sample Input 1

4 3 1
1 2
2 3
3 4
2 3

Sample Output 1

1 2 2 1

All the four cities are connected to each other by roads.

By railways, only the second and third cities are connected. Thus, the answers for the cities are 1, 2, 2 and 1, respectively.

Sample Input 2

4 2 2
1 2
2 3
1 4
2 3

Sample Output 2

1 2 2 1

Sample Input 3

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

Sample Output 3

1 1 2 1 2 2 2


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

int main() {

  string A,B,C;
  cin >> A >> B >> C;

  cout << 'A' + B[0] + 'C' <<endl;
  return 0;
}

Score : 100 points

Problem Statement

Snuke is going to open a contest named "AtCoder s Contest".
Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.

Snuke has decided to abbreviate the name of the contest as "AxC".
Here, x is the uppercase English letter at the beginning of s.

Given the name of the contest, print the abbreviation of the name.

Constraints

The length of s is between 1 and 100, inclusive.

The first character in s is an uppercase English letter.

The second and subsequent characters in s are lowercase English letters.

Input

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

AtCoder s Contest

Output

Print the abbreviation of the name of the contest.

Sample Input 1

AtCoder Beginner Contest

Sample Output 1

ABC

The contest in which you are participating now.

Sample Input 2

AtCoder Snuke Contest

Sample Output 2

ASC

This contest does not actually exist.

Sample Input 3

AtCoder X Contest

Sample Output 3

AXC


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

int main() {
  string s, t;

	cin >> s >> t;
	cout << "A" << t.at(0) << "C" << endl;

}


#include <iostream>
#include <string>
using namespace std;
int main(){
    string r, s, t; cin >> r >> s >> t;
    cout << r[0] << s[0] << t[0] << endl;
}


#include<bits/stdc++.h>
using namespace std;
int main(){
  int64_t a,b,c;
  cin >> a >> b >> c;
  int64_t count = 0;
  int64_t bet = b-a+1;
  while(bet > 0){
    if(a%c == 0)
      count++;
    a++;
    bet--;
  }
  cout << count << endl;
}

Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

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

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


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

int main(){
long a,b,x;
  cin>>a>>b>>x;

  long ans=b/x-a/x;
  if(a%x==0){ans++;}
  cout<<ans<<endl;
}


#include<bits/stdc++.h>
using namespace std;
int a[101];
int main(){
	int n,i,j,x,sum=0;
	cin>>n>>x;
	for(i=1;i<=n;i++)
		cin>>a[i];
	for(i=1;i<n;i++)
		for(j=2;j<=n;j++)
			if(a[j]-a[i]>x||a[i]-a[j]>x) sum++;
	cout<<sum;
	return 0;
}

Score : 300 points

Problem Statement

There are N boxes arranged in a row.
Initially, the i-th box from the left contains a_i candies.

Snuke can perform the following operation any number of times:

Choose a box containing at least one candy, and eat one of the candies in the chosen box.

His objective is as follows:

Any two neighboring boxes contain at most x candies in total.

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

Constraints

2 ≤ N ≤ 10^5

0 ≤ a_i ≤ 10^9

0 ≤ x ≤ 10^9

Input

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

N x
a_1 a_2 ... a_N

Output

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

Sample Input 1

3 3
2 2 2

Sample Output 1

1

Eat one candy in the second box.
Then, the number of candies in each box becomes (2, 1, 2).

Sample Input 2

6 1
1 6 1 2 0 4

Sample Output 2

11

For example, eat six candies in the second box, two in the fourth box, and three in the sixth box.
Then, the number of candies in each box becomes (1, 0, 1, 0, 0, 1).

Sample Input 3

5 9
3 1 4 1 5

Sample Output 3

0

The objective is already achieved without performing operations.

Sample Input 4

2 0
5 5

Sample Output 4

10

All the candies need to be eaten.


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

int main()
{
    char a[119999];
    scanf("%s",a);
    int len = strlen(a);
    int sum = 0;
    //cout<<sum<<endl;
    if(!len%2)
    {
        if(a[0]==a[len-1])
            printf("First\n");
        else printf("Second\n");
    }
    else
    {
        if(a[0]==a[len-1])
            printf("Second\n");
        else printf("First\n");
    }

    return 0;
}

Score : 500 points

Problem Statement

There is a string s of length 3 or greater.
No two neighboring characters in s are equal.

Takahashi and Aoki will play a game against each other.
The two players alternately performs the following operation, Takahashi going first:

Remove one of the characters in s, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in s.

The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally.

Constraints

3 ≤ |s| ≤ 10^5

s consists of lowercase English letters.

No two neighboring characters in s are equal.

Input

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

s

Output

If Takahashi will win, print First. If Aoki will win, print Second.

Sample Input 1

aba

Sample Output 1

Second

Takahashi, who goes first, cannot perform the operation, since removal of the b, which is the only character not at either ends of s, would result in s becoming aa, with two as neighboring.

Sample Input 2

abc

Sample Output 2

First

When Takahashi removes b from s, it becomes ac.
Then, Aoki cannot perform the operation, since there is no character in s, excluding both ends.

Sample Input 3

abcab

Sample Output 3

First


#include <bits/stdc++.h>
#define rep(i, a, b) for(int i = a; i < b; i++)
#define Rep(i, a, b) for(int i = a; i <= b; i++)
#define _GLIBCXX_DEBUG
#define Vl vector<ll>
#define Vs vector<string>
#define ll long long
#define ALL(v) (v).begin(),(v).end()
using namespace std;

void solve() {
    int h, w; cin >> h >> w;
    vector<vector<string>> vvs(h, vector<string>(w));
    rep(i, 0, h) rep(j, 0, w) cin >> vvs[i][j];
    int ii, jj;
    rep(i, 0, h) rep(j, 0, w) {
        if(vvs[i][j] == "snuke") ii = i, jj = j;
    }
    ii++;
    vector<char> a = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
    cout << a[jj] << ii << endl;
}

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

    solve();
    return 0;
}

Score : 100 points

Problem Statement

There is a grid with H rows and W columns.

The square at the i-th row and j-th column contains a string S_{i,j} of length 5.

The rows are labeled with the numbers from 1 through H, and the columns are labeled with the uppercase English letters from A through the W-th letter of the alphabet.

Exactly one of the squares in the grid contains the string snuke. Find this square and report its location.

For example, the square at the 6-th row and 8-th column should be reported as H6.

Constraints

1≦H, W≦26

The length of S_{i,j} is 5.

S_{i,j} consists of lowercase English letters (a-z).

Exactly one of the given strings is equal to snuke.

Input

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

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

Output

Print the labels of the row and the column of the square containing the string snuke, with no space inbetween.

Sample Input 1

15 10
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snuke snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake

Sample Output 1

H6

Sample Input 2

1 1
snuke

Sample Output 2

A1


#include <stdio.h>
#include <string.h>
int i = 0;
char arr[6];
int main() {
	int r, c;
	scanf("%d %d", &r, &c);
	while (1) {
		scanf("%s", arr);
		if (!strcmp(arr, "snuke")) break;
		++i;
	}
	printf("%c%d", i%c + 'A', i / c + 1);
}


#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (int)(n); i ++)
#define irep(i,n) for (int i = (int)(n) - 1;i >= 0;--i)
using namespace std;
using ll = long long;
using PL = pair<ll,ll>;
using P = pair<int,int>;
constexpr int INF = 1000000000;
constexpr long long HINF = 1000000000000000;
constexpr long long MOD = 1000000007;// = 998244353;
constexpr double EPS = 1e-4;
constexpr double PI = 3.14159265358979;

int main() {
    int N; cin >> N;
    int M = 1;
    rep(i,N + 1) {
        if (i*(i + 1)/2 == N) {
            M = -i;
            break;
        } else if (i*(i + 1)/2 > N) {
            M = i;
            break;
        }
    }
    if (M >= 0) {
        int x = M*(M + 1)/2 - N;
        for (int i = 1;i <= M;++i) {
            if (i == x) continue;
            cout << i << '\n';
        }
    } else {
        for (int i = 1;i <= -M;++i) {
            cout << i << '\n';
        }
    }
    return 0;
}

Score : 300 points

Problem Statement

The problem set at CODE FESTIVAL 20XX Finals consists of N problems.

The score allocated to the i-th (1≦i≦N) problem is i points.

Takahashi, a contestant, is trying to score exactly N points. For that, he is deciding which problems to solve.

As problems with higher scores are harder, he wants to minimize the highest score of a problem among the ones solved by him.

Determine the set of problems that should be solved.

Constraints

1≦N≦10^7

Partial Score

200 points will be awarded for passing the test set satisfying 1≦N≦1000.

Additional 100 points will be awarded for passing the test set without additional constraints.

Input

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

N

Output

Among the sets of problems with the total score of N, find a set in which the highest score of a problem is minimum, then print the indices of the problems in the set in any order, one per line.

If there exists more than one such set, any of them will be accepted.

Sample Input 1

4

Sample Output 1

1
3

Solving only the 4-th problem will also result in the total score of 4 points, but solving the 1-st and 3-rd problems will lower the highest score of a solved problem.

Sample Input 2

7

Sample Output 2

1
2
4

The set \{3,4\} will also be accepted.

Sample Input 3

1

Sample Output 3

1


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

int main(){
  int W, H, N;  cin >> W >> H >> N;
  int xmi = 0, xma = W, ymi = 0, yma = H;
  for(int i = 0; i < N; i++){
    int x, y, a;  cin >> x >> y >> a;
    if(a == 1) xmi = max(xmi, x);
    if(a == 2) xma = min(xma, x);
    if(a == 3) ymi = max(ymi, y);
    if(a == 4) yma = min(yma, y);
  }
  cout << max(0, (xma - xmi) * (yma - ymi)) << endl;
}

Score : 200 points

Problem Statement

There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.

Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) point was (x_i, y_i).

Then, he created an integer sequence a of length N, and for each 1 ≦ i ≦ N, he painted some region within the rectangle black, as follows:

If a_i = 1, he painted the region satisfying x < x_i within the rectangle.

If a_i = 2, he painted the region satisfying x > x_i within the rectangle.

If a_i = 3, he painted the region satisfying y < y_i within the rectangle.

If a_i = 4, he painted the region satisfying y > y_i within the rectangle.

Find the area of the white region within the rectangle after he finished painting.

Constraints

1 ≦ W, H ≦ 100

1 ≦ N ≦ 100

0 ≦ x_i ≦ W (1 ≦ i ≦ N)

0 ≦ y_i ≦ H (1 ≦ i ≦ N)

W, H (21:32, added), x_i and y_i are integers.

a_i (1 ≦ i ≦ N) is 1, 2, 3 or 4.

Input

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

W H N
x_1 y_1 a_1
x_2 y_2 a_2
:
x_N y_N a_N

Output

Print the area of the white region within the rectangle after Snuke finished painting.

Sample Input 1

5 4 2
2 1 1
3 3 4

Sample Output 1

9

The figure below shows the rectangle before Snuke starts painting.

First, as (x_1, y_1) = (2, 1) and a_1 = 1, he paints the region satisfying x < 2 within the rectangle:

Then, as (x_2, y_2) = (3, 3) and a_2 = 4, he paints the region satisfying y > 3 within the rectangle:

Now, the area of the white region within the rectangle is 9.

Sample Input 2

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

Sample Output 2

0

It is possible that the whole region within the rectangle is painted black.

Sample Input 3

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

Sample Output 3

64


// All Library
// #include <bits/stdc++.h> // https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/precompiled/stdc%2B%2B.h

// C Library
// #include <cassert> // (assert.h) C Diagnostics Library (header)
// #include <cctype> // (ctype.h) Character handling functions (header)
// #include <cerrno> // (errno.h) C Errors (header)
// #include <cfloat> // (float.h) Characteristics of floating-point types (header)
// #include <ciso646> // (iso646.h) ISO 646 Alternative operator spellings (header)
// #include <climits> // (limits.h) Sizes of integral types (header)
// #include <clocale> // (locale.h) C localization library (header)
// #include <cmath> // (math.h) C numerics library (header)
// #include <csetjmp> // (setjmp.h) Non local jumps (header)
// #include <csignal> // (signal.h) C library to handle signals (header)
// #include <cstdarg> // (stdarg.h) Variable arguments handling (header)
// #include <cstdbool> // (stdbool.h) Boolean type (header)
// #include <cstddef> // (stddef.h) C Standard definitions (header)
// #include <cstdint> // (stdint.h) Integer types (header)
#include <cstdio> // (stdio.h) C library to perform Input/Output operations (header)
// #include <cstdlib> // (stdlib.h) C Standard General Utilities Library (header)
// #include <cstring> // (string.h) C Strings (header)
// #include <ctime> // (time.h) C Time Library (header)
// #include <cuchar> // (uchar.h) Unicode characters (header)
// #include <cwchar> // (wchar.h) Wide characters (header)
// #include <cwctype> // (wctype.h) Wide character type (header)

// Containers
// #include <array> // Array header (header)
// #include <bitset> // Bitset header (header)
#include <deque> // Deque header (header)
// #include <forward_list> // Forward list (header)
// #include <list> // List header (header)
#include <map> // Map header (header)
// #include <queue> // Queue header (header)
#include <set> // Set header (header)
// #include <stack> // Stack header (header)
// #include <unordered_map> //Unordered map header (header)
// #include <unordered_set> // Unordered set header (header)
#include <vector> // Vector header (header)

// Input/Output Stream Library
#include <iostream> // The class relies on a single streambuf object for both the input and output operations.
// #include <fstream> // Input/output stream class to operate on files.
// #include <sstream> //

// Miscellaneous headers
#include <algorithm> // Standard Template Library: Algorithms (library )
// #include <chrono> // Time library (header)
// #include <codecvt> // Unicode conversion facets (header)
// #include <complex> // Complex numbers library (header)
// #include <exception> // Standard exceptions (header)
// #include <functional> // Function objects (header)
// #include <initializer_list> // Initializer list (header)
// #include <iterator> // Iterator definitions (header)
// #include <limits> // Numeric limits (header)
// #include <locale> // Localization library (header)
// #include <memory> //Memory elements (header)
// #include <new> // Dynamic memory (header)
// #include <numeric> // Generalized numeric operations (header)
// #include <random> // Random (header)
// #include <ratio> // Ratio header (header)
// #include <regex> // Regular Expressions (header)
// #include <stdexcept> // Exception classes (header)
#include <string> // Strings (header)
// #include <system_error> // System errors (header)
#include <tuple> // Tuple library (header)
// #include <typeinfo> // Type information (header)
// #include <type_traits> //type_traits (header)
// #include <utility> // Utility components (header)
// #include <valarray> // Library for arrays of numeric values (header)

// Boost
// #include <boost/multiprecision/cpp_int.hpp>

using namespace std;
// using namespace boost::multiprecision;

#define BEGIN ios_base::sync_with_stdio(false);cin.tie(NULL)
#define END return EXIT_SUCCESS
#define rep(I,N) for((I)=0;(I)<(N);(I)++)
#define up(I,A,B) for((I)=(A);(I)<=(B);(I)++)
#define dw(I,A,B) for((I)=(A);(I)>=(B);(I)--)
#define all(C) (C).begin(),(C).end()
#define rall(C) (C).rbegin(),(C).rend()
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define lb lower_bound
#define ub upper_bound
template<class T>inline bool chmax(T& a,T b){if(a<b){a=b;return true;}return false;}
template<class T>inline bool chmin(T& a,T b){if(a>b){a=b;return true;}return false;}
template<class T>inline void                             in(T &p){cin>>p;}
template<class T1,class T2>inline void                   in(T1 &p1,T2 &p2){cin>>p1>>p2;}
template<class T1,class T2,class T3>inline void          in(T1 &p1,T2 &p2,T3 &p3){cin>>p1>>p2>>p3;}
template<class T1,class T2,class T3,class T4>inline void in(T1 &p1,T2 &p2,T3 &p3,T4 &p4){cin>>p1>>p2>>p3>>p4;}
template<class T>inline void                             out(T p){cout<<p<<endl;}
template<class T1,class T2>inline void                   out(T1 p1,T2 p2){cout<<p1<<" "<<p2<<endl;}
template<class T1,class T2,class T3>inline void          out(T1 p1,T2 p2,T3 p3){cout<<p1<<" "<<p2<<" "<<p3<<endl;}
template<class T1,class T2,class T3,class T4>inline void out(T1 p1,T2 p2,T3 p3,T4 p4){cout<<p1<<" "<<p2<<" "<<p3<<" "<<p4<<endl;}

// 【WIP】
// class fast_io{
// private:
// public:
//   void in(long&&... params){}
//   void out(){}
// };
// #define mygc(c) (c)=getchar_unlocked()
// #define mypc(c) putchar_unlocked(c)
// int reader(char c[]){int i,s=0;for(;;){mygc(i);if(i!=' '&&i!='\n'&&i!='\r'&&i!='\t') break;}c[s++]=i;for(;;){mygc(i);if(i==' '||i=='\n'||i=='\r'||i=='\t') break;c[s++]=i;}return s;}
// void reader(int *x){int k,m=0;*x=0;for(;;){k=getchar_unlocked();if(k=='-'){m=1;break;}if('0'<=k&&k<='9'){*x=k-'0';break;}}for(;;){k=getchar_unlocked();if(k<'0'||k>'9')break;*x=(*x)*10+k-'0';}if(m)(*x)=-(*x);}
// void reader(char x[], int len){int i,k;if(len==0)return;for(;;){mygc(k);if(!(k==' '||k=='\n'||k=='\t'||k=='\r')){x[0]=k;break;}}REP(i,1,len)mygc(x[i]);}
// void writer(const char c[]){int i;for(i=0;c[i]!='\0';i++)mypc(c[i]);}
// void writer(int x, char c){int i,sz=0,m=0;char buf[10];if(x<0)m=1,x=-x;while(x)buf[sz++]=x%10,x/=10;if(!sz)buf[sz++]=0;if(m)putchar_unlocked('-');while(sz--)putchar_unlocked(buf[sz]+'0');putchar_unlocked(c);}
// void writer(const char c[]){int i;for(i=0;c[i]!='\0';i++)putchar_unlocked(c[i]);}
// void writer(const char c[], int len){int i;rep(i,len)putchar_unlocked(c[i]);}

// 【WIP】
// class mod_int{
// public:
//   long n,MOD;
//   mod_int():MOD((long)1e9+7){}
//   // modint(int a) { x = a % mod; if (x < 0) x += mod; }
//   mod_int(T MOD){this->MOD=MOD;}
//   mod_int &operator+=(mod_int that){n=(n+that.n)%MOD;return *this;}
//   mod_int &operator-=(mod_int that){n=(n+MOD-that.n)%MOD;return *this;}
//   mod_int &operator*=(mod_int that){n=(long)n*that.n%MOD;return *this;}
//   mod_int &operator/=(mod_int that){return *this*=that.inverse();}
//   mod_int operator-(){return mod_int(-this->n);}
//   friend ostream& operator<<(ostream &out,mod_int m){return out<<m.n;}
//   mod_int inverse(){
//     long a=n,b=MOD,u=1,v=0;
//     while(b){int t=a/b;a-=t*b;u-=t*v;swap(a,b);swap(u,v);}
//     return mod_int(u);
//   }
// #define op(o,p) mod_int operator o(mod_int that){return mod_int(*this) p that;}
//   op(+,+=) op(-,-=) op(*,*=) op(/,/=)
// #undef op
// #define op(o) bool operator o(mod_int that)const{return n o that.n;}
//   op(==) op(!=) op(<) op(<=) op(>) op(>=)
// #undef op
// };

int w,h,n,l,r,d,u,x,y,a,i;
inline void solve(void){
  in(w,h,n);
  r=w,u=h;
  rep(i,n){
    in(x,y,a);
    if(a==1)l=x;
    else if(a==2)r=x;
    else if(a==3)d=y;
    else if(a==4)u=y;
  }
  out(max(r-l,0)*max(u-d,0));
}

int main(int argc,char**argv){
  BEGIN;
  solve();
  END;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<ll, ll> P;

#define EACH(i,a) for (auto&& i : a)
#define FOR(i,a,b) for (ll i=(a),__last_##i=(b);i<__last_##i;i++)
#define RFOR(i,a,b) for (ll i=(b)-1,__last_##i=(a);i>=__last_##i;i--)
#define REP(i,n) FOR(i,0,n)
#define RREP(i,n) RFOR(i,0,n)
#define __GET_MACRO3(_1, _2, _3, NAME, ...) NAME
#define rep(...) __GET_MACRO3(__VA_ARGS__, FOR, REP)(__VA_ARGS__)
#define rrep(...) __GET_MACRO3(__VA_ARGS__, RFOR, RREP)(__VA_ARGS__)
#define debug(x) cout<<#x<<": "<<x<<endl
#define pb push_back
#define ALL(a) (a).begin(),(a).end()
#define chmin(x,v) x = min(x, v)
#define chmax(x,v) x = max(x, v)

const ll linf = 1e18;
const int inf = 1e9;
const double eps = 1e-12;
const double pi = acos(-1);

template<typename T>
istream& operator>>(istream& is, vector<T>& vec) {
    EACH(x,vec) is >> x;
    return is;
}
template<typename T>
ostream& operator<<(ostream& os, const vector<T>& vec) {
    REP(i,vec.size()) {
        if (i) os << " ";
        os << vec[i];
    }
    return os;
}
template<typename T>
ostream& operator<<(ostream& os, const vector< vector<T> >& vec) {
    REP(i,vec.size()) {
        if (i) os << endl;
        os << vec[i];
    }
    return os;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    string s; cin >> s;
    s.erase(unique(ALL(s)), s.end());
    cout << s.size()-1 << endl;
}

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 <string>

using namespace std;

typedef long long ll;

int main() {
    int n;
    string s, t;
    cin >> n >> s >> t;

    string ans = "";
    for (int i = 0; i < n; ++i) {
        if (s.substr(i, n - i) == t.substr(0, n - i)){
            break;
        }else{
            ans.push_back(s[i]);
        }
    }

    ans += t;

    cout << ans.size() << endl;
}

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.


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

int main()
{
   int a,b,c;
   cin>>a>>b>>c;
   set <int, greater <int> > s;
   s.insert(a);
   s.insert(b);
   s.insert(c);
   int ans;
   ans = s.size();
   cout<<ans<<endl;
}

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

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

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


#include <iostream>
#include <math.h>

using std::cin;
using std::cout;
using std::endl;

int main()
{
  double N, K;

  cin >> N >> K;

  cout << (K * pow(K - 1, N - 1)) << endl;
}

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.


#include <bits/stdc++.h>
using namespace std;
string s;
int main()
{
    cin>>s;
    int num=0,res=0;
    for (int i=0;i<(int)s.length();++i)
        if (!(i&1)) res-=s[i]=='p';
        else {
            ++num;
            res+=s[i]=='g';
        }
    printf("%d\n",res);
    return 0;
}

Score : 300 points

Problem Statement

AtCoDeer the deer and his friend TopCoDeer is playing a game.
The game consists of N turns.
In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition:

(※) After each turn, (the number of times the player has played Paper)≦(the number of times the player has played Rock).

Each player's score is calculated by (the number of turns where the player wins) - (the number of turns where the player loses), where the outcome of each turn is determined by the rules of Rock-paper-scissors.

(For those who are not familiar with Rock-paper-scissors: If one player plays Rock and the other plays Paper, the latter player will win and the former player will lose. If both players play the same gesture, the round is a tie and neither player will win nor lose.)

With his supernatural power, AtCoDeer was able to foresee the gesture that TopCoDeer will play in each of the N turns, before the game starts.
Plan AtCoDeer's gesture in each turn to maximize AtCoDeer's score.

The gesture that TopCoDeer will play in each turn is given by a string s. If the i-th (1≦i≦N) character in s is g, TopCoDeer will play Rock in the i-th turn. Similarly, if the i-th (1≦i≦N) character of s in p, TopCoDeer will play Paper in the i-th turn.

Constraints

1≦N≦10^5

N=|s|

Each character in s is g or p.

The gestures represented by s satisfy the condition (※).

Input

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

s

Output

Print the AtCoDeer's maximum possible score.

Sample Input 1

gpg

Sample Output 1

0

Playing the same gesture as the opponent in each turn results in the score of 0, which is the maximum possible score.

Sample Input 2

ggppgggpgg

Sample Output 2

2

For example, consider playing gestures in the following order: Rock, Paper, Rock, Paper, Rock, Rock, Paper, Paper, Rock, Paper. This strategy earns three victories and suffers one defeat, resulting in the score of 2, which is the maximum possible score.


/*************************************************************************

       Author:            palayutm
       Created Time :     Mon 10 Oct 2016 12:13:01 PM CST

       File Name:         e.cc
       Description:       new style, new life

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

using namespace std;

typedef unsigned long long ull;

const ull base = 1e9+7;

const int B = 640;

int ch[400005][26], cnt = 1;
vector<int> vec[400006];
vector<string> vstr, vv;
vector<vector<ull> > key;
int cl[B+100][B+100];
int idx[100005];
bool tx[256][267];
int hh[400005];

void insert(char* s, int id) {
  int now = 0;
  for (int i = 0; s[i]; i ++) {
    int c = s[i] - 'a';
    if (!ch[now][c]) {
      ch[now][c] = cnt ++;
    }
    now = ch[now][c];
    vec[now].push_back(id);
  }
  hh[now] = id;
}

char s[400005];

int solve(int k, const string& t){
  string& s = vv[k-1];
  for (int i = 0; i < 26; i ++) {
    for (int j = i+1; j < 26; j ++) {
      tx[t[i]][t[j]] = 1;
      tx[t[j]][t[i]] = 0;
    }
  }
  int ans = 0;
  int now = 0;
  for (int i = 0; i < min(B, (int)s.size()); i ++) {
    if (hh[now] >= 0) {
      ans ++;
    }
    for (int j = 0; j < 26; j ++) {
      if (t[j] == s[i]) {
        now = ch[now][s[i]-'a'];
        break;
      }
      int c = t[j]-'a';
      int num = vec[ch[now][c]].size();
      ans += num;
    }
  }
  if (s.size() < B) {
    return ans;
  }
  sort(vec[now].begin(), vec[now].end(), [](const int xx, const int yy){
      int x = idx[xx], y = idx[yy];
      if (cl[x][y] == -1) {
      return vstr[x].size() < vstr[y].size();
      } else {
      int id = cl[x][y];
      return tx[ vstr[x][id] ][ vstr[y][id] ];
      }
      ;
      });
  for (auto x : vec[now]) {
    if (x != k-1) {
      ans ++;
    } else {
      break;
    }
  }
  return ans;
}

int main(int argc, const char *argv[])
{
  memset(hh, -1, sizeof(hh));
  int n;
  cin >> n;
  for (int i = 0; i < n; i ++) {
    scanf("%s", s);
    int len = strlen(s);
    insert (s, i);
    vv.push_back(string(s));
    if (len >= B) {
      idx[i] = vstr.size();
      vstr.push_back(string(s));
      key.push_back(vector<ull>());
      key.back().push_back(s[0]);
      for (int j = 1; j < len; j ++) {
        key.back().push_back(key.back().back()*base + s[j]);
      }
    }
  }
  for (int i = 0; i < (int)vstr.size(); i ++) {
    for (int j = i+1; j < (int)vstr.size(); j ++) {
      const string& x = vstr[i], y = vstr[j];
      int low = 0, high = (int)min(x.size(), y.size()) - 1;
      while (low <= high) {
        int mid = (low + high)/2;
        if (key[i][mid] != key[j][mid]) {
          high = mid -1;
        } else {
          low = mid + 1;
        }
      }
      if (low > (int)min(x.size(), y.size()) - 1) {
        cl[i][j] = cl[j][i] = -1;
      } else {
        cl[i][j] = cl[j][i] = low;
      }
    }
  }
  int q;
  cin >> q;
  while (q --) {
    int k;
    string t;
    cin >> k >> t;
    int now = 0;
    cout << solve(k, t) + 1 << endl;
  }
  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>
using namespace std;
using ll = long long;

#define FOR(i,a,b)  for(ll (i)=a;(i)<(b);++(i))
#define RFOR(i,a,b) for(ll (i)=a;(i)>=(b);--(i))
#define REP(i,n)    FOR(i,0,n)
#define RREP(i,n)   RFOR(i,n,0)
#define ALL(v)      (v).begin(),(v).end()
#define BIT(n)      (1LL<<(n))
#define IN(x,l,r)   ((l)<=(x)&&(x)<=(r))
#define SHOW(x)     cout<<#x<<" = "<<x<<endl
#define SORT(v)     sort(ALL(v))
#define SZ(v)       (ll)(v).size()
#define UNIQ(v)     SORT(v);(v).erase(unique(ALL(v)),(v).end())
#define PERM(c)     for(bool p=1;p;p=next_permutation(ALL(c)))
#define PQ(T)       priority_queue<T,vector<T>,greater<T>>

template<typename T>string join(const vector<T>& v, string d=" ")
{stringstream s;REP(i,SZ(v))s<<d<<v[i];return s.str().substr(d.length());}

template<typename T> ostream& operator<<(ostream& s, const vector<T>& v)
{if(SZ(v))s<<join(v,", ");return s;}

const ll inf = 1e15;
const ll mod = 1e9+7;
const double eps = 1e-10;

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

int main() {
    string X; cin >> X;
    X += "XX";

    for (ll i = 0; i < X.length() - 1; ) {
        if (X.substr(i, 2) == "ST") {
            string Y = "";
            REP(j, i) Y += X[j];
            FOR(j, i+2, X.length()) Y += X[j];
            X = Y;
            i = 0;
        } else {
            i++;
        }
    }
    cout << X.length() - 2 << endl;

    return 0;
}

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

template <typename T>
std::ostream &operator<<(std::ostream &out, const std::vector<T> &v){
    if(!v.empty()) {
        out << '[';
        std::copy(v.begin(), v.end(), std::ostream_iterator<T>(out, ", "));
        out << "\b\b]";
    }
    return out;
}

template <typename T1, typename T2>
std::ostream &operator<<(std::ostream &out, const std::pair<T1, T2> &p) {
    out << "[" << p.first << ", " << p.second << "]";
    return out;
}
//---------

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    string s;
    cin >> s;
    stack<char> st;
    for(auto &a : s){
        if(a == 'S'){
            st.push(a);
        }else if(st.empty() || a == 'T' && st.top() == 'T'){
            st.push(a);
        }else if(st.empty() || a == 'T' && st.top() == 'S' ){
            st.pop();
        }
    }
    cout << st.size() << endl;

}


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

int n,m,a[100010];

void work()
{
	scanf("%d",&n);
	for (int i=1,x; i<=n; i++)
		scanf("%d",&x),m=max(m,x),a[x]++;
	for (int i=m/2+1; i<=m; i++)
		if (a[i]<2)  puts("Impossible"),exit(0);
		else  a[i]-=2;
	if (!(m&1))
		{
			if (a[m/2]!=1)  puts("Impossible"),exit(0);
			a[m/2]=0;
		}
	for (int i=1; i<=(m+1)/2; i++)  if (a[i])  puts("Impossible"),exit(0);
	puts("Possible");
}

int main()
{
	work();
	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


using i64 = long long;
#define _overload(_1, _2, _3, _4, name, ...) name
#define _rep1(Itr, N) _rep3(Itr, 0, N, 1)
#define _rep2(Itr, a, b) _rep3(Itr, a, b, 1)
#define _rep3(Itr, a, b, step) for (i64 (Itr) = a; (Itr) < b; (Itr) += step)
#define repeat(...) _overload(__VA_ARGS__, _rep3, _rep2, _rep1)(__VA_ARGS__)

#include <iostream>
#include <string>

using namespace std;
using llong = long long;

int main() {
    string s;
    llong k;

    cin >> s >> k;

    for (auto &ch:s) {
        if ('z' - ch + 1 <= k) {
            k -= 'z' - ch + 1;
            ch = 'a';
        }
    }

    k %= 26;
    s.back() += k;
    if (s.back() > 'z') {
        s.back() -= 26;
    }

    cout << s << endl;

    return 0;
};

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>
using namespace std;
using lint     = long long;
const lint inf = 1LL << 60;
const lint mod = 1000000007;

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    string s;
    cin >> s;
    lint k;
    cin >> k;
    lint n = s.size();
    for (int i = 0; i < n; ++i) {
        if ('z' + 1 - s[i] <= k) {
            k -= ('z' - s[i]) + 1;
            s[i] = 'a';
        }
    }
    k %= lint('z' + 1 - 'a');
    s[n - 1] += k;
    cout << s << "\n";
    return 0;
}


Score : 800 points

Problem Statement

There is a grid with R rows and C columns.
We call the cell in the r-th row and c-th column (r，c).

Mr. Takahashi wrote non-negative integers into N of the cells, that is, he wrote a non-negative integer a_i into (r_i，c_i) for each i (1≤i≤N).
After that he fell asleep.

Mr. Aoki found the grid and tries to surprise Mr. Takahashi by writing integers into all remaining cells.
The grid must meet the following conditions to really surprise Mr. Takahashi.

Condition 1: Each cell contains a non-negative integer.

Condition 2: For any 2×2 square formed by cells on the grid, the sum of the top left and bottom right integers must always equal to the sum of the top right and bottom left integers.

Determine whether it is possible to meet those conditions by properly writing integers into all remaining cells.

Constraints

2≤R，C≤10^5

1≤N≤10^5

1≤r_i≤R

1≤c_i≤C

(r_i，c_i) ≠ (r_j，c_j) (i≠j)

a_i is an integer.

0≤a_i≤10^9

Input

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

R C
N
r_1 c_1 a_1
r_2 c_2 a_2
:
r_N c_N a_N

Output

Print Yes if it is possible to meet the conditions by properly writing integers into all remaining cells.
Otherwise, print No.

Sample Input 1

2 2
3
1 1 0
1 2 10
2 1 20

Sample Output 1

Yes

You can write integers as follows.

Sample Input 2

2 3
5
1 1 0
1 2 10
1 3 20
2 1 30
2 3 40

Sample Output 2

No

There are two 2×2 squares on the grid, formed by the following cells:

Cells (1，1), (1，2), (2，1) and (2，2)

Cells (1，2), (1，3), (2，2) and (2，3)

You have to write 40 into the empty cell to meet the condition on the left square, but then it does not satisfy the condition on the right square.

Sample Input 3

2 2
3
1 1 20
1 2 10
2 1 0

Sample Output 3

No

You have to write -10 into the empty cell to meet condition 2, but then it does not satisfy condition 1.

Sample Input 4

3 3
4
1 1 0
1 3 10
3 1 10
3 3 20

Sample Output 4

Yes

You can write integers as follows.

Sample Input 5

2 2
4
1 1 0
1 2 10
2 1 30
2 2 20

Sample Output 5

No

All cells already contain a integer and condition 2 is not satisfied.


#include <bits/stdc++.h>
using namespace std;
//型に気を付けよう

int main() {
  int a,b,h;
  const int p=2;
  cin>>a>>b>>h;
  cout<<((a+b)*h)/p;

}

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>
#include <ext/rope>
#define VALHALLA cin.tie(0);ios_base::sync_with_stdio(false);cout<<fixed<<setprecision(13);
#define endl "\n"
#define pb push_back
#define all(v) v.begin(),v.end()
#define debug(x) std::cerr << #x << ": " << (x) << '\n';
#define sz(x) (int)x.size()
#define fast(map_name) map_name.reserve(1024);map_name.max_load_factor(0.25);
using namespace std;
using namespace __gnu_cxx;
typedef long long int ll;
typedef pair<int,int> ii;
typedef complex<double> point;
const double epsilon=1e-9;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int mod=1e9+7;
/* VARIABLE DECLARATION START */
/*  FUCNTION TEMPLATE STARTS  HERE */

double dot(point a,point b){ return (conj(a)*b).real() ; }
double cross(point a,point b){ return (conj(a)*b).imag() ; }
double dist(point a, point b){ return abs(a-b); }
struct neal {
static uint64_t splitmix64(uint64_t x)
 {
    x += 0x9e3779b97f4a7c15;
    x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
    x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
    return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const
 {
    static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
    return splitmix64(x + FIXED_RANDOM);
}
};
struct HASH{
  size_t operator()(const pair<int,int>&x)const{
    return (size_t) x.first * 37U + (size_t) x.second;
  }
};
bool isprime(ll n) {
    if (n == 2 || n == 3) return true;
    if (n < 2 || n % 2 == 0 || n % 3 == 0) return false;
    for (ll i = 6; (i - 1) * (i - 1) <= n; i += 6) {
        if (n % (i - 1) == 0 || n % (i + 1) == 0) {
            return false;
        }
    }
    return true;
}
inline ll exp(ll a, ll b, ll mod) {
    ll n = 1;
    ll p = a;
    while (b > 0) {
        if (b % 2 == 1) {
            n *= p;
            n %= mod;
        }
        p *= p;
        p %= mod;
        b /= 2;
    }
    return n;
}

inline bool comp(double a,double b)
{
  return (fabs(a-b)<epsilon);
}
ll gcd(ll u, ll v) {
  ll r;
  while (0 != v) {
    r = u % v; u = v; v = r;
  }
  return u;
}

/*  FUCNTION TEMPLATE ENDS HERE */
int main()
{
   VALHALLA
   string s1,s2,s3;
   cin>>s1>>s2>>s3;
   map<char,string> m;
   reverse(all(s1));
   reverse(all(s2));
   reverse(all(s3));
   m['a']=s1;m['b']=s2;m['c']=s3;
   char curr='a';
   while(sz(m[curr])!=0)
   {
     string s=m[curr];
     char res=s.back();
     s.pop_back();
     m[curr]=s;
     curr=res;
   }
   cout<<char(curr-32)<<endl;

}

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

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

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


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

using namespace std;
typedef long long ll;
#define rep(i,s,n)for(ll i = s;i<n;i++)
#define repe(i,s,n)for(ll i = s;i<=n;i++)
static const ll maxLL = (ll)1 << 62;

string s;
ll ans;
set<string> se;

string create(int n) {
	string t;
	ll f = 0;
	if (n == 0) {
		return s;
	}
	while (n > 0) {
		t += s[f++];

		if (n % 2 == 1) {
			t += '+';
		}
		n /= 2;
	}
	rep(i, f, s.size()) {
		t += s[i];
	}

	return t;
}
ll convertV(string s) {
	ll ans = 0;
	ll t = 1;

	for (int i = s.size() - 1; i >= 0; i--) {
		rep(k, 0, i) {
			t *= 10;
		}
		ans += (ll)((s[s.size() - 1 - i] - '0') * t);
		t = 1;
	}

	return ans;
}

ll calc(string s) {
	string p;
	map<string, ll> value;
	rep(i, 0, s.size()) {
		if (s[i] == '+') {
			value[p]++;
			p = "";
		}
		else if (s[i] == '0' && i >= 1 && s[i - 1] == '+') {
		}
		else {
			p += s[i];
		}
		if (i == s.size() - 1) {
			value[p]++;
		}
	}

	ll cnt = 0;
	for (map<string, ll>::iterator it = value.begin(); it != value.end(); it++) {
		rep(i, 0, it->second) {
			cnt += convertV(it->first);
		}
	}
	return cnt;
}

int main() {
	cin >> s;
	ll dig = s.size();

	for (int i = 0; i < 1 << (dig - 1); i++) {
		string t = create(i);
		se.insert(t);
	}

	for (set<string>::iterator it = se.begin(); it != se.end(); it++) {
		//cout << *it << endl;
		ans += calc(*it);
	}

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

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

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

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944


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

int main(){
	string s;
	cin>>s;
	int N=s.size();

	long long ans=0;

	for(int bit=0;bit<(1<<(N-1));bit++){
		long long sum=0;

		for(int j=0;j<N-1;j++){
			sum *=10;
			sum +=s.at(j)-'0';

			if(bit &(1<<j)){
				ans+=sum;
				sum=0;
			}
		}

		sum *= 10;
		sum += s.back()-'0';
		ans += sum;
	}
	cout << ans <<endl;

	return 0;

}


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

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

  int ans = 0;

  for(int i=0;i<(1<<(S.size()-1));i++){
    int temp = i+(1<<S.size());
    int factor = 1;
    int j =S.size()-1;
    while(temp){
      ans += (stoi(S.substr(j,j+1))*factor);
      factor*=10;
      j-=1;
      if(temp&0b1) {factor=1;}
      temp = (temp>>1);
    }
  }

  cout << ans << endl;

}


#include <iostream>
#include <string>
using namespace std;
int main(){
  string s;
  cin >>s;
  long long int sum,n,ans=0,ss=s.size();
  for(int i=0;i<(1<<(ss-1));i++){
      sum=0;
      n=s[0]-'0';
      for(int j=0;j<ss-1;j++){
        if(i&(1<<j)){
          sum+=n;
          n=0;
        }
        n=n*10+s[j+1]-'0';
      }
      sum+=n;
      ans+=sum;
  }
  cout <<ans<<endl;
}


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

#include <bits/stdc++.h>

#define ll long long
#define ull unsigned long long
#define int ll
#define ld long double
#define rep(i, l, r) for (int i = l; i < r; i++)
#define repb(i, r, l) for (int i = r; i > l; i--)
#define sz(a) (int)a.size()
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define pb push_back
#define mp(a, b) make_pair(a, b)
#define ret(a) {cout << a; exit(0);}

using namespace std;

mt19937 mrand(random_device{}());
const ll mod=1000000007;
int rnd(int x) { return mrand() % x;}
ll powmod(ll a,ll b,ll mod) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}

typedef pair < int , int > pii ;
typedef pair < long long  , long long > pll ;

const int N = 1e6 + 123, K = 501;
int a[N];
int n , m ;
int c[N] , u[N] , v[N];

vector < pii > gr[N];
set < int > st[N];
int id ;
map < int , int > gid[N];
int d[N];
void flex(int x){
	for(auto to : st[x])
		gid[x][to] = ++id;
}
main(){
	ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
	cin >> n >> m;
	id = n;
	for(int i = 1 ;i <= m; i++){
		cin >> u[i] >> v[i] >> c[i];
		st[u[i]].insert(c[i]);
		st[v[i]].insert(c[i]);
	}

	for(int i = 1 ; i <= n; i++)
		flex(i);
	for(int i = 1; i <= m ; i++){
		int u1 = gid[u[i]][c[i]] , v1 = gid[v[i]][c[i]];
		gr[u1].pb({v1,0});
		gr[v1].pb({u1,0});
		gr[u1].pb({u[i],1});
		gr[v1].pb({v[i],1});
		gr[u[i]].pb({v1,0});
		gr[v[i]].pb({u1,0});
	}
	set < pii > ds;
	for(int i = 1; i <= id; i++)
		d[i] = 1e9 ;
	d[1] = 1;
	ds.insert({d[1] , 1});
	while(sz(ds) != 0){
		int u = (*ds.begin()).se;
		ds.erase(ds.begin());
		for(auto to : gr[u])
			if(d[to.fi] > d[u] + to.se){
				ds.erase({d[to.fi],to.fi});
                d[to.fi] = d[u] + to.se;
				ds.insert({d[to.fi],to.fi});
			}
	}
	int ans = d[n];
	for(auto to : st[n]){
		ans = min(ans , d[gid[n][to]]);
	}

	if(ans >= 1e9)ans = -1;
	cout << ans;

}

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


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

template <class T>
inline void read(T &x)
{
    static char c;
    x=0;
    for(c=getchar();isspace(c);c=getchar());
    static bool sign;
    sign=0;
    if (c=='-') sign=!sign,c=getchar();
    for(;isdigit(c);x=x*10+c-'0',c=getchar());
    if (sign) x=-x;
    return;
}

#ifndef DEBUG//-DDEBUG
#define SHOW(x)
#else
#define SHOW(x) cout<<#x"="<<(x)<<endl
#endif

const int MAXN=2e3+5;
ll a[MAXN<<1];
ll best[MAXN];
const ll INF=1LL<<50;
int main()
{
	int n;
	ll x;
	scanf("%d%lld",&n,&x);
	for (int i=1;i<=n;i++)
	{
		read(a[i]);
		a[i+n]=a[i];
	}
	ll ans=INF;
	memset(best,15,sizeof(best));
	for (int ev=0;ev<n;ev++)
	{
		ll sum=ev*x;
		for (int i=1;i<=n;i++)
		{
			best[i]=min(best[i],a[i+ev]);
			sum+=best[i];
		}
		ans=min(ans,sum);
	}
	printf("%lld",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 <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <iostream>
#include <istream>
#include <iterator>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
//#include <tuple>
#include <iomanip>
#include <cstring>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef vector<ll> vec;
typedef vector<vec> mat;
#define rep(i, n) for(ll i = 0; i < (n); i++)
#define revrep(i, n) for(ll i = (n-1); i >= 0; i--)
#define pb push_back
#define f first
#define s second
ll max(ll a, ll b){return (a > b) ? a : b;}
ll min(ll a, ll b){return (a < b) ? a : b;}
ll max3(ll a, ll b, ll c){return max(a, max(b, c));};
ll min3(ll a, ll b, ll c){return min(a, min(b, c));};
ll max4(ll a, ll b, ll c, ll d){return max(max(a, b), min(c, d));};
ll min4(ll a, ll b, ll c, ll d){return min(min(a, b), min(c, d));};
ll max5(ll a, ll b, ll c, ll d, ll e){return max(max(a, b), max3(c, d, e));};
ll min5(ll a, ll b, ll c, ll d, ll e){return min(min(a, b), min3(c, d, e));};

const ll INFL = 1LL << 60;//10^18 = 2^60
const int INF = 1 << 30;//10^9
ll MOD = 1000000007;
//ll MOD = 998244353;
/*
vector<ll> dy = {0, 0, 1, -1, 1, 1, -1, -1, 0};
vector<ll> dx = {1, -1, 0, 0, 1, -1, 1, -1, 0};
*/

ll pow_long(ll x, ll k){
  ll res = 1;
  while(k > 0){
    if(k % 2) res *= x;
    x *= x;
    k /= 2;
  }
  return res;
}
ll pow_mod(ll x, ll k){
  x %= MOD; x += MOD; x %= MOD;
  ll res = 1;
  while(k > 0){
    if(k % 2){
      res *= x; res %= MOD;
    }
    x *= x; x %= MOD;
    k /= 2;
  }
  return res;
}

ll inverse(ll x){return pow_mod(x, MOD - 2);};

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

ll lcm(ll x, ll y){return x / gcd(x, y) * y;};

ll kai_mod(ll x){
  if(x == 0) return 1;
  return x * kai_mod(x-1) % MOD;
}

/*
//コンビネーション
const int MAXcomb = 200010;
ll fac[MAXcomb], finv[MAXcomb], inv[MAXcomb];
//facはn!,finvは1/n!
//invは逆元
void COMinit(){
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for(int i = 2; i < MAXcomb; 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;
    }
}
ll comb(int n, int k){
    if(n < k) return 0;
    if(n < 0 || k < 0) return 0;
    return fac[n] * finv[k] % MOD * finv[n-k] % MOD;
}
*/

ll N, K;
vector<ll> tree[100010];
vector<ll> depth(100010);
map<pair<ll, ll>, ll> memo;
ll ans;

void make_depth(ll now, ll dep){
  depth[now] = dep;
  for(ll to : tree[now]){
    make_depth(to, dep + 1);
  }
}

ll solve(ll now, ll dep){
  if(memo[{now, dep}] != 0) return (memo[{now, dep}] - 1);
  if(dep > K){
    ll res = 0;
    res++;
    for(ll to : tree[now]) res += solve(to, 2);
    memo[{now, dep}] = res + 1;
    return res;
  }else{
    ll res1 = 0;
    res1++;
    for(ll to : tree[now]) res1 += solve(to, 2);

    ll res2 = 0;
    for(ll to : tree[now]) res2 += solve(to, dep + 1);
    ll res = min(res1, res2);
    memo[{now, dep}] = res + 1;
    return res;
  }
}

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

  rep(i, N){
    ll a;
    cin >> a;
    a--;
    if(i == 0){
      if(a != 0) ans++;
      continue;
    }
    tree[a].pb(i);
  }
  make_depth(0, 0);
  ans += solve(0, 0);
  cout << ans << endl;

}

Score : 800 points

Problem Statement

There are N towns in Snuke Kingdom, conveniently numbered 1 through N.
Town 1 is the capital.

Each town in the kingdom has a Teleporter, a facility that instantly transports a person to another place.
The destination of the Teleporter of town i is town a_i (1≤a_i≤N).
It is guaranteed that one can get to the capital from any town by using the Teleporters some number of times.

King Snuke loves the integer K.
The selfish king wants to change the destination of the Teleporters so that the following holds:

Starting from any town, one will be at the capital after using the Teleporters exactly K times in total.

Find the minimum number of the Teleporters whose destinations need to be changed in order to satisfy the king's desire.

Constraints

2≤N≤10^5

1≤a_i≤N

One can get to the capital from any town by using the Teleporters some number of times.

1≤K≤10^9

Input

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

N K
a_1 a_2 ... a_N

Output

Print the minimum number of the Teleporters whose destinations need to be changed in order to satisfy King Snuke's desire.

Sample Input 1

3 1
2 3 1

Sample Output 1

2

Change the destinations of the Teleporters to a = (1,1,1).

Sample Input 2

4 2
1 1 2 2

Sample Output 2

0

There is no need to change the destinations of the Teleporters, since the king's desire is already satisfied.

Sample Input 3

8 2
4 1 2 3 1 2 3 4

Sample Output 3

3

For example, change the destinations of the Teleporters to a = (1,1,2,1,1,2,2,4).


#include <iostream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>

#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define ford(i, n) for (int i = (int)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)

using namespace std;

typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<pii> vpi;
typedef vector<vi> vvi;
typedef long long i64;
typedef vector<i64> vi64;
typedef vector<vi64> vvi64;

template<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }
template<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }

const int maxn = 110000;
int n, k;
vi e[maxn];

pii dfs(int v, bool fix = false) {
    int s = 0, h = 0;
    for (int u: e[v]) {
        pii res = dfs(u);
        s += res.fi;
        uax(h, res.se + 1);
    }
    if (h == k && !fix) ++s, h = 0;
//    cerr << v << ' ' << s << ' ' << h << '\n';
    return mp(s, h);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.precision(10);
    cout << fixed;
#ifdef LOCAL_DEFINE
    freopen("input.txt", "rt", stdin);
#endif

    cin >> n >> k;
    int ans = 0;
    forn(i, n) {
        int x;
        cin >> x;
        --x;
        if (!i) ans += x != 0;
        else e[x].pb(i);
    }
    --k;
    for (int v: e[0]) ans += dfs(v, true).fi;
    cout << ans << '\n';

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