#include <bits/stdc++.h>
using namespace std;
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
typedef long long ll;
typedef pair<int, int> P;
const int INF = 100100100;
const int MOD = (int)1e9 + 7;
const double EPS = 1e-9;
struct Edge {
  ll to;
  ll cost;
};
int main() {
  int N, A, B, C, D;
  cin >> N >> A >> B >> C >> D, A--, B--, C--, D--;
  string S;
  cin >> S;
  for (int i = A; i <= max(C, D) - 1; i++) {
    if (S[i] == '#' && S[i + 1] == '#') {
      cout << "No" << endl;
      return 0;
    }
  }
  if (D < C) {
    bool t = false;
    for (int i = B - 1; i <= D - 2; i++) {
      if (S[i] == '.' && S[i + 1] == '.' && S[i + 2] == '.') t = true;
    }
    if (t) {
      cout << "Yes" << endl;
    } else {
      cout << "No" << endl;
    }
    return 0;
  } else {
    cout << "Yes" << endl;
  }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,a,b,c,d;
    string s;
    scanf("%d %d %d %d %d",&n,&a,&b,&c,&d);
    cin>>s;
    a--;
    b--;
    c--;
    d--;
    int x=0,y=0;
    int m=max(c,d);
    for(int i=min(a,b);i<m;i++)
    {
        if(s[i]=='#' && s[i+1]=='#')
        {
            x++;
            break;
        }
    }
    m=min(c,d);
    for(int i=min(a,b);i<=m-2;i++)
    {
        if(s[i]=='.' && s[i+1]=='.' && s[i+2]=='.')
        {
            y++;
            break;
        }
    }
    if(x)
    {
        printf("No");
        return 0;
    }
    if(d<c)
    {
        if(s[d-1]=='.' && s[d+1]=='.' && s[d]=='.')
        printf("Yes");
        else
        {
            if(y) printf("Yes");
            else printf("No");
        }
    }
    else printf("Yes") ;
    return 0;
}

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

Score : 400 points

Problem Statement

There are N squares arranged in a row, numbered 1, 2, ..., N from left to right.
You are given a string S of length N consisting of . and #. If the i-th character of S is #, Square i contains a rock; if the i-th character of S is ., Square i is empty.

In the beginning, Snuke stands on Square A, and Fnuke stands on Square B.

You can repeat the following operation any number of times:

Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.

You want to repeat this operation so that Snuke will stand on Square C and Fnuke will stand on Square D.

Determine whether this is possible.

Constraints

4 \leq N \leq 200\ 000

S is a string of length N consisting of . and #.

1 \leq A, B, C, D \leq N

Square A, B, C and D do not contain a rock.

A, B, C and D are all different.

A < B

A < C

B < D

Input

Input is given from Standard Input in the following format:

N A B C D
S

Output

Print Yes if the objective is achievable, and No if it is not.

Sample Input 1

7 1 3 6 7
.#..#..

Sample Output 1

Yes

The objective is achievable by, for example, moving the two persons as follows. (A and B represent Snuke and Fnuke, respectively.)

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

7 1 3 7 6
.#..#..

Sample Output 2

No

Sample Input 3

15 1 3 15 13
...#.#...#.#...

Sample Output 3

Yes

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>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef pair<int,P> P1;
typedef pair<P,P> P2;
#define pu push
#define pb push_back
#define mp make_pair
#define eps 1e-7
#define INF 1000000000
#define fi first
#define sc second
#define rep(i,x) for(int i=0;i<x;i++)
#define repn(i,x) for(int i=1;i<=x;i++)
#define SORT(x) sort(x.begin(),x.end())
#define ERASE(x) x.erase(unique(x.begin(),x.end()),x.end())
#define POSL(x,v) (lower_bound(x.begin(),x.end(),v)-x.begin())
#define POSU(x,v) (upper_bound(x.begin(),x.end(),v)-x.begin())

int n;
bool h[2005];
vector<int>edge[2005];
int dist[2005][2005];
int sum[2005][2005];
int cnt[2005][2005];
P dfs(int v,int u,int g,int d){
	dist[g][v] = d;
	if(h[v]){
		sum[g][v] = d;
		cnt[g][v] = 1;
	}
	rep(i,edge[v].size()){
		if(edge[v][i] == u) continue;
		P p = dfs(edge[v][i],v,g,d+1);;
		sum[g][v] += p.fi;
		cnt[g][v] += p.sc;
	}
	return P(sum[g][v],cnt[g][v]);
}
int gen(int v,int u,int g){
	int S = 0, mx = 0;
	rep(i,edge[v].size()){
		if(edge[v][i] == u) continue;
		S += sum[g][edge[v][i]];
		mx = max(mx,sum[g][edge[v][i]]);
	}
	if(mx <= S/2) return cnt[g][v]+S%2;
	else{
		int id;
		rep(i,edge[v].size()){
			if(edge[v][i] == u) continue;
			if(mx == sum[g][edge[v][i]]) id = edge[v][i];
		}
		int reduction = gen(id,v,g);
		if(reduction <= S-mx) return cnt[g][v]+S%2;
		else return (reduction-S+mx)+cnt[g][v];
	}
}
int check(int v,int u,int g){
	int S = 0, mx = 0;
	rep(i,edge[v].size()){
		if(edge[v][i] == u) continue;
		S += sum[g][edge[v][i]];
		mx = max(mx,sum[g][edge[v][i]]);
	}
	if(u == -1){
		if(mx <= S/2) return S;
		int id = -1;
		rep(i,edge[v].size()){
			if(edge[v][i] == u) continue;
			if(sum[g][edge[v][i]] == mx) id = edge[v][i];
		}
		int reduction = gen(id,v,g);
		//cout << id << " " << v << " " << g << " " << reduction << endl;
		if(reduction > S-mx) return INF;
		else return S;
	}
}
int main(){
	cin >> n;
	string s; cin >> s;
	rep(i,n) if(s[i] == '1') h[i+1] = 1;
	rep(i,n-1){
		int a,b; cin >> a >> b;
		edge[a].pb(b);edge[b].pb(a);
	}
	repn(i,n) dfs(i,-1,i,0);
	int ans = INF;
	repn(i,n){
		if(sum[i][i]%2 == 1) continue;
		ans = min(ans,check(i,-1,i));
		assert(ans%2 == 0);
		//cout << i << " " << check(i,-1,i) << endl;
	}
	cout << (ans>INF/2?-1:ans/2) << endl;
}

Score : 1500 points

Problem Statement

You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i.
You are also given a string S of length N consisting of 0 and 1. The i-th character of S represents the number of pieces placed on Vertex i.

Snuke will perform the following operation some number of times:

Choose two pieces the distance between which is at least 2, and bring these pieces closer to each other by 1. More formally, choose two vertices u and v, each with one or more pieces, and consider the shortest path between them. Here the path must contain at least two edges. Then, move one piece from u to its adjacent vertex on the path, and move one piece from v to its adjacent vertex on the path.

By repeating this operation, Snuke wants to have all the pieces on the same vertex. Is this possible?
If the answer is yes, also find the minimum number of operations required to achieve it.

Constraints

2 \leq N \leq 2000

|S| = N

S consists of 0 and 1, and contains at least one 1.

1 \leq a_i, b_i \leq N(a_i \neq b_i)

The edges (a_1, b_1), (a_2, b_2), ..., (a_{N - 1}, b_{N - 1}) forms a tree.

Input

Input is given from Standard Input in the following format:

N
S
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}

Output

If it is impossible to have all the pieces on the same vertex, print -1. If it is possible, print the minimum number of operations required.

Sample Input 1

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

Sample Output 1

3

We can gather all the pieces in three operations as follows:

Choose the pieces on Vertex 3 and 5.

Choose the pieces on Vertex 2 and 7.

Choose the pieces on Vertex 4 and 6.

Sample Input 2

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

Sample Output 2

-1

Sample Input 3

2
01
1 2

Sample Output 3

0


#include<bits/stdc++.h>
#define REP(i,x,y) for(ll i=x; i<=y; i++)
using namespace std;
typedef long long ll;

ll const MAX = 2005;
vector<ll> g[MAX];
bool ex[MAX];

bool dfs(vector<long long>& num, vector<ll>& dist, vector<ll>& point, vector<bool>& visited, ll cur, ll i){
    visited[cur] = 1;
    for(ll nx: g[cur]){
        if(visited[nx]){
            continue;
        }
        dfs(num, dist, point, visited, nx, i);

        dist[nx] += num[nx];
        ll dn = dist[nx], dc = dist[cur], pn = point[nx], pc = point[cur];
        if(dist[nx] < dist[cur]){
            swap(dn, dc);
            swap(pn, pc);
        }
        point[cur] = dc * 2 + min(dn - dc, pn) / 2 * 2;
        num[cur] += num[nx];
        dist[cur] += dist[nx];
    }
    num[cur] += ex[cur];
    return (dist[cur] == point[cur]);
}

ll f(ll n,ll i){
    vector<long long> num(MAX, 0), dist(MAX, 0), point(MAX,0);
    vector<bool> visited(MAX, 0);
    if(dfs(num, dist, point, visited, i, i)){
        return point[i] / 2;
    }else{
        return 1e18;
    }
}

int main(){
    ll n;
    cin >> n;
    string s;
    cin >> s;
    REP(i,1,n-1){
        ll a,b;
        cin >> a >> b;
        g[a].push_back(b);
        g[b].push_back(a);
    }

    REP(i,1,n){
        ex[i] = (s[i-1] == '1');
    }
    ll ans = 1e18;
    REP(i,1,n){
        ans = min(ans, f(n, i));
    }
    if(ans == 1e18){
        cout << -1 << endl;
    }else{
        cout << ans << endl;
    }
}


#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

int n;
char s[2001];
vector <int> v[2000];

pair<int, pair<int, int>> dfs(int x, int y) {
    int c1 = 0, c2 = 0, c3 = 0, m = 0, sum = 0, i;

    for (i = 0; i < v[x].size(); i++) {
        if (v[x][i] == y) continue;

        pair<int, pair<int, int>> p = dfs(v[x][i], x);

        c1 += p.first;
        c2 += p.second.first;
        c3 += p.second.second;
        m = max(m, p.second.first - p.second.second * 2);
        sum += p.second.first - p.second.second * 2;
    }

    c3 += max(sum - m, sum / 2);

    if (s[x] == '1') c1++;

    c2 += c1;

    return make_pair(c1, make_pair(c2, c3));
}

int calc(int x) {
    int sum = 0, m1 = 0, m2 = 0, i;

    for (i = 0; i < v[x].size(); i++) {
        pair<int, pair<int, int>> p = dfs(v[x][i], x);

        if (p.first > 0) {
            sum += p.second.first;
            if (p.second.first > m1) {
                m1 = p.second.first;
                m2 = p.second.second;
            }
        }
    }

    if (sum % 2 == 0 && m1 - m2 * 2 <= sum - m1) {
        return sum / 2;
    } else {
        return 1e9;
    }
}

int main() {
    int ans = 1e9, i;

    scanf("%d", &n);
    scanf("%s", s);

    for (i = 0; i < n - 1; i++) {
        int a, b;

        scanf("%d %d", &a, &b);
        a--;
        b--;

        v[a].push_back(b);
        v[b].push_back(a);
    }

    for (i = 0; i < n; i++) ans = min(ans, calc(i));

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

    return 0;
}


#include<iostream>
using namespace std;

int main(){
	int n;
	cin >> n;
	cout << 180*(n-2) << endl;
	return 0;
}

Score : 100 points

Problem Statement

Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.

Print the answer in degrees, but do not print units.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print an integer representing the sum of the interior angles of a regular polygon with N sides.

Sample Input 1

3

Sample Output 1

180

The sum of the interior angles of a regular triangle is 180 degrees.

Sample Input 2

100

Sample Output 2

17640


//#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) FOR(i,0,n)
#define ROF(i,a,b) for(int i=a;i>=b;i--)
#define per(i,a) ROF(i,a,0)
#define pb push_back
using namespace std;
using ll=long long;
using ld=long double;
typedef pair<ll,ll> P;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<P> vP;
typedef vector<char> vc;
typedef vector<vc> vvc;
const ll MOD=1000000007;
const ll MOD2=998244353;
const ld PI=acos(-1);
const ll INF=1e18;
struct edge{ll to,cost;};
struct edge2{ll from,to,cost;};

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

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

ll pow_mod(ll x,ll y){
    if(y==0)return 1;
    if(y%2==1)return (x*pow_mod(x,y-1))%MOD;
    ll t=pow_mod(x,y/2);return (t*t)%MOD;
}
//組み合わせを線形で
//参考:https://drken1215.hatenablog.com/entry/2018/06/08/210000

const int MXN=200001;//変更可
ll fac[MXN],inv[MXN],finv[MXN];

void COMinit(int M) {
    fac[0]=fac[1]=1;
    inv[1]=1;
    finv[0]=finv[1]=1;
    for(int i=2;i<MXN;i++){
        fac[i]=fac[i-1]*i%M;
        inv[i]=M-M/i*inv[M%i]%M;
        finv[i]=finv[i-1]*inv[i]%M;
    }
}

ll COMBI(int N,int K,int M){
    if(N<K){
        return 0;
    }
    if(N<0||K<0){
        return 0;
    }
    return fac[N]*finv[N-K]%M*finv[K]%M;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    ll N,A,B,C;//Cは別物として考えていい（線形性より）
    cin >> N >> A >> B >> C;
    COMinit(MOD);
    ll resA=0,resB=0,powa=1,powb=1;
    rep(i,N){//aoki が i 回勝つ
        resA+=(N+i)*((powb*COMBI(N-1+i,i,MOD))%MOD)%MOD;
        powb*=(B*inv[A+B])%MOD;
        powb%=MOD;
        resA%=MOD;
    }
    resA*=pow_mod(A,N);
    rep(i,N){//takahashi が i 回勝つ
        resB+=(N+i)*((powa*COMBI(N-1+i,i,MOD))%MOD)%MOD;
        powa*=(A*inv[A+B])%MOD;
        powa%=MOD;
        resB%=MOD;
    }
    resB*=pow_mod(B,N);
    resA%=MOD;resB%=MOD;
    ll res=(resA+resB)%MOD;
    res*=pow_mod(inv[A+B],N);
    res%=MOD;
    res*=100;
    res%=MOD;
    res*=inv[100-C];
    res%=MOD;
    cout << res << endl;
}
/*
overflow checked?
corner case checked?
boundary checked?
not TLE in worst case checked?
*/

Score : 500 points

Problem Statement

Takahashi and Aoki will play a game. They will repeatedly play it until one of them have N wins in total.

When they play the game once, Takahashi wins with probability A %, Aoki wins with probability B %, and the game ends in a draw (that is, nobody wins) with probability C %.
Find the expected number of games that will be played, and print it as follows.

We can represent the expected value as P/Q with coprime integers P and Q.
Print the integer R between 0 and 10^9+6 (inclusive) such that R \times Q \equiv P\pmod {10^9+7}.
(Such an integer R always uniquely exists under the constraints of this problem.)

Constraints

1 \leq N \leq 100000

0 \leq A,B,C \leq 100

1 \leq A+B

A+B+C=100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C

Output

Print the expected number of games that will be played, in the manner specified in the statement.

Sample Input 1

1 25 25 50

Sample Output 1

2

Since N=1, they will repeat the game until one of them wins.
The expected number of games played is 2.

Sample Input 2

4 50 50 0

Sample Output 2

312500008

C may be 0.

Sample Input 3

1 100 0 0

Sample Output 3

1

B may also be 0.

Sample Input 4

100000 31 41 28

Sample Output 4

104136146


#include <bits/stdc++.h>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
cout<<(a*3+b)/2;
}

Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.

Find the maximum number of apple pies we can make with what we have now.

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

Print the maximum number of apple pies we can make with what we have.

Sample Input 1

1 3

Sample Output 1

3

We can first make one apple pie by simmering two of the three pieces of apple. Then, we can make two more by simmering the remaining piece and three more pieces obtained by cutting the whole apple.

Sample Input 2

0 1

Sample Output 2

0

We cannot make an apple pie in this case, unfortunately.

Sample Input 3

32 21

Sample Output 3

58


#include <bits/stdc++.h>
#include <iomanip>      // std::setprecision
using namespace std;
#define what_is(x) cerr << #x << " is " << x << endl;
#define bit(x,i) (x&(1<<i))  //select the bit of position i of x
#define lowbit(x) ((x)&((x)^((x)-1))) //get the lowest bit of x
#define hBit(msb,n) asm("bsrl %1,%0" : "=r"(msb) : "r"(n)) //get the highest bit of x, maybe the fastest
#define max(a,b) (a<b?b:a)
#define IN(i,l,r) (l<i&&i<r) //the next for are for checking bound
#define LINR(i,l,r) (l<=i&&i<=r)
#define LIN(i,l,r) (l<=i&&i<r)
#define INR(i,l,r) (l<i&&i<=r)
#define F(i,L,R) for (int i = L; i < R; i++) //next four are for "for loops"
#define FE(i,L,R) for (int i = L; i <= R; i++)
#define FF(i,L,R) for (int i = L; i > R; i--)
#define FFE(i,L,R) for (int i = L; i >= R; i--)
#define char2Int(c) (c-'0')
#define lastEle(vec) vec[vec.size()-1]
#define SZ(x) ((int)((x).size()))
#define REMAX(a,b) (a)=max((a),(b)) // set a to the maximum of a and b
#define REMIN(a,b) (a)=min((a),(b));
#define FENWICK(k) (k&-k)
#define FOREACH(i,t) for (auto i=t.begin(); i!=t.end(); i++) // traverse an STL data structure
#define ALL(c) (c).begin(),(c).end() //handy for function like "sort()"
#define PRESENT(c,x) ((c).find(x) != (c).end())
#define CPRESENT(c,x) (find(ALL(c),x) != (c).end())
#define LL long long //data types used often, but you don't want to type them time by time
#define ull unsigned long long
#define ui unsigned int
#define us unsigned short
#define IOS ios_base::sync_with_stdio(0); //to synchronize the input of cin and scanf
#define INF 1001001001
#define PI 3.1415926535897932384626
//for map, pair
#define mp make_pair
#define fi first
#define se second
//for vectors
#define pb push_back
typedef int elem_t;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> ii;
// directions
const int fx[4][2] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
const int fxx[8][2] = {{0,1}, {0,-1}, {1,0}, {-1,0}, {1,1}, {1,-1}, {-1,1}, {-1,-1}};
const int rogi[4][2] = { {1,1}, {1,-1}, {-1,1}, {-1,-1} };

int n,k;
LL val[111];
LL best = 0;

vector<LL> vals;
void dane() {
	cin>>n>>k;
	F(i,0,n) cin>>val[i];

	F(ile_lewa,0,n) {
		F(ile_prawa,0,(n-ile_lewa-1)) {
			LL sum = 0;
			if(ile_lewa + ile_prawa > k || ile_lewa + ile_prawa > n) {
				continue;
			}
			//cout<<"Ile lewa: "<<ile_lewa<<" "<<ile_prawa<<endl;
			vals.clear();
			//dodajemy elementy
			F(i,0,ile_lewa) {
				vals.push_back(val[i]);
				sum+=val[i];
			}
			F(i,0,ile_prawa) {
				vals.push_back(val[n-i-1]);
				sum+=val[n-i-1];
			}
			best = max(best, sum);
			//cout<<"SUM : "<<sum<<endl;
			sort(ALL(vals));
			int kroki = min((int)vals.size(),k- ile_lewa - ile_prawa);
			//poki mozna tu usuwamy najmniejszy
			F(i,0,kroki) {
				sum-=vals[i];
				best = max(best, sum);
			}
		}
	}
	cout<<best<<endl;

}

int main() {
	IOS
	// int t;
	// cin>>t;
	// F(i,0,t)
	    dane();
    return 0;
}

Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.


#include "iostream"
#include "vector"
using namespace std;
int main()
{
    int r,d,x200;
    cin>>r>>d>>x200;

    int result[11];
    result[0]=x200;

    for(int i=1;i<=10;i++)
    {
        result[i]=result[i-1]*r-d;
        cout<<result[i]<<endl;
    }

}

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


#include<iostream>
using namespace std;
int x[12];
int main(){
	int a,b,c;
	cin>>a>>b>>c;
	x[0]=a*c-b;
	cout<<x[0]<<endl;
	for(int i=1;i<=9;i++){
		x[i]=a*x[i-1]-b;
		cout<<x[i]<<endl;
	}
	return 0;
}


#include <string>
#include <iostream>
#include <vector>
#include <stack>
#include <stdio.h>
#include <math.h>
#include <utility>
#include <algorithm>
#include <sstream>

using namespace std;

int main() {
	int r,d, x;
	cin >> r >> d >> x;
	for (int i = 0; i < 10; i++) {
		x=r*x - d;
		cout << x<<endl;
	}

	return 0;
}


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

int main() {
  int n,m;
  cin>>n>>m;
  vector<int> l(m);
  vector<int> r(m);
  for (int i=0;i<m;++i) {
    cin>>l[i]>>r[i];
  }
  sort(l.begin(), l.end());
  sort(r.begin(), r.end());
  if (r[0]>=l[m-1]) {
    int num=r[0]-l[m-1]+1;
    cout<<num<<endl;
  } else {
    cout<<0<<endl;
  }
}

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


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

int main()
{
  long int n,m;
  cin >> n >> m;
  vector<pair<int,int> > v;
  long int a,b,c;
  for(int i=0;i<n;++i){
    cin >> a;
    v.push_back(make_pair(a,1));
  }
  for(int i=0;i<m;++i){
	cin >> b >> c;
    v.push_back(make_pair(c,b));
  }
  sort(v.begin(),v.end(),greater<>());
  long int sum=0;
  long int cnt=n;
  for(int i=n;i>0 && cnt>0;--i){
    if(cnt-v[n-i].second>=0) sum += (long)v[n-i].first*v[n-i].second;
    else sum += v[n-i].first*cnt;
    cnt-=v[n-i].second;
  }
  cout << sum << endl;
  return 0;
}

Score : 400 points

Problem Statement

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

By replacing the integer on the second card with 5, the sum of the integers written on the three cards becomes 5 + 5 + 4 = 14, which is the maximum result.

Sample Input 2

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Sample Output 4

10000000001

The output may not fit into a 32-bit integer type.


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

int N, M;
vector<int> A;
vector<pair<int, int>> CB(100000);

int
main()
{
  cin >> N >> M;
  for (int i = 0; i < N; i++) {
    int a; cin >> a;
    A.emplace_back(a);
  }
  for (int i = 0; i < M; i++) {
    cin >> CB.at(i).second >> CB.at(i).first;
  }

  sort(CB.begin(), CB.begin() + M);
  int index = N;
  for (int i = 0; i < M; i++) {
    for (int j = 0; j < CB.at(i).second; j++) {
      A.emplace_back(CB.at(i).first);
      index++;
    }
  }

  if (100000 < index) index = 100000;

  sort(A.begin(), A.end(), greater<int>());

  unsigned long long num = 0;
  for (int i = 0; i < N; i++) {
    num += A.at(i);
  }

  cout << num << endl;

  /*
  for (int i = index - 1; i > 0; i--)
    cout << A.at(i) << endl;
  for (int i = 0; i < M; i++) {
    cout << CB.at(i).second << "," << CB.at(i).first << endl;

  */
}
/*
3 2
5 1 4
2 3
1 5
 */


#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
#include<sstream>

using namespace std;

int main(void)
{
	string S;
	cin >> S;
	string front = S.substr(0, S.length() / 2);
	string back = S.substr(S.length() / 2);
	int frontInt = 0;
	int backInt = 0;
	istringstream iss(front);
	iss >> frontInt;
	istringstream iss2(back);
	iss2 >> backInt;

	if (frontInt <= 12 && backInt <= 12 && frontInt > 0 && backInt > 0)
	{
		cout << "AMBIGUOUS";
	}
	else if (backInt <= 12 && backInt > 0)
	{
		cout << "YYMM";
	}
	else if (frontInt <= 12 && frontInt > 0)
	{
		cout << "MMYY";
	}
	else
		cout << "NA";
}

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

#define REP(i, n) for (ll i = 0; i < (n); i++)
#define REPR(i, n) for (ll i = (n); i >= 0; i--)
#define FOR(i, m, n) for (ll i = (m); i < (n); i++)
#define FORR(i, m, n) for (ll i = (m); i >= (n); i--)
#define INF 1e9
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((ll)(x).size())
#define SORT(x) sort((x).begin(), (x).end())
#define dump(x) cerr << #x << " = " << (x) << endl
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" \
                      << " " << __FILE__ << endl

int main(int argc, char const *argv[])
{
    string s;
    cin >> s;
    ll s0 = (s[0] - '0');
    ll s1 = (s[1] - '0');
    ll s2 = (s[2] - '0');
    ll s3 = (s[3] - '0');
    ll a = s0 * 10 + s1;
    ll b = s2 * 10 + s3;
    // bool a_year = true;
    bool a_month = true;
    // bool b_year = true;
    bool b_month = true;
    if (a < 1 || a > 12)
        a_month = false;
    if (b < 1 || b > 12)
        b_month = false;
    if (a_month && b_month)
        cout << "AMBIGUOUS" << endl;
    else if (!a_month && b_month)
        cout << "YYMM" << endl;
    else if (a_month && !b_month)
        cout << "MMYY" << endl;
    else
        cout << "NA" << endl;
    return 0;
}


#include <iostream>
#include <string>

using namespace std;
int main()
{
	double N, K;
	cin >> N >> K;
	double ans = 0;
	for(int i = 1; i <= N; i++)
	{
		double temp = 1.0 / N;
		int cur = i;
		while(cur < K)
		{
			cur *= 2;
			temp *= 0.5;
		}
		ans += temp;
	}
	printf("%.12f", ans);
	return 0;
}

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


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

int N;
vector<vector<pair<int,int>>> G;
vector<int> seen;
void dfs(int a,int b){
  seen[a]=b;
  for(auto x:G[a]){
    int s,t;
    tie(s,t)=x;
    if(seen[s]==-1){
      dfs(s,(b+t)%2);
    }
  }
}

int main() {
  cin>>N;
  G.resize(N);
  seen.resize(N);
  for(int i=0;i<N;i++){
    seen[i]=-1;
  }
  for(int i=1;i<N;i++){
    int a,b,c;
    cin>>a>>b>>c;
    a--,b--;
    G[b].push_back(make_pair(a,c));
    G[a].push_back(make_pair(b,c));
  }
  dfs(0,0);
  for(int i=0;i<N;i++){
    cout<<seen[i]<<endl;
  }
}

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

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

Sample Output 2

1
0
1
0
1


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <string>
#include <stack> // s.top()
#include <bitset>
#include <queue> // s.front()
using namespace std;
using Graph = vector<vector<pair<int, int> > >;
typedef long long ll;
typedef pair<ll, ll> P;
#define print(x) cout<<(x)<<endl
#define INF10 10000000000
#define INF5 100000
#define EPS 1e-10
#define MOD 1000000007

vector<int> color;

Graph g(100010);

void dfs(int current, int col) {
	color[current] = col;
	for (int i = 0; i < g[current].size(); i++) {
		if (color[g[current][i].first] != 0)continue;
		else {
			if (g[current][i].second % 2 == 0) {
				dfs(g[current][i].first, col);
			}
			else dfs(g[current][i].first, -1 * col);
		}
	}
	return;
}

int main(){
	int N; cin >> N;
	for (int i = 0; i < N-1; i++) {
		int u, v, w;
		cin >> u >> v >> w;
		u--; v--;
		g[u].push_back(pair<int, int>(v, w));
		g[v].push_back(pair<int, int>(u, w));
	}
	color.assign(N, 0);

	for (int i = 0; i < N; i++) {
		if (color[i] != 0)continue;
		dfs(i, 1);
	}
	for (int i = 0; i < color.size(); i++) {
		cout << max(color[i], 0) << endl;
	}

	return 0;
}


#include<iostream>
using namespace std;

void print_stack(int stack[], int i_top){
    for(int i = 0; i <= i_top; ++i){
        cout << stack[i] << " ";
    }
    cout << endl;
}

void print_edge(int edge[], int n){
    cout << "\n===" << endl;
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < n; ++j){
            cout << ((edge[i*n+j] == -1) ? 8 : edge[i*n+j]) << " ";
        }
        cout << endl;
    }
    cout << "\n===" << endl;
}

void color_tree(int edge[], int n, int ans[]){
    int stack[n];
    int i_top = 0;
    stack[0] = 0;
    ans[0] = 0;

    int count = 0;
    while(0 <= i_top){
        if(count++ > 10) break;
        int from = stack[i_top];
        --i_top;

        for(int to = 0; to < n; ++to){
            if(0 <= edge[from*n + to]){
                edge[to*n + from] = -1;  // Remove the reverse edge.

                ++i_top;
                stack[i_top] = to;

                ans[to] = (ans[from] + edge[from*n + to]) % 2;

            }
        }
        // print_edge(edge, n);
        // print_stack(stack, i_top);
    }
}

int main(void){
    int n;
    cin >> n;

    int edge[n * n];

    fill(edge, edge + n * n, -1);

    for(int i = 0; i < n - 1; ++i){
        int u, v, w;
        cin >> u >> v >> w;
        u = u - 1;
        v = v - 1;
        edge[u*n + v] = w % 2;
        edge[v*n + u] = w % 2;
    }

    // print_edge(edge, n);

    int ans[n];
    color_tree(edge, n, ans);

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

    return 0;
}


#include "bits/stdc++.h"
#define in std::cin
#define out std::cout
#define rep(i,N) for(LL i=0;i<N;++i)
typedef long long int LL;

int main()
{
	LL N, K;
	in >> N >> K;
	out << (N - K + 1) << std::endl;
}

Score : 100 points

Problem Statement

Snuke has N integers: 1,2,\ldots,N.
He will choose K of them and give those to Takahashi.

How many ways are there to choose K consecutive integers?

Constraints

All values in input are integers.

1 \leq K \leq N \leq 50

Input

Input is given from Standard Input in the following format:

N K

Output

Print the answer.

Sample Input 1

3 2

Sample Output 1

2

There are two ways to choose two consecutive integers: (1,2) and (2,3).

Sample Input 2

13 3

Sample Output 2

11


#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include <algorithm>
#include <map>
using namespace std;

int main()
{
	int n, k;
	cin >> n >> k;
	cout << n - k + 1 << endl;
	//system("pause");
	return 0;
}


#include<bits/stdc++.h>

#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define ll long long

#pragma GCC optimize("Ofast")

using namespace std;

bool is_integer( float x ){
    return floor(x) == x;
}
bool is_integer(double x){
    return floor(x) == x;
}

int main() {

    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    float a[3]; cin >> a[0] >> a[1] >> a[2];
    float n; cin >> n;
    int ans = 0;
    sort(a,a+3);

    rep(i,3001){
        rep(j,3001){
            if(is_integer((n-i*a[0]-j*a[1])/a[2]) && (n-i*a[0]-j*a[1]) >= 0){
                ans ++;
            }
        }
    }

    cout << ans;

    return 0;
}

Score : 200 points

Problem Statement

Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:

Red boxes, each containing R red balls

Green boxes, each containing G green balls

Blue boxes, each containing B blue balls

Snuke wants to get a total of exactly N balls by buying r red boxes, g green boxes and b blue boxes.
How many triples of non-negative integers (r,g,b) achieve this?

Constraints

All values in input are integers.

1 \leq R,G,B,N \leq 3000

Input

Input is given from Standard Input in the following format:

R G B N

Output

Print the answer.

Sample Input 1

1 2 3 4

Sample Output 1

4

Four triples achieve the objective, as follows:

(4,0,0)

(2,1,0)

(1,0,1)

(0,2,0)

Sample Input 2

13 1 4 3000

Sample Output 2

87058


#include <iostream>
using namespace std;

int main()
{
	int R, G, B, N;
	cin >> R >> G >> B >> N;

	int maxR = N / R;
	int maxG = N / G;
	int maxB = N / B;

	int result = 0;
	for (int r = 0; r <= maxR; ++r) {
		for (int g = 0; g <= maxG; ++g) {
			for (int b = 0; b <= maxB; ++b) {
				if (r*R + g * G + b * B == N) {
					++result;
				}
			}
		}
	}

	cout << result << endl;

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

int cnt[3];

int main() {
    int ans = 0;

    int n; cin >> n;
    for (int i = 1; i <= n; ++i) {
        string s; cin >> s;

        for (int j = 0; j + 1 < (int) s.length(); ++j) {
            if (s[j] == 'A' && s[j + 1] == 'B') {
                ++ans;
            }
        }

        if (s.front() == 'B' && s.back() == 'A') {
            ++cnt[2];
        } else if (s.front() == 'B') {
            ++cnt[0];
        } else {
            ++cnt[1];
        }
    }

    if (cnt[2] == 0) {
        ans += min(cnt[0], cnt[1]);
    } else {
        ans += cnt[2] - 1;
        cnt[2] = 1;
        if (cnt[0] > 0 || cnt[1] > 0) {
            ans += 1;
            ans += min(cnt[0], cnt[1]);
        }
    }

    cout << ans << endl;

    return 0;
}

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


#include <iostream>
#include <string>
using namespace std;
int main(){
  int N; cin >> N;
  //vector<string> s;
  int a=0, b=0, ans=0;
  //string AB = "AB"
  //int size = AB.size();
  for(int i=0; i<N; i++) {
    string s_hold;
    cin >> s_hold;
    //s.push_back(s_hold);
    if (s_hold[0] == 'B') {
      b++;
    }
    for (int p = 0; p < s_hold.length() - 1; p++) {
      if (s_hold[p] == 'A') {
        if (s_hold[p+1] == 'B') {
          ans++;
        }
      }
    }
    if (s_hold[s_hold.length() - 1] == 'A') {
      a++;
    }
    //int p;
    /*while (p != string::npos) {
       pos = s_hold.find(AB, pos + size);
       }*/
    //s_hold.find(AB)
  }

  if (a==N && b==N) {
    ans = ans + N - 1;
  }
  else {
    ans = ans + min(a, b);
  }
  cout << ans << endl;
  return 0;
}


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

int main()
{
    // 整数の入力
    long long N,stable,headB,tailA,headtailAB;
    stable = 0;
    headB = 0;
    tailA = 0;
    headtailAB = 0;
    cin >> N;
    for (int i = 0;i< N;i++){
        string s;
        cin >> s;
        for (int j = 1; j < s.size();j++){
            if (s[j] == 'B' && s[j-1] == 'A'){
                stable++;
            }
        }
        if (s[0] == 'B' && s[s.size() -1] != 'A'){
            headB++;
        }
        if (s[0] != 'B' && s[s.size() -1] == 'A'){
            tailA++;
        }
        if (s[0] == 'B' && s[s.size() -1] == 'A'){
            headtailAB++;
        }
    }
    // cout << stable << " " << headB << " " << tailA << " " << headtailAB << endl;
    if (headtailAB > 0){
        if (headB != tailA){
            cout << stable + max(headtailAB - 1LL,0LL) + min(headB,tailA) + 1 << endl;
        }else{
            cout << stable + max(headtailAB - 1LL,0LL) + min(headB,tailA) << endl;
        }
    }else{
        cout << stable + min(min(headB,tailA),N - 1LL) << endl;
    }
    return 0;
}


#include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<complex>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<utility>
using namespace std;
typedef long long ll;
typedef unsigned int ui;
const ll mod = 1000000007;
const ll INF = (ll)1000000007 * 1000000007;
typedef pair<int, int> P;
#define stop char nyaa;cin>>nyaa;
#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define Rep1(i,sta,n) for(int i=sta;i<=n;i++)
typedef long double ld;
typedef complex<ld> Point;
const ld eps = 1e-8;
const ld pi = acos(-1.0);
typedef pair<ll, ll> LP;

int h,w,n;
int x,y;
string s,t;

void solve(){
    cin >> h >> w >> n;
    cin >> y >> x;
    cin >> s >> t;
    int l=1,r=w,u=h,d=1;
    per(i,n){

        if (t[i]=='D') {
            u=min(u+1,h);
        }
        if (t[i]=='U') {
            d=max(d-1,1);
        }
        if (t[i]=='L') {
            r=min(r+1,w);
        }
        if (t[i]=='R') {
            l=max(l-1,1);
        }
        if (s[i]=='U') u-=1;
        if (s[i]=='D') d+=1;
        if (s[i]=='R') r-=1;
        if (s[i]=='L') l+=1;

        //cout << d << "," << u << " " << l << "," << r << endl;
        if (l>r or d>u){
            cout << "NO" << endl;
            return;
        }
    }

    if (l<=x && x<=r && d<=y && y<=u) cout << "YES" << endl;
    else cout << "NO" << endl;
}

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

Score : 600 points

Problem Statement

We have a rectangular grid of squares with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.
On this grid, there is a piece, which is initially placed at square (s_r,s_c).

Takahashi and Aoki will play a game, where each player has a string of length N.
Takahashi's string is S, and Aoki's string is T. S and T both consist of four kinds of letters: L, R, U and D.

The game consists of N steps. The i-th step proceeds as follows:

First, Takahashi performs a move. He either moves the piece in the direction of S_i, or does not move the piece.

Second, Aoki performs a move. He either moves the piece in the direction of T_i, or does not move the piece.

Here, to move the piece in the direction of L, R, U and D, is to move the piece from square (r,c) to square (r,c-1), (r,c+1), (r-1,c) and (r+1,c), respectively. If the destination square does not exist, the piece is removed from the grid, and the game ends, even if less than N steps are done.

Takahashi wants to remove the piece from the grid in one of the N steps.
Aoki, on the other hand, wants to finish the N steps with the piece remaining on the grid.
Determine if the piece will remain on the grid at the end of the game when both players play optimally.

Constraints

2 \leq H,W \leq 2 \times 10^5

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

1 \leq s_r \leq H

1 \leq s_c \leq W

|S|=|T|=N

S and T consists of the four kinds of letters L, R, U and D.

Input

Input is given from Standard Input in the following format:

H W N
s_r s_c
S
T

Output

If the piece will remain on the grid at the end of the game, print YES; otherwise, print NO.

Sample Input 1

2 3 3
2 2
RRL
LUD

Sample Output 1

YES

Here is one possible progress of the game:

Takahashi moves the piece right. The piece is now at (2,3).

Aoki moves the piece left. The piece is now at (2,2).

Takahashi does not move the piece. The piece remains at (2,2).

Aoki moves the piece up. The piece is now at (1,2).

Takahashi moves the piece left. The piece is now at (1,1).

Aoki does not move the piece. The piece remains at (1,1).

Sample Input 2

4 3 5
2 2
UDRRR
LLDUD

Sample Output 2

NO

Sample Input 3

5 6 11
2 1
RLDRRUDDLRL
URRDRLLDLRD

Sample Output 3

NO


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

int i,root,parent[200005],depth[200005];
vector<int> g[200005];

void dfs(int v,int p,int d){
	depth[v]=d;
	for(i=0;i<g[v].size();i++){
		if(g[v][i]==p) continue;
		dfs(g[v][i],v,d+1);
	}
}

int main (void){
	int j,n,a[200005],b[200005],ji[200005],lp;
	cin >> n;
	for(i=1;i<n;i++) {
		cin >> a[i] >> b[i];
		ji[a[i]]++;
		ji[b[i]]++;
		g[a[i]].push_back(b[i]);
		g[b[i]].push_back(a[i]);
	}
	lp=0;
	for(i=1;i<=n;i++){
		if(depth[i]>lp) lp=depth[i];
	}
	if(lp%3==1) cout << "Second" << endl;
	else cout << "First" << endl;
	return 0;
}

Score : 800 points

Problem Statement

Takahashi and Aoki will play a game on a tree.
The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.

At the beginning of the game, each vertex contains a coin.
Starting from Takahashi, he and Aoki will alternately perform the following operation:

Choose a vertex v that contains one or more coins, and remove all the coins from v.

Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.

The player who becomes unable to play, loses the game.
That is, the player who takes his turn when there is no coin remaining on the tree, loses the game.
Determine the winner of the game when both players play optimally.

Constraints

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

1 \leq a_i, b_i \leq N

a_i \neq b_i

The graph given as input is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}

Output

Print First if Takahashi will win, and print Second if Aoki will win.

Sample Input 1

3
1 2
2 3

Sample Output 1

First

Here is one possible progress of the game:

Takahashi removes the coin from Vertex 1. Now, Vertex 1 and Vertex 2 contain one coin each.

Aoki removes the coin from Vertex 2. Now, Vertex 2 contains one coin.

Takahashi removes the coin from Vertex 2. Now, there is no coin remaining on the tree.

Aoki takes his turn when there is no coin on the tree and loses.

Sample Input 2

6
1 2
2 3
2 4
4 6
5 6

Sample Output 2

Second

Sample Input 3

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

Sample Output 3

First


#include <bits/stdc++.h>

using namespace std;

const int N = 3e5 + 5, mod = 1e9 + 7;
int dp[N], sum[N];

char s[N];

int main() {
  int n, m;
  scanf("%d %d", &n, &m);
  scanf("%s", s);
  bool same = 1;
  for (int i = 0; i < m; ++i)
    if (s[i] != s[0])
      same = 0;
  if (same) {
    dp[0] = 1;
    for (int i = 1; i <= n; ++i) {
      dp[i] = dp[i-1];
      if (i > 1)
        dp[i] = (dp[i] + dp[i-2]) % mod;
    }
    int ans = (dp[n] + dp[n-2]) % mod;
    printf("%d\n", ans);
    return 0;
  }
  int cnt = 0;
  while (s[cnt] == s[0]) ++cnt;
  if ((cnt & 1) == 0)
    ++cnt;
  int cur = 0;
  for (int i = 0; i < m; ++i) {
    if (s[i] != s[0]) {
      if (cur & 1) {
        cnt = min(cnt, cur);
      }
      cur = 0;
    }
    else {
      ++cur;
    }
  }
  dp[0] = 1;
  sum[0] = 1;
  for (int i = 2; i <= n; i += 2) {
    dp[i] = sum[i-2] - (i - (cnt+3) >= 0 ? sum[i - (cnt+3)] : 0);
    dp[i] %= mod;
    if (dp[i] < 0)
      dp[i] += mod;
    sum[i] = (dp[i] + sum[i-2]) % mod;
  }
  int ans = dp[n];
  for (int i = 2; i <= n && i <= cnt+1; i += 2) {
    ans = (ans + 1LL * dp[n-i] * (i-1)) % mod;
  }
  printf("%d\n", ans);
  return 0;
}

Score : 1500 points

Problem Statement

Consider a circle whose perimeter is divided by N points into N arcs of equal length, and each of the arcs is painted red or blue. Such a circle is said to generate a string S from every point when the following condition is satisfied:

We will arbitrarily choose one of the N points on the perimeter and place a piece on it.

Then, we will perform the following move M times: move the piece clockwise or counter-clockwise to an adjacent point.

Here, whatever point we choose initially, it is always possible to move the piece so that the color of the i-th arc the piece goes along is S_i, by properly deciding the directions of the moves.

Assume that, if S_i is R, it represents red; if S_i is B, it represents blue.
Note that the directions of the moves can be decided separately for each choice of the initial point.

You are given a string S of length M consisting of R and B.
Out of the 2^N ways to paint each of the arcs red or blue in a circle whose perimeter is divided into N arcs of equal length, find the number of ways resulting in a circle that generates S from every point, modulo 10^9+7.

Note that the rotations of the same coloring are also distinguished.

Constraints

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

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

|S|=M

S_i is R or B.

Input

Input is given from Standard Input in the following format:

N M
S

Output

Print the number of ways to paint each of the arcs that satisfy the condition, modulo 10^9+7.

Sample Input 1

4 7
RBRRBRR

Sample Output 1

2

The condition is satisfied only if the arcs are alternately painted red and blue, so the answer here is 2.

Sample Input 2

3 3
BBB

Sample Output 2

4

Sample Input 3

12 10
RRRRBRRRRB

Sample Output 3

78


#include <iostream>

using namespace std;
const int MAXN = 20  + 5;
int v[MAXN] , c[MAXN];
int n;

int solve(int i)
{

if(i == n) return 0;

return max(solve(i + 1) , solve(i + 1) + v[i] - c[i]);

}

int main() {

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

cout << solve(0) ;

}

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


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

#define endl "\n"
#define all(x) x.begin(),x.end()
#define pb push_back
#define ff first
#define ss second
#define pii pair<int,int>
#define vi vector<int>
#define vc vector<char>
#define vii vector<pii>
#define vvi vector<vi>
#define fori(i,n) for(int i=1;i<=n;++i)
#define forn(i,n) for(int i=0;i<n;++i)
#define sz(x) int(x.size())
#define error(x) cout<<#x<<" "<<x<<endl
#define IOS  ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)

const int N=200*1000;
const int mod=1e9+7;

int min3(int a,int b,int c){return min(a,min(b,c));}
int max3(int a,int b,int c){return max(a,max(b,c));}
int min4(int a,int b,int c,int d){return min(min(a,b),min(c,d));}
int max4(int a,int b,int c,int d){return max(max(a,b),max(c,d));}

//#define int int64_t
//int a[N+2];
int pref[N+2]={0};
int32_t  main(){
	IOS;
  int ans=0;
  int n;cin>>n;

  string s;cin>>s;
  if(n==1){cout<<"0\n";return 0;}
  memset(pref,0,sizeof(pref));
  if(s[0]=='.')pref[0]=1;
  for(int i=1;i<n;++i){
    if(s[i]=='.')pref[i]=1+pref[i-1];
    else pref[i]=pref[i-1];
  }
  ans=n-pref[n-1];//all black cost
  for(int i=0;i<n;++i){
    //uptil ith pos white remaining black
    ans=min(ans,i+1-pref[i]+(pref[n-1]-pref[i]));
  }
  cout<<ans<<endl;

  return 0;
}

Score : 300 points

Problem Statement

There are N stones arranged in a row. Every stone is painted white or black.
A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

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

S is a string of length N consisting of . and #.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i = 0;i<((int)(n));i++)
#define reg(i,a,b) for(int i = ((int)(a));i<=((int)(b));i++)
#define irep(i,n) for(int i = ((int)(n)-1);i>=0;i--)
#define ireg(i,a,b) for(int i = ((int)(b));i>=((int)(a));i--)
typedef long long ll;

/*
5
1
2
4
-2
-5
0
*/

ll n,g;
vector<ll> p,fact,a;
set<ll> ans;

void prime_list(ll n,vector<ll>& p){
	ll visited[300010]={};
	reg(i,2,n){
		if(visited[i]==0){
			p.push_back(i);
			reg(j,2,n){
				if(j*i>n)break;
				visited[i*j]=1;
			}
		}
	}
}
void factoring(ll n,vector<ll>& v,vector<ll>& p){
	rep(i,p.size()){
		while(n%p[i]==0){
			n/=p[i];
			v.push_back(p[i]);
		}
	}
	if(n>1)v.push_back(n);//残渣が素数でないといけない。
}

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

bool division(vector<ll> v,ll p){//ここは変更するのでコピーにしないといけない
	bool ok=true;
	rep(i,v.size())v[i]%=p;
	rep(i,v.size()){
		//今回は計算量短縮のために多項式を陽に与える
		if(i+(p-1)>=v.size()-1)break;//最後は定数なので変えられない
		ll t=v[i];
		v[i]-=t;
		v[i+(p-1)]+=t;
	}
	rep(i,v.size())if(v[i]%p!=0)ok=false;
	return ok;
}

void init(){
	cin>>n;
	reg(i,0,n){
		ll b;
		cin>>b;
		a.push_back(b);
	}
	g=a[0];
	reg(i,1,n)g=gcd(g,abs(a[i]));
	prime_list(100010,p);
	factoring(g,fact,p);
	rep(i,fact.size())ans.insert(fact[i]);
	cerr<<"初期化終了"<<endl;
}

int main(void){
	init();
	rep(i,p.size()){
		if(p[i]>n)break;
		if(division(a,p[i]))ans.insert(p[i]);
	}
	for(auto itr=ans.begin();itr!=ans.end();itr++){
		cout<<*itr<<endl;
	}
	return 0;
}

Score : 800 points

Problem Statement

You are given a polynomial of degree N with integer coefficients: f(x)=a_Nx^N+a_{N-1}x^{N-1}+...+a_0. Find all prime numbers p that divide f(x) for every integer x.

Constraints

0 \leq N \leq 10^4

|a_i| \leq 10^9(0\leq i\leq N)

a_N \neq 0

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_N
:
a_0

Output

Print all prime numbers p that divide f(x) for every integer x, in ascending order.

Sample Input 1

2
7
-7
14

Sample Output 1

2
7

2 and 7 divide, for example, f(1)=14 and f(2)=28.

Sample Input 2

3
1
4
1
5

Sample Output 2

There may be no integers that satisfy the condition.

Sample Input 3

0
998244353

Sample Output 3

998244353


#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<vector>
#include<algorithm>
#include<iterator>
#include<sstream>
#include<iomanip>
#include<map>

#define rep(i, n) for (int i = 0; i < n; i++)
#define rrep(i, n) for(int i = n-1; i>=0; i--)
#define range(i, n, m) for (int i = n; i < m; i++)
#define rrange(i, n, m) for (int i = n - 1; i => m; i--)
#define MOD 1000000007
#define MAX 20000000000

typedef long long int ll;
typedef unsigned long long int ull;

using namespace std;

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

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

	ll A, B;
	cin >> A >> B;

	ll ret = 0;

	if (A == B) {
		ret = A * 2;
	}
	else {
		ll m = max(A, B);
		ret = A + (A - 1);
	}

	cout << ret << endl;

	return 0;
}

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


#include <bits/stdc++.h>
using namespace std;
int main(){
    int N,b=0;
    cin >> N;
    vector<int> Height(N);
    for(int i=0; i<N; i++){
        cin >>Height.at(i);
    }
    for(int j = 0; j < N;j++){
        bool is_candidate = true;
        for(int k = 0; k < j; k++){
            if(Height.at(k) >Height.at(j)){
                is_candidate= false;
                break;
            }

        }
        if(is_candidate) {
            b++;
        }
    }

    cout << b << endl;
}

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


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

int N;
vector<int> h;

int main() {
    cin >> N; h.resize(N);
    for (int i = 0; i < N; i++) scanf("%d", &h[i]);
    int maxi = h[0];
    int count = 1;
    for (int i = 1; i < N; i++) {
        maxi = max(maxi, h[i-1]);
        if (maxi <= h[i]) count++;
    }
    cout << count << endl;
    return 0;
}


#include <iostream>
using namespace std;

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

  bool isPrevEven = false;
  bool isChanged = false;
  int num = 0;
  int cont = 1;
  char prev = *s.begin();
  for (string::iterator i = s.begin() + 1; i != s.end(); i++) {
    if (prev != *i) {
      num += cont / 2;
      if (isPrevEven && cont == 1) {
        if (!isChanged) {
          num++;
          isChanged = true;
        }
        if (isChanged && cont == 1) {
          cout << "koko";
          num++;
          isChanged = true;
        }
      }

      if (cont % 2 == 0) {
        isPrevEven = true;
      }
      cont = 1;
      prev = *i;
    } else {
      cont++;
    }
  }
  num += cont / 2;
  cout << num;
  return 0;
}

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


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

ll psum(std::vector<ll> S, int i, int j)
{
  return S[j+1] - S[i];
}

void print(vector<int> v[2])
{
  for(int i=0; i<(int)v[0].size(); i++)
  {
    cout << v[0][i] << " ";
  }
  cout << endl;
  for(int i=0; i<(int)v[1].size(); i++)
  {
    cout << v[1][i] << " ";
  }
  cout << endl;
}

int main()
{
  int n,k;
  cin >> n >> k;
  string S;
  cin >> S;
  std::vector<int> v[2];
  std::vector<ll> ASum;
  int tmp=1,cont=0;

  for(int i=0; i<n; i++)
  {
    int s = S[i]-'0';
    if(s==tmp){
      cont++;
    } else {
      v[tmp].push_back(cont);
      tmp = s;
      cont = 1;
    }
  }
  v[tmp].push_back(cont);
  if(tmp==0) v[1].push_back(0);

  std::vector<ll> psum[2];

  int div = (int)v[0].size();
  ll tmp0=0,tmp1=0;
  for(int i=0; i<div; i++)
  {
    psum[0].push_back(tmp0);
    psum[1].push_back(tmp1);
    tmp0+=v[0][i];
    tmp1+=v[1][i];
  }
  psum[0].push_back(tmp0);
  psum[1].push_back(tmp1);
  tmp1 += v[1][div];
  psum[1].push_back(tmp1);

  ll max=0;
  for(int i=0; i+k<=div; i++)
  {
    ll tmp = psum[0][i+k]-psum[0][i];
    tmp += psum[1][i+k+1]-psum[1][i];
    if(max<tmp) max = tmp;
  }
  if(max==0) cout << n << endl;
  else cout << max << endl;
  return 0;
}

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


#include<bits/stdc++.h>
using namespace std;
int n,k,a[100010],ans=0;
int b[100010],c[100010],cnt=0;

int main()
{
	cin>>n>>k;
	b[0]=0;
	for(int i=1;i<=n;i++)
	{
		char ch;
		cin>>ch;
		if(ch=='1') a[i]=1;
		else a[i]=0;
	}
	int ch=2;
	for(int i=1;i<=n;i++)
	{
		if(a[i]!=ch) ch=a[i],c[++cnt]=ch,b[cnt]++;
		else b[cnt]++;
	}
	if(c[1]==1)
	{
		for(int j=1;j<=cnt;j+=2)
		{
			int s=0;
			for(int i=j;i<=min(j+k*2,cnt);i++) s+=b[i];
			if(c[min(j+k*2,cnt)]==0) s-=b[min(j+k*2,cnt)];
			ans=max(ans,s);
		}
	}
	else
	{
		for(int j=2;j<=cnt;j+=2)
		{
			int s=0;
			for(int i=j-2;i<=min(cnt,j+k*2-2);i++) s+=b[i];
			if(c[min(cnt,j+k*2-2)]==0) s-=b[min(cnt,j+k*2-2)];
			ans=max(ans,s);
		}
	}
	cout<<ans<<endl;
	return 0;
}


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

int main() {
  ios::sync_with_stdio(false), cin.tie(0);
  vector<int> a(5);
  cin >> a[0] >> a[1] >> a[2] >> a[3] >> a[4];
  int k;
  cin >> k;
  bool ok = true;
  for (int i = 0; i < 5; i++)
    for (int j = 0; j < 5; j++)
      if (abs(a[i] - a[j]) > k)
        ok = false;
  cout << (ok ? "Yay!" : ":(");
  return 0;
}

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


#include <iostream>
#include <time.h>
#include <string>

using namespace std;

int main()
{
	int a[5];
	int time = 0;
	int minTime = 10;
	for (int i = 0;i < 5;i++)
	{
		cin >> a[i];
	}
	for (int i = 0;i < 5;i++)
	{
		int num = a[i];
		for (;num > 10;num -= 10)
		{
		}
		if (num < minTime)
		{
			minTime = num;
		}
		time += a[i] + 10 - num;
	}
	time -= 10- minTime;
	cout << time;
		return 0;
}

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


/// Containers Start
#include <algorithm>
#include <bitset>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
/// C Header Files
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <math.h>
#include <stdio.h>
/// Containers End

using namespace std;

/// Math Start
#define PI acos(-1.0)
#define Pi 3.141592653589793
#define EPS (1e-7)
#define INF (0x3f3f3f3f)
/// Math End

/// Extra Start
#define nn '\n'
#define pb push_back
#define ull unsigned long long
#define ll long long
#define MOD 1000000007
#define sz(a) int((a).size())
#define space " "
#define All(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
/// Extra End

#define rep(i, n) for (int i = 0; i < n; i++)
#define Cini(a)                                                                \
    int a;                                                                     \
    cin >> a;
#define Cinii(a, b)                                                            \
    int a, b;                                                                  \
    cin >> a >> b;
#define Ciniii(a, b, c)                                                        \
    int a, b, c;                                                               \
    cin >> a >> b >> c;
#define Cins(s)                                                                \
    string s;                                                                  \
    cin >> s;
#define Cinss(s1, s2)                                                          \
    string s1, s2;                                                             \
    cin >> s1 >> s2;
#define Cinc(c)                                                                \
    char c;                                                                    \
    cin >> c;
/// Functions End

/// Debug Start
#define deb(x) cout << #x << ": " << x << endl
#define deb2(x, y) cout << #x << ": " << x << '\t' << #y << ": " << y << endl;
#define deb3(x, y, z)                                                          \
    cout << #x << ": " << x << '\t' << #y << ": " << y << '\t' << #z << ": "   \
         << z << endl;
/// Debug End

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

/**>>>>>>>>>>>>>>>>>>> END <<<<<<<<<<<<<<<<<<**/

/// template

bool _mysort(int a, int b) { return a % 10 > b % 10; }

signed main(void) {
    cin.sync_with_stdio(false);
    cin.tie(0);
    vector<int> a, b;
    rep(i, 5) {
        Cini(p);
        if (p % 10 == 0) {
            a.push_back(p);
        } else {
            b.push_back(p);
        }
    };
    int ans = 0;
    for (auto i : a)
        ans += i;
    sort(All(b), _mysort);
    ans += b.back();
    if (b.size() > 0) {
        b.erase(--b.end());
    }
    for (auto i : b)
        ans += (i + 10 - 1) / 10 * 10;
    cout << ans << nn;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main()
{
    int x, y, z, k;
    cin >> x >> y >> z >> k;
    vector<ll> a(x);
    vector<ll> b(y);
    vector<ll> c(z);
    for(int i = 0; i < x; i++)
    {
        cin >> a[i];
    }
    for(int i = 0; i < y; i++)
    {
        cin >> b[i];
    }
    for(int i = 0; i < z; i++)
    {
        cin >> c[i];
    }

    vector<ll> absum(x*y);
    for(int i = 0; i < x; i++)
    {
        for(int j = 0; j < y; j++)
        {
            absum[i*y + j] = a[i] + b[j];
        }
    }
    sort(absum.begin(), absum.end());
    reverse(absum.begin(), absum.end());

    int m = min(int(absum.size()), k);
    vector<ll> abc(m*z);
    for(int i = 0; i < m; i++)
    {
        for(int j = 0; j < z; j++)
        {
            abc[i*z + j] = absum[i] + c[j];
        }
    }
    sort(abc.begin(), abc.end());
    reverse(abc.begin(), abc.end());

    for(int i = 0; i < k; i++)
    {
        cout << abc[i] << endl;
    }
}

Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

Note that the input or output may not fit into a 32-bit integer type.


#include <bits/stdc++.h>
using namespace std;
#define inf 999999999
#define loop(i, a, b) for (int i = (a), i##len = (b); i < i##len; ++i)
#define rep(i, n) loop(i, 0, n)
#define lin long long
#define lfl long double

lin x[3], a[3][1000], k, mn[3];
unordered_set<lin> cleared;

int main(void)
{
    rep(i,3)
    {
        cin >> x[i];
        mn[i] = x[i] - 1;
    }
    cin >> k;
    rep(i,3)
    {
        rep(j,x[i])
        {
            cin >> a[i][j];
        }
    }

    rep(i,3)
    {
        sort(a[i], a[i] + x[i]);
    }

    rep(i, k)
    {
        lin res = 0;
        lin ans[3];
        lin hss;

        for(lin aa = mn[0]; aa < x[0]; aa++)
        {
            for(lin bb = mn[1]; bb < x[1]; bb++)
            {
                for(lin cc = mn[2]; cc < x[2]; cc++)
                {
                    lin hs = aa * 1024 * 1024 + bb * 1024 + cc;
                    auto it = cleared.find(hs);
                    if(it != cleared.end())
                        continue;

                    lin cdd = a[0][aa] + a[1][bb] + a[2][cc];
                    if(cdd > res)
                    {
                        res = cdd;
                        ans[0] = aa;
                        ans[1] = bb;
                        ans[2] = cc;
                        hss = hs;
                    }
                }

            }
        }

        cout << res << endl;
        rep(i,3)
        {
            mn[i] = min(mn[i] - 1, ans[i]);
            if(mn[i] < 0)
                mn[i] = 0;
        }
        cleared.emplace(hss);
    }

    return 0;
}


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

using namespace std;

int main(){
	int N,Q;
	cin>>N>>Q;
	int flag[N+2],flag_new[N+2];
	for(int i=0;i<N+2;i++){flag_new[i]=1.0;}
	string s;
	cin>>s;
	string t,d;

	int dir;
	for(int i=0;i<Q;i++){
		flag_new[0]=0.0;
		flag_new[N+1]=0.0;
		for(int k=0;k<N+2;k++){flag[k]=flag_new[k];}
		cin>>t>>d;
		if(d[0]=='L'){
			dir=-1;
		}else{
			dir=1;
		}
		for(int k=0;k<N;k++){
			if(s[k]==t[0]){
				flag_new[k+1+dir]+=flag[k+1];
				flag_new[k+1]-=flag[k+1];
			}
		}

	}
	int sur=0;
	for(int i=1;i<=N;i++){
		sur+=flag_new[i];
	}
	cout<<sur<<endl;

	return 0;

}

Score : 100 points

Problem Statement

You are given three integers A, B and C.

Determine if there exists an equilateral triangle whose sides have lengths A, B and C.

Constraints

All values in input are integers.

1 \leq A,B,C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

If there exists an equilateral triangle whose sides have lengths A, B and C, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

There exists an equilateral triangle whose sides have lengths 2, 2 and 2.

Sample Input 2

3 4 5

Sample Output 2

No

There is no equilateral triangle whose sides have lengths 3, 4 and 5.


#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back

using namespace std;
const long long MOD = (long long)1e9 + 7;

char c;

int main()
{
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> c;
    switch (c) {
        case 'A': c = 'T';break;
        case 'T': c = 'A';break;
        case 'C': c = 'G';break;
        case 'G': c = 'C';
    }
    cout << c << "\n";
	//system("pause");
	return 0;
}

Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


#include <bits/stdc++.h>

using namespace std;

int main() {
  string s;
  cin >> s;
  int ans = 0, cnt = 0;
  for (int i = 0; i < s.size(); i++) {
    if (s[i] == 'A')
      cnt++;
    else if (s[i] == 'T')
      cnt++;
    else if (s[i] == 'C')
      cnt++;
    else if (s[i] == 'G')
      cnt++;
    else
      cnt = 0;
    ans = max(ans, cnt);
  }
  cout << ans << endl;

  return 0;
}

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

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

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


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

bool pd(char A) {
    if(A=='A' || A=='T' || A=='C' || A=='G') return true;
    return false;
}
int p[15];
int main() {
    string s;
    memset(p,0,sizeof(p));
    cin>>s;
    int ans=0,in=0;
    if(pd(s[0])) p[0]=1;
    if(p[0] > ans) ans=p[0];
    for(int i=1;i<s.size();i++) {
        if(pd(s[i])) {
            p[i]=p[i-1]+1;
            if(p[i] > ans) ans = p[i];
        }
    }
    cout<<ans<<endl;
}


#include <bits/stdc++.h>
#define repz(i, z, n) for (decltype(n) i = (z); i < (n); i++)
#define rep(i, n) for (decltype(n) i = 0; i < (n); i++)

#define REPZ(i, z, n) for (decltype(n) i = (z); i <= (n); i++)
#define REP(i, n) for (decltype(n) i = 0; i <= (n); i++)
#define ALL(v) v.begin(), v.end()
#define SIZE(v) ((ll)(v).size())
#define MAX(v) (*max_element(ALL(v)))
#define MIN(v) (*min_element(ALL(v)))
#define INF 1000000000000  // 1E+12

// 略
#define PB push_back
#define F first
#define S second
#define MP make_pair
#define READ cin >>
#define PRINT cout <<
#define PYES cout << "YES" << endl
#define pyes cout << "Yes" << endl
#define POK cout << "OK" << endl
#define PNO cout << "NO" << endl
#define pno cout << "No" << endl
#define PNG cout << "NG" << endl
#define ret return 0

using namespace std;

// デバッグ用
void debug_out() { cout << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
  cout << H << " ";
  debug_out(T...);
}

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

#ifdef _DEBUG
#define debug(...) debug_out(__VA_ARGS__)
#else
#define debug(...)
#endif

// typedef
typedef long long ll;
typedef unsigned long long ul;
typedef long double ld;
typedef pair<ll, ll> pl;

// const
// 円周率
const ld pi = acos(-1);
// mod用
// 1E+9 +7
const ll mod = (int)1e+9 + 7;
// 1s間で可能なループ回数2E+8回
// int        最大値2147483647         〜2E+9
// long long  最大値9223372036854775807〜9E+18
// 総和accumulate
// 単純リストvector<type> push_back
// 連想配列map<key,value> insert,
// 集合set<type>
// pair キーとバリューを格納 firstとsecondでアクセス
// 小数点指定 cout << fixed << setprecision(15) << endl;
// to_string<->stoi
// stoll(longlong)
// stod(double)
// deep copy v1->v2 copy(v1.begin(), v1.end(), back_inserter(v2) );
// 大文字65-90(-32)
// 小文字97-122(+32)
//  priority_queue<pair<ll, ll>, vector<pair<ll, ll>>, greater<pair<ll, ll>>>
//  ba;
signed main() {
  // faster
  // C言語流の入出力は使用できない
  ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  int n;
  int q;
  cin >> n >> q;
  string s;
  cin >> s;
  vector<int> dp(SIZE(s), 0);
  bool flag = false;
  repz(i, 1, SIZE(s)) { dp[i] = dp[i - 1] + (s[i - 1] == 'A' and s[i] == 'C'); }
  rep(i, q) {
    int l, r;
    cin >> l >> r;
    l--;
    r--;
    cout << dp[r] - dp[l] << endl;
  }
  ret;
}

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


//include
//------------------------------------------
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include<queue>
using namespace std;
//conversion
//------------------------------------------
inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}
//math
//-------------------------------------------
template<class T> inline T sqr(T x) {return x*x;}
//typedef
//------------------------------------------
typedef long long ll;
typedef long long LL;
typedef vector<long long > VLL;
typedef vector<long long > vll;
typedef pair<long long , long long> pll;
typedef pair<long long , long long> PLL;

//container util
//------------------------------------------
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define VECMAX(x) *max_element(ALL(x))
#define VECMIN(x) *min_element(ALL(x))
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())
//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)
#define MULTIPLE(i,n,k) for(int i = (k) ; i<(n) ; i+=k+1)//倍数ループ
//constant
//------------------------------------------
const double EPS = 1e-10;
const double PI  = acos(-1.0);
//clear memory
#define CLR(a) memset((a), 0 ,sizeof(a))
//debug
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
#define SIZEOF(x) sizeof(x)/sizeof(x[0])

const long long INF = 100000000000000;
const long long NINF = -100000000000000;

//----------------search for specific figure--------------------
//--------------------------------------------------------------

ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
ll nCr(ll n, ll r) {

	if (n == 0) { return 0; }
	if (r == 0) { return 1; }
	if (r == 1) { return n; }
	if (n == r) { return 1; }

	if (r > n / 2) { r = n / 2; }

	ll result = 1;
	for (ll i = 1; i <= r; i++) {
		result *= (n - i + 1) / i;
    }
	return(result);
}

//firstが最大値（最小値） , second が index
pair<LL , LL> maxP(vll a , ll size){
    pair <ll , ll> p;
    vll::iterator iter = max_element(a.begin() , a.end());
    p.first = *iter;
    p.second = distance(a.begin() , iter);
    return p;
}

pair<LL , LL> minP(vll a , ll size){
    pair <ll , ll> p;
    vll::iterator iter = min_element(a.begin() , a.end());
    p.first = *iter;
    p.second = distance(a.begin() , iter);
    return p;
}

ll sumL(vll a , ll size){
    ll sum = 0;
    REP(i,size){
        sum += a[i];

    }
    return sum;
}

 //aのなかにtがいくつあるか
ll counT(VLL a , ll t ){

    sort(a.begin(),a.end());
    return upper_bound(a.begin(),a.end(),t)-lower_bound(a.begin() , a.end() , t);
}

#define COUNT(a,b) counT((a),(b))
#define MAX(x) maxP(x,x.size())
#define MIN(x) minP(x,x.size())
#define SUM(x) sumL(x,x.size())

//-------------------DIVIDE----------------------
// DIV[i][j] は　i の j分割数 j == 0 && i != 0 なら 0
//並び順を区別しない

ll DIV[1000+1][1000+1];
void divide(ll n ,ll m){
    DIV[0][0]= 1;
    FOR(i,1,n+1){
        DIV[i][0] = 0;
    }
    REP(i,n+1){
        DIV[i][1] = 1;
    }
    FOR(i,1,m+1){
        FOR(t,0,n+1){
            if(DIV[t][i] > 0)continue;
            if(t>=i){
                DIV[t][i]=DIV[t-i][i] + DIV[t][i-1];
            }else{
                DIV[t][i] = DIV[t][i-1];
            }
        }
    }
}
#define DIVIDE(a,b) (DIV[a][b] - DIV[a][(b)-1])

//-------要素を見つける-----------

ll search(vll &a , ll n ){//a内のnのindexを返す
    std::vector<ll>::iterator iter = std::find(a.begin(), a.end(), n);
    size_t index = distance(a.begin(), iter);
    return index;
}

//------------素数判定-----------------

//------------素数判定-----------------
vector<bool> IS_PRIME_CONTAINER(1000005 , true);
//メモリを圧迫する可能性あり

void IsPrime_Contain(ll num){
    IS_PRIME_CONTAINER[0] = false;
    IS_PRIME_CONTAINER[1] = false;
    FOR(i,2,sqrt(num)+1){
        if(IS_PRIME_CONTAINER[i]){
            FOR(j,2,num/i + 1){
                if(j*i<=num){
                    IS_PRIME_CONTAINER[i*j]=false;
                }
            }
        }
    }
}

inline bool IsPrime(ll num){
    return IS_PRIME_CONTAINER[num];
}

//---------ベルマンフォード----------
struct E{
    ll from , to, cost;
};
ll DIST[100005];
//start と 辺の数 m 辺の情報 x を入力
void shortest(LL s , vector<E> &x , ll m){
    REP(i,100000){
        DIST[i] = INF;
    }
    DIST[s] = 0;
    while(1){
        bool t = false;
        REP(i,m){
            E h = x[i];
            if(DIST[h.from] != INF && DIST[h.to] > DIST[h.from] + h.cost){
                DIST[h.to] = DIST[h.from] + h.cost;
                t = true;
            }
        }
        if(!t){
            break;
        }
    }
}

//----UnionFind-----

class UnionFind{
    public:
    vll par;
    vll rank;//rankが高いほど上の親である
    UnionFind(LL N):par(N),rank(N){
        REP(i,N)par[i] = i;
        REP(i,N)rank[i] = 0;
    }
    ~UnionFind(){}
    LL root(LL x){
        if(par[x] ==x)return x;
        else {
            par[x] = root(par[x]);
            return par[x];
        }
    }
    void unite(LL x, LL y){
        LL rx = root(x);
        LL ry = root(y);
        if(rx == ry)return;
        if(rank[rx] < rank[ry]){
            par[rx] = ry;//rankの高い方を親にする
        }else{
            par[ry] = rx;
            if(rank[rx] == rank[ry]){
                //rankがどちらも同じ時、どちらか好きな方を親にしてそのrankを1上げる
                rank[rx]++;
            }
        }

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

//--------BFS---------

class BFS_shortestDistance{
    public:
    BFS_shortestDistance(vector<vector <char> > p_ , ll h_ , ll w_){
        p = p_;
        h=h_;
        w=w_;
        initial_number = h*w*2;
        REP(i,h){
            vector <LL> k(w);
            REP(t,w)k[t] =  initial_number;
            field.push_back(k);
        }
    }
    vector<vector <char> > p;

    ll h;
    ll w;
    ll initial_number;//初期化用数値

    vector< vector<LL> >field;  //この変数に書き込む

    pair<LL , LL > plus(pair<LL , LL> &a, pair<LL , LL > &b){
        pair<LL , LL> p;
        p.first = a.first + b.first;
        p.second = a.second + b.second;
        return p;
    }
    bool equal(pair<LL , LL> &a, pair<LL , LL > &b){
        return (a.first == b.first && a.second == b.second);
    }
    bool is_in_field(int h, int w, const pair<LL , LL> &point)
    {
        const int c = point.second;
        const int r = point.first;
        return (0 <= c && c < w) && (0 <= r && r < h);
    }

    // fieldの中身を初期化
    //最短距離がh*w*2になることはないのでこれで初期化する
    void init(){
        REP(i,field.size()){
            REP(t,field[i].size()){
                field[i][t] = initial_number;
            }
        }
    }

    // sy , sx はスタート位置の 『INDEX』!!
    // syが縦　sx が横
    void shortest(ll sy,ll sx){
        //初期化
        init();

        pair <LL , LL> c[4];
        c[0].first = 0;
        c[0].second = 1;
        c[1].first = 0;
        c[1].second = -1;
        c[2].first = 1;
        c[2].second = 0;
        c[3].first = -1;
        c[3].second = 0;
        queue <pair<LL ,LL> >Q;
        pair<LL , LL> s;
        s.first = sy;
        s.second = sx;
        field[sy][sx] = 0;//スタート位置のみ0で初期化

        Q.push(s);
        while(Q.empty() == false){
            pair <LL , LL> now = Q.front();
            Q.pop();

            for(int u = 0; u < 4 ; u++){
                pair<LL , LL > x = c[u];
                pair<LL , LL> next = plus(now , x);
                if(is_in_field(h,w,next)){
                    if(p[next.first][next.second] == '.'){
                        //まだ到達してない　＝＝　field の値が initial_number
                        if(field[next.first][next.second] == initial_number){
                            field[next.first][next.second] = field[now.first][now.second] + 1;
                            Q.push(next);
                        }else{
                            //すでに到達済みである＝＝これ以前にQueueから出てきたpairがすでに
                            //到達している＝＝すでにfieldの値が最小値であることは明らか;
                        }
                    }
                }
            }
        }
    }

};

//-----------DP---------------//

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

//-----------MODつきCombination------------//
const int MAX = 1000007;
const int MOD = 1000000007;

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

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

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

//-------------bit全探索---------------

//aは空の二重配列
//aに格納する
void BIT(vector<vll> &a , ll n){
    for(ll bit = 0; bit < (1<<n) ; bit++){
        vll P;
        a.push_back(P);
        for(ll i = 0 ; i < n ; i++){
            if(bit & (1<<i)){
                a[bit].push_back(i);
            }
        }
    }
}

//-----------MAIN------------//

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

    vll a(q) , b(q);
    REP(i,q){
        cin >>a[i] >> b[i];
    }
    vll p(n);
    ll j = 0;
    REP(i,s.size()){
        if(i>0){
            if(s[i-1]=='A' && s[i] == 'C')j++;
        }
        p[i] = j;
        //debug(p[i])
    }

    REP(i,q){
        if(b[i]-a[i]>=2)
        cout << p[b[i]-1] - p[a[i]-1] << endl;
        else cout << 0 << endl;
    }

    return 0;
    }


#include<iostream>
#include<string>

using namespace std;

int main(){
  int n,q;
  string s;
  int l[100000];
  int r[100000];
  cin >> n >> q;
  cin >> s;
  for(int i = 0; i < q ; i++){
    cin >> l[i] >> r[i];
    l[i]--;
    r[i]--;
  }
  int ans[100000] = {0};
  for(int i = 1; i < n; i++){
    if(s[i-1] == 'A' && s[i] == 'C'){
      ans[i] = ans[i-1] + 1;
    }
    else ans[i] = ans[i-1];
  }
  for(int i = 0; i < q; i++){
    cout << ans[r[i]] - ans[l[i]] << endl;
  }
}


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

int main() {
  int N, Q; cin >> N >> Q;
  string S; cin >> S;

  vector<int> sum(N + 1, 0);

  vector<int> l(Q), r(Q);
  for (int i = 0; i < Q; ++i) {
    cin >> l[i] >> r[i];
  }

  // 累積和
  for (int i = 1; i < N; ++i) {
    if (S[i - 1] == 'A' && S[i] == 'C') {
      sum[i + 1] = sum[i] + 1;
    }
    else sum [i + 1] = sum[i];
  }

  for (int i = 0; i < Q; ++i) {
    int ans = sum[r[i]] - sum[l[i]];
    cout << ans << endl;
  }
}