#include <bits/stdc++.h>
using namespace std;
#define N 210
#define pb push_back
vector<int> v[N];
int a[N],b[N],vis[N];
int s[10000010];
inline int read() {
    int x=0;
    char ch=getchar();
    while (!isdigit(ch)) ch=getchar();
    while (isdigit(ch)) x=x*10+ch-'0',ch=getchar();
    return x;
}
inline int P(int x) {
    if (x<2) return false;
    for (int i=2;i<=sqrt(x);i++)
        if (x%i==0) return false;
    return true;
}
int mat[N];
inline int dfs(int x) {
    for (auto y:v[x]) {
        if (vis[y]) continue;
        if (!mat[y] || dfs(mat[y])) return mat[y]=x,1;
    }
    return false;
}
int main() {
    int n=read(),Max=0,cnta=0,cntb=0,ans=0,res=0;
    for (int i=1;i<=n;i++) s[Max=max(Max,read())]^=1;
    for (int i=1;i<=Max+1;i++) if (s[i]!=s[i-1])
        ((i&1)?(a[++cnta]):(b[++cntb]))=i;
    // cout<<cnta<<endl;
    // cout<<cntb<<endl;
    for (int i=1;i<=cnta;i++)
        for (int j=1;j<=cntb;j++) if (P(abs(a[i]-b[j]))) v[i].pb(j);
    for (int i=1;i<=cnta;i++) {
        for (int j=1;j<=cntb;j++) vis[j]=0; ans+=dfs(i);
    }
    // cout<<ans<<endl;
    res+=(cnta-ans)/2*2;
    res+=(cntb-ans)/2*2;
    res+=ans+((cnta-ans)&1)*3;
    cout<<res<<endl;
    return 0;
}

Score : 1200 points

Problem Statement

There are infinitely many cards, numbered 1, 2, 3, ...
Initially, Cards x_1, x_2, ..., x_N are face up, and the others are face down.

Snuke can perform the following operation repeatedly:

Select a prime p greater than or equal to 3. Then, select p consecutive cards and flip all of them.

Snuke's objective is to have all the cards face down.
Find the minimum number of operations required to achieve the objective.

Constraints

1 ≤ N ≤ 100

1 ≤ x_1 < x_2 < ... < x_N ≤ 10^7

Input

Input is given from Standard Input in the following format:

N
x_1 x_2 ... x_N

Output

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

Sample Input 1

2
4 5

Sample Output 1

2

Below is one way to achieve the objective in two operations:

Select p = 5 and flip Cards 1, 2, 3, 4 and 5.

Select p = 3 and flip Cards 1, 2 and 3.

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

3

Below is one way to achieve the objective in three operations:

Select p = 3 and flip Cards 1, 2 and 3.

Select p = 3 and flip Cards 4, 5 and 6.

Select p = 3 and flip Cards 7, 8 and 9.

Sample Input 3

2
1 10000000

Sample Output 3

4


#include<iostream>
#include<vector>
#include<algorithm>
#include<iomanip>

#define PI 3.141592653589793238
#define INF 1050000000

using namespace std;

//cout << fixed << setprecision(15) << << endl;
//cout << << endl;

int main() {

	int N;

	cin >> N;

  	char a = N%10+'0';
  	char b = ((N-a)/10)%10+'0';
  	char c = (N-a-10*b)/100+'0';

  	string ans="ABC";

  	ans+=a;
 	 ans+=b;
 	 ans+=c;

	cout << ans <<endl;

	return 0;
}

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

Score : 100 points

Problem Statement

This contest, AtCoder Beginner Contest, is abbreviated as ABC.

When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC.

What is the abbreviation for the N-th round of ABC? Write a program to output the answer.

Constraints

100 ≤ N ≤ 999

Input

Input is given from Standard Input in the following format:

N

Output

Print the abbreviation for the N-th round of ABC.

Sample Input 1

100

Sample Output 1

ABC100

The 100th round of ABC is ABC100.

Sample Input 2

425

Sample Output 2

ABC425

Sample Input 3

999

Sample Output 3

ABC999

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 <cstring>
#include <cstdio>
int fa[200005], val[200005], nxt[200005], ban;
int lst[200005], to[200005], pre[200005], tot;
bool vis[200005];
inline void add_edge(int u, int v)
{
	to[tot] = v;
	pre[tot] = lst[u];
	lst[u] = tot++;
}
int getfa(int u)
{
	if (u == fa[u])
		return u;
	return fa[u] = getfa(fa[u]);
}
void dfs(int u)
{
	if (u == ban || lst[u] == -1)
		return;
	for (int i = lst[u]; ~i; i = pre[i])
		dfs(to[i]);
	for (int i = lst[u]; ~i; i = pre[i])
		vis[val[to[i]]] = true;
	for (val[u] = 0; vis[val[u]]; val[u]++);
	for (int i = lst[u]; ~i; i = pre[i])
		vis[val[to[i]]] = false;
}
int main()
{
	// freopen("ARC079-F.in", "r", stdin);
	memset(lst, -1, sizeof(lst));
	int n, rt;
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
		fa[i] = i;
	for (int i = 0; i < n; i++)
	{
		scanf("%d", nxt + i);
		nxt[i]--;
		if (getfa(i) == getfa(nxt[i]))
			rt = i;
		else
		{
			fa[getfa(i)] = getfa(nxt[i]);
			add_edge(nxt[i], i);
		}
	}
	ban = -1;
	dfs(rt);
	if (val[rt] == val[nxt[rt]])
	{
		ban = nxt[rt];
		val[nxt[rt]]++;
		dfs(rt);
		if (val[rt] != val[nxt[rt]] - 1)
		{
			puts("IMPOSSIBLE");
			return 0;
		}
	}
	puts("POSSIBLE");
	return 0;
}

Score : 800 points

Problem Statement

There is a directed graph with N vertices and N edges. The vertices are numbered 1, 2, ..., N.

The graph has the following N edges: (p_1, 1), (p_2, 2), ..., (p_N, N), and the graph is weakly connected. Here, an edge from Vertex u to Vertex v is denoted by (u, v), and a weakly connected graph is a graph which would be connected if each edge was bidirectional.

We would like to assign a value to each of the vertices in this graph so that the following conditions are satisfied. Here, a_i is the value assigned to Vertex i.

Each a_i is a non-negative integer.

For each edge (i, j), a_i \neq a_j holds.

For each i and each integer x(0 ≤ x < a_i), there exists a vertex j such that the edge (i, j) exists and x = a_j holds.

Determine whether there exists such an assignment.

Constraints

2 ≤ N ≤ 200 000

1 ≤ p_i ≤ N

p_i \neq i

The graph is weakly connected.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

If the assignment is possible, print POSSIBLE; otherwise, print IMPOSSIBLE.

Sample Input 1

4
2 3 4 1

Sample Output 1

POSSIBLE

The assignment is possible: {a_i} = {0, 1, 0, 1} or {a_i} = {1, 0, 1, 0}.

Sample Input 2

3
2 3 1

Sample Output 2

IMPOSSIBLE

Sample Input 3

4
2 3 1 1

Sample Output 3

POSSIBLE

The assignment is possible: {a_i} = {2, 0, 1, 0}.

Sample Input 4

6
4 5 6 5 6 4

Sample Output 4

IMPOSSIBLE


/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author
 */

#ifndef MAJK_LIB
#define MAJK_LIB

#include <vector>
#include <stack>
#include <iostream>
#include <unordered_map>
#include <map>
#include <iomanip>
#include <set>
#include <functional>
#include <fstream>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <string>
#include <sstream>
#include <queue>
#include <bitset>
using namespace std;

#define x first
#define y second
constexpr int MOD = 1000000007;

typedef std::pair<int,int> pii;
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int ui;

template<typename T, typename F> T foo(T t, T g, F f) {
	return t;
}

template <typename T, typename U> std::istream&operator>>(std::istream&i, pair<T,U>&p) {i >> p.x >> p.y; return i;}
template<typename T>std::istream&operator>>(std::istream&i,vector<T>&t) {for(auto&v:t){i>>v;}return i;}
template<typename T>std::ostream&operator<<(std::ostream&o,const vector<T>&t) {for(size_t i=0;i<t.size();++i){o<<t[i]<<" \n"[i == t.size()-1];}return o;}
template<typename T> using minheap = priority_queue<T, vector<T>, greater<T>>;
template<typename T> using maxheap = priority_queue<T, vector<T>, less<T>>;
auto fraclt = [](const pii&a,const pii&b) { return (ll)a.x * b.y < (ll)b.x * a.y; };
struct cmpfrac { bool operator()(const pii&a,const pii&b)const { return (ll)a.x * b.y < (ll)b.x * a.y; }};
template <typename T> bool in(T a, T b, T c) { return a <= b && b < c; }
int logceil(ll x) {int b=0;while(x){x>>=1;++b;}return b;}

namespace std {
    template<typename T,typename U>struct hash<pair<T,U>>{hash<T>t;hash<U>u;size_t operator()(const pair<T,U>&p)const{return t(p.x)^(u(p.y)<<7);}};
}
template<typename T,typename F>T bsh(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){l=m+1;r=m;}else{h=m-1;}}return r;}
template<typename T,typename F>T bsl(T l,T h,const F&f){T r=-1,m;while(l<=h){m=(l+h)/2;if(f(m)){h=m-1;r=m;}else{l=m+1;}}return r;}
template<typename T> T gcd(T a,T b) { if (a<b) swap(a,b); return b?gcd(b,a%b):a; }

template<typename T>class vector2:public vector<vector<T>>{public:vector2(){} vector2(size_t a,size_t b,T t=T()):vector<vector<T>>(a,vector<T>(b,t)){}};
template<typename T>class vector3:public vector<vector<vector<T>>>{public:vector3(){} vector3(size_t a,size_t b,size_t c,T t=T()):vector<vector<vector<T>>>(a,vector<vector<T>>(b,vector<T>(c,t))){}};
template <typename T> struct bounded_priority_queue {
	inline bounded_priority_queue(ui X) : A(X), B(0) {}
	inline void push(ui L, T V) { B = max(B, L); A[L].push(V); }
	inline const T &top() const { return A[B].front(); }
	inline void pop() { A[B].pop(); while (B > 0 && A[B].empty()) --B; }
	inline bool empty() const { return A[B].empty(); }
	inline void clear() { B = 0; for (auto &a: A) a = queue<T>(); }
private:
	vector<queue<T>> A; ui B;
};

#endif
// #include "../l/mod.h"

class F {
public:
	int mex(vector<int> &V) {
		sort(V.begin(), V.end());
		if (V.empty()) return 0;
		int w = 0;
		for (int v: V) {
			if (v > w) return w;
			++w;
		}
		return V.back() + 1;
	}

	void run(vector<vector<int>> &U, vector<int> &C) {
		stack<int> Q;
		for (int i = 0; i < N; ++i) {
			if (C[i] == 0) Q.push(i);
		}

		while (!Q.empty()) {
			int x = Q.top(); Q.pop();
			int val = mex(U[x]);
			A[x] = val;
			if (--C[P[x]] == 0) {
				Q.push(P[x]);
			}
			U[P[x]].push_back(val);
		}
	}

	int N;
	vector<int> A, P;
	vector<vector<int>> E;

    void solve(istream& cin, ostream& cout) {
		cin >> N;
		P.resize(N); A.resize(N);
		E.resize(N); E.clear();
		vector<int> C(N);
		for (int i = 0; i < N; ++i) {
			int p; cin >> p; --p;
			E[p].push_back(i);
			P[i] = p;
			C[p]++;
		}

		vector<vector<int>> U(N);
		run(U, C);
		int q = 0;
		while (C[q] == 0) ++q;
		int val = mex(U[q]);
		//cerr << "Using q " << q << ' ' << val << endl;

		auto CC = C;
		auto UU = U;
		CC[P[q]]--;
		UU[P[q]].push_back(val);
		run(UU, CC);
		if (A[q] == val) {
		//	cerr << "A " << A;
			cout << "POSSIBLE\n" << endl;
			return;
		}

		auto UUU = U[q];
		UUU.push_back(val);
		val = mex(UUU);
		UU = U;
		CC = C;
		CC[P[q]]--;
		UU[P[q]].push_back(val);
		run(UU, CC);
		if (A[q] == val) {
		//	cerr << "B " << A;
			cout << "POSSIBLE\n" << endl;
			return;
		}

		cout << "IMPOSSIBLE\n";
    }
};

int main() {
	ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
	F solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
	return 0;
}


#include<bits/stdc++.h>

#define INF 1000010000
#define nl '\n'
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define fi first
#define se second
#define pii pair<int,int>
#define pdd pair<double,double>
#define all(c) (c).begin(), (c).end()
#define SORT(c) sort(all(c))
#define sz(c) (c).size()
#define rep(i,n) for( int i = 0; i < n; ++i )
#define repi(i,n) for( int i = 1 ; i <= n; ++i )
#define repn(i,n) for( int i = n - 1 ; i >= 0 ; --i )
#define repf(j,i,n) for( int j = i ; j < n ; ++j )
#define die(s) {std::cout << s << nl;}
#define dier(s) {std::cout << s; return 0;}
#define vi vector<int>
typedef long long ll;

using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.precision(0);

	vi d;

	rep(kk , 9){
		int l = 0 , r = 9;
		while(r - l > 1){
			int mid = (r + l) / 2;
			cout << flush << "? ";
			rep(i , 12){
				cout << (i < sz(d) ? d[i] : (i == sz(d) ? mid : 9));
			}
			cout << nl << flush;
			string ans;
			cin >> ans;
			if(ans == "Y"){
				r = mid;
			}else{
				l = mid;
			}
		}
		d.pb(r);
		if(kk == 8)break;
		cout << flush << "? ";
		for(int e : d)cout << e;
		cout << "0" << nl << flush;
		string ans;
		cin >> ans;
		bool ck1 = ans == "Y";
		cout << flush << "? ";
		for(int e : d)cout << e;
		cout << "9" << nl << flush;
		cin >> ans;
		bool ck2 = ans == "Y";
		if((ck1 || ck2) == 0)break;
	}
	cout << flush << "! ";
	for(int e : d)cout << e;

	return 0;
}

Score : 300 points

Problem Statement

Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.

They will share these cards.
First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards.
Here, both Snuke and Raccoon have to take at least one card.

Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively.
They would like to minimize |x-y|.
Find the minimum possible value of |x-y|.

Constraints

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

-10^{9} \leq a_i \leq 10^{9}

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{N}

Output

Print the answer.

Sample Input 1

6
1 2 3 4 5 6

Sample Output 1

1

If Snuke takes four cards from the top, and Raccoon takes the remaining two cards, x=10, y=11, and thus |x-y|=1. This is the minimum possible value.

Sample Input 2

2
10 -10

Sample Output 2

20

Snuke can only take one card from the top, and Raccoon can only take the remaining one card. In this case, x=10, y=-10, and thus |x-y|=20.


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

ll a[N];
ll s;
int n;

int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%lld",&a[i]);
		s+=a[i];
	}
	ll ans=1e18;
	ll s0=0;
	for(int i=1;i<n;i++){
		s0+=a[i];
		ans=min(ans,abs(s-s0-s0));
	}
	cout<<ans<<endl;
	return 0;
}


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

long long pow(long long a, long long n) {
    long long res = 1;
    while (n > 0) {
        if (n & 1) res = res*a;
        a = a*a;
        n >>= 1;
    }
    return res;
}

int main() {
  int n,p,o = 0,d = 0;
  ll ans = 1;
  cin >> n >> p;
  rep(i,n){
    int a;
    cin >> a;
    if(a%2 == 0) d++;
    else o++;
  }
  if(d != 0) ans *= pow(2,d);
  if(p == 0){
    if(o > 1) ans *= pow(2,o-1);
  }
  else{
    if(o == 0) ans *= 0;
    else ans *= pow(2,o-1);
  }
  cout << ans << endl;
}

Score : 200 points

Problem Statement

There are N bags of biscuits. The i-th bag contains A_i biscuits.

Takaki will select some of these bags and eat all of the biscuits inside.
Here, it is also possible to select all or none of the bags.

He would like to select bags so that the total number of biscuits inside is congruent to P modulo 2.
How many such ways to select bags there are?

Constraints

1 \leq N \leq 50

P = 0 or 1

1 \leq A_i \leq 100

Input

Input is given from Standard Input in the following format:

N P
A_1 A_2 ... A_N

Output

Print the number of ways to select bags so that the total number of biscuits inside is congruent to P modulo 2.

Sample Input 1

2 0
1 3

Sample Output 1

2

There are two ways to select bags so that the total number of biscuits inside is congruent to 0 modulo 2:

Select neither bag. The total number of biscuits is 0.

Select both bags. The total number of biscuits is 4.

Sample Input 2

1 1
50

Sample Output 2

0

Sample Input 3

3 0
1 1 1

Sample Output 3

4

Two bags are distinguished even if they contain the same number of biscuits.

Sample Input 4

45 1
17 55 85 55 74 20 90 67 40 70 39 89 91 50 16 24 14 43 24 66 25 9 89 71 41 16 53 13 61 15 85 72 62 67 42 26 36 66 4 87 59 91 4 25 26

Sample Output 4

17592186044416


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <stack> // s.top()
#include <bitset>
#include <queue> // s.front()
using namespace std;

typedef long long Int;
typedef pair<Int,Int> P;
#define print(x) cout<<(x)<<endl

#define INF10 10000000000
#define INF5 100000
#define EPS 1e-10
#define MOD 1000000007

int main() {
	int N, P; cin >> N >> P;
	int od = 0; int ev = 0;
	for (int i = 0; i < N; i++) {
		int ips; cin >> ips;
		if (ips % 2 == 0)ev++;
		else od++;
	}
	if (od == 0 && P == 1)print(0);
	Int ans = 1;
	if (P) {
		for (int i = 0; i < N; i++) {
			ans *= 2;
		}
		print(ans / 2);
	}
	else {
		for (int i = 0; i < N; i++) {
			ans *= 2;
		}
		print(ans);
	}

	return 0;
}


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

int n;
vector<int> edges[100000];

int solve(int v, int p){
    int ch = edges[v].size();
    if(p >= 0) --ch;
    if(ch == 0) return 0;
    int ret = 0;
    for(int u: edges[v]){
        if(u == p) continue;
        ret ^= solve(u, v) + 1;
    }
    return ret;
}

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

    cin >> n;
    for(int i=1;i<n;++i){
        int x, y;
        cin >> x >> y;
        --x; --y;
        edges[x].push_back(y);
        edges[y].push_back(x);
    }
    if(solve(0, -1) == 0) cout << "Bob" << endl;
    else cout << "Alice" << endl;

    return 0;
}

Score : 1100 points

Problem Statement

There is a tree with N vertices numbered 1, 2, ..., N.
The edges of the tree are denoted by (x_i, y_i).

On this tree, Alice and Bob play a game against each other.
Starting from Alice, they alternately perform the following operation:

Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1.

A player loses the game when he/she is unable to perform the operation.
Determine the winner of the game assuming that both players play optimally.

Constraints

2 \leq N \leq 100000

1 \leq x_i, y_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

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

Output

Print Alice if Alice wins; print Bob if Bob wins.

Sample Input 1

5
1 2
2 3
2 4
4 5

Sample Output 1

Alice

If Alice first removes the edge connecting Vertices 1 and 2, the tree becomes a single vertex tree containing only Vertex 1.
Since there is no edge anymore, Bob cannot perform the operation and Alice wins.

Sample Input 2

5
1 2
2 3
1 4
4 5

Sample Output 2

Bob

Sample Input 3

6
1 2
2 4
5 1
6 3
3 2

Sample Output 3

Alice

Sample Input 4

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

Sample Output 4

Bob


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

int a,b,c;
vector<int> v;

int main() {
	// your code goes here
	cin>>a>>b>>c;
	v.push_back(a);
	v.push_back(b);
	v.push_back(c);
	sort(v.begin(),v.end());
	cout<<v[0]+v[1]<<endl;
	return 0;
}

Score : 100 points

Problem Statement

Snuke is buying a bicycle.
The bicycle of his choice does not come with a bell, so he has to buy one separately.

He has very high awareness of safety, and decides to buy two bells, one for each hand.

The store sells three kinds of bells for the price of a, b and c yen (the currency of Japan), respectively.
Find the minimum total price of two different bells.

Constraints

1 \leq a,b,c \leq 10000

a, b and c are integers.

Input

Input is given from Standard Input in the following format:

a b c

Output

Print the minimum total price of two different bells.

Sample Input 1

700 600 780

Sample Output 1

1300

Buying a 700-yen bell and a 600-yen bell costs 1300 yen.

Buying a 700-yen bell and a 780-yen bell costs 1480 yen.

Buying a 600-yen bell and a 780-yen bell costs 1380 yen.

The minimum among these is 1300 yen.

Sample Input 2

10000 10000 10000

Sample Output 2

20000

Buying any two bells costs 20000 yen.


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

bool A(string S){
  for(int i=0;i<S.size()/2;i++){
    if(S.at(i)!=S.at(i+S.size()/2)){
      return 1;
    }
  }
  return 0;
}

int main(){
  string N;cin>>N;
  if(N.size()%2){
    N.pop_back();
  }
  while(A(N)){
    cout<<N<<endl;
    N.pop_back();
    N.pop_back();
  }
  cout<<N.size()/2<<endl;
}

Score : 200 points

Problem Statement

We will call a string that can be obtained by concatenating two equal strings an even string.
For example, xyzxyz and aaaaaa are even, while ababab and xyzxy are not.

You are given an even string S consisting of lowercase English letters.
Find the length of the longest even string that can be obtained by deleting one or more characters from the end of S.
It is guaranteed that such a non-empty string exists for a given input.

Constraints

2 \leq |S| \leq 200

S is an even string consisting of lowercase English letters.

There exists a non-empty even string that can be obtained by deleting one or more characters from the end of S.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest even string that can be obtained.

Sample Input 1

abaababaab

Sample Output 1

6

abaababaab itself is even, but we need to delete at least one character.

abaababaa is not even.

abaababa is not even.

abaabab is not even.

abaaba is even. Thus, we should print its length, 6.

Sample Input 2

xxxx

Sample Output 2

2

xxx is not even.

xx is even.

Sample Input 3

abcabcabcabc

Sample Output 3

6

The longest even string that can be obtained is abcabc, whose length is 6.

Sample Input 4

akasakaakasakasakaakas

Sample Output 4

14

The longest even string that can be obtained is akasakaakasaka, whose length is 14.


#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <utility>
#include <cmath>
#include <tuple>
#include <queue>
#include <bitset>
#include <set>
#include <map>
#include <list>

using ll = long long;
using ld = long double;
using namespace std;
const int INF = 1e9+100;
const ll INF64 = 7e18l;
const int mod = 1000000007;
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define ALL(a) (a).begin(), (a).end()
#define FIN ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);

int main(){
    FIN;
    ll n; cin >> n;
    vector<ll> a(n+1);
    a[0] = 0;
    for(ll i=1;i<n+1;i++){
        cin >> a[i];
    }

    vector<ll> ans(n+1);
    ans[0] = 0;

    if(n%2 == 0){
        ll idx = n;
        for(ll i=1;i<=n/2;i++){
            ans[i] = a[idx];
            idx -= 2;
        }
        idx = 1;
        for(ll i=n/2+1;i<=n;i++){
            ans[i] = a[idx];
            idx += 2;
        }
    }

    if(n%2 == 1){
        ll idx = n;
        for(ll i=1;i<=n/2+1;i++){
            ans[i] = a[idx];
            idx -= 2;
        }
        idx = 2;
        for(ll i=n/2+2;i<=n;i++){
            ans[i] = a[idx];
            idx += 2;
        }
    }

    for(ll i=1;i<=n;i++) cout << ans[i] << " ";
    cout << endl;
    return 0;
}

Score : 300 points

Problem Statement

You are given an integer sequence of length n, a_1, ..., a_n.
Let us consider performing the following n operations on an empty sequence b.

The i-th operation is as follows:

Append a_i to the end of b.

Reverse the order of the elements in b.

Find the sequence b obtained after these n operations.

Constraints

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

0 \leq a_i \leq 10^9

n and a_i are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print n integers in a line with spaces in between.
The i-th integer should be b_i.

Sample Input 1

4
1 2 3 4

Sample Output 1

4 2 1 3

After step 1 of the first operation, b becomes: 1.

After step 2 of the first operation, b becomes: 1.

After step 1 of the second operation, b becomes: 1, 2.

After step 2 of the second operation, b becomes: 2, 1.

After step 1 of the third operation, b becomes: 2, 1, 3.

After step 2 of the third operation, b becomes: 3, 1, 2.

After step 1 of the fourth operation, b becomes: 3, 1, 2, 4.

After step 2 of the fourth operation, b becomes: 4, 2, 1, 3.

Thus, the answer is 4 2 1 3.

Sample Input 2

3
1 2 3

Sample Output 2

3 1 2

As shown above in Sample Output 1, b becomes 3, 1, 2 after step 2 of the third operation. Thus, the answer is 3 1 2.

Sample Input 3

1
1000000000

Sample Output 3

1000000000

Sample Input 4

6
0 6 7 6 7 0

Sample Output 4

0 6 6 0 7 7


#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>

// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>

#include <unordered_set>
#include <unordered_map>

using namespace std;

#define all(c) ((c).begin()), ((c).end())
#define dump(c) cerr << "> " << #c << " = " << (c) << endl;
#define iter(c) __typeof((c).begin())
#define tr(i, c) for (iter(c) i = (c).begin(); i != (c).end(); i++)
#define REP(i, a, b) for (int i = a; i < (int)(b); i++)
#define rep(i, n) REP(i, 0, n)
#define mp make_pair
#define fst first
#define snd second
#define pb push_back
#define debug( fmt, ... ) \
        fprintf( stderr, \
                  fmt "\n", \
                  ##__VA_ARGS__ \
        )

typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

const int INF = 1 << 30;
const double EPS = 1e-10;

double zero(double d) {
    return abs(d) < EPS ? 0.0 : d;
}

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 (b<a) { a=b; return true; } return false; }
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );

template<typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
    return os << '(' << p.first << ',' << p.second << ')';
}

template<typename T>
ostream &operator<<(ostream &os, const vector<T> &a) {
    os << '[';
    rep(i, a.size()) os << (i ? " " : "") << a[i];
    return os << ']';
}

string toString(int i) {
    stringstream ss;
    ss << i;
    return ss.str();
}

const int MOD = 1000000007;
// a^k
ll fpow(ll a, ll k, int M) {
    ll res = 1ll;
    ll x = a;
    while (k != 0) {
        if ((k & 1) == 1)
            res = (res * x) % M;
        x = (x * x) % M;
        k >>= 1;
    }
    return res;
}

struct prepare {
	prepare() {
	    cout.setf(ios::fixed, ios::floatfield);
	    cout.precision(8);
	    ios_base::sync_with_stdio(false);
	}
} _prepare;

bool solve() {
    int n;
    cin >> n;
    vi a(n);
    rep(i,n)
    cin>>a[i];

    deque<int> que;
    rep(i, n){
        if(i%2==0)
            que.push_front(a[i]);
        else
            que.push_back(a[i]);
    }

    while(!que.empty()) {
        int f=0;
        if(n % 2 == 0) {
            f = que.back();
            que.pop_back();
        }
        else {
            f = que.front();
            que.pop_front();

        }
        cout << f << " ";
    }
    cout << endl;
}

int main() {
    auto res = solve();

    return 0;
}


#include <bits/stdc++.h>
#define ll long long
#define V vector<long long>
#define VV vector<vector<long long>>
#define VVV vector<vector<vector<long long>>>
#define rep(i,n) for(ll (i)=0;(i)<(n);++(i))
using namespace std;

V kai;
V ikai;
ll mod=1e9+7;

ll mpow(ll x, ll n){
    ll ans = 1;
    while(n != 0){
        if(n&1) ans = ans*x % mod;
        x = x*x % mod;
        n = n >> 1;
    }
    return ans;
}

ll comb(ll a,ll b){
    if(a == 0 && b == 0)return 1;
    if(a < b || a < 0)return 0;
    ll tmp = ikai[a-b]*ikai[b] % mod;
    return tmp * kai[a] % mod;
}

int main() {
    ll n;
    cin>>n;
    V a(n+1);
    vector<bool> used(n+1,false);
    ll num;
    rep(i,n+1){
        cin>>a[i];
        if(used[a[i]-1])num=a[i];
        used[a[i]-1]=true;
    }
    V pos;
    rep(i,n+1)if(a[i]==num)pos.push_back(i);
    kai.assign(1e6+1,0);
    ikai.assign(1e6+1, 0);
    kai[0]=1;
    ikai[0]=1;
    rep(i,1e6){
        kai[i+1]=kai[i]*(i+1);
        kai[i+1]%=mod;
        ikai[i+1]=ikai[i]*mpow(i+1, mod-2);
        ikai[i+1]%=mod;
    }
    for(ll k=1;k<=n+1;k++){
        ll res=comb(n+1,k);
        res-=comb(pos[0]+n-pos[1],k-1);
        res=(res+mod)%mod;
        cout<<res<<endl;
    }
}

Score : 600 points

Problem Statement

You are given an integer sequence of length n+1, a_1,a_2,...,a_{n+1}, which consists of the n integers 1,...,n.
It is known that each of the n integers 1,...,n appears at least once in this sequence.

For each integer k=1,...,n+1, find the number of the different subsequences (not necessarily contiguous) of the given sequence with length k, modulo 10^9+7.

Notes

If the contents of two subsequences are the same, they are not separately counted even if they originate from different positions in the original sequence.

A subsequence of a sequence a with length k is a sequence obtained by selecting k of the elements of a and arranging them without changing their relative order. For example, the sequences 1,3,5 and 1,2,3 are subsequences of 1,2,3,4,5, while 3,1,2 and 1,10,100 are not.

Constraints

1 \leq n \leq 10^5

1 \leq a_i \leq n

Each of the integers 1,...,n appears in the sequence.

n and a_i are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_{n+1}

Output

Print n+1 lines.
The k-th line should contain the number of the different subsequences of the given sequence with length k, modulo 10^9+7.

Sample Input 1

3
1 2 1 3

Sample Output 1

3
5
4
1

There are three subsequences with length 1: 1 and 2 and 3.

There are five subsequences with length 2: 1,1 and 1,2 and 1,3 and 2,1 and 2,3.

There are four subsequences with length 3: 1,1,3 and 1,2,1 and 1,2,3 and 2,1,3.

There is one subsequence with length 4: 1,2,1,3.

Sample Input 2

1
1 1

Sample Output 2

1
1

There is one subsequence with length 1: 1.

There is one subsequence with length 2: 1,1.

Sample Input 3

32
29 19 7 10 26 32 27 4 11 20 2 8 16 23 5 14 6 12 17 22 18 30 28 24 15 1 25 3 13 21 19 31 9

Sample Output 3

32
525
5453
40919
237336
1107568
4272048
13884156
38567100
92561040
193536720
354817320
573166440
818809200
37158313
166803103
166803103
37158313
818809200
573166440
354817320
193536720
92561040
38567100
13884156
4272048
1107568
237336
40920
5456
528
33
1

Be sure to print the numbers modulo 10^9+7.


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

int a,b,c;

int main()
{
    cin>>a>>b>>c;
    if(c<=b)
        cout<<"delicious";
    else
    if(a>=c-b)
        cout<<"safe";
    else
        cout<<"dangerous";
}

Score : 100 points

Problem Statement

Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier.
He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.

Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Otherwise, he does not find it delicious.

Takahashi bought some food A days before the "best-by" date, and ate it B days after he bought it.

Write a program that outputs delicious if he found it delicious, safe if he did not found it delicious but did not get a stomachache either, and dangerous if he got a stomachache.

Constraints

1 ≤ X,A,B ≤ 10^9

Input

Input is given from Standard Input in the following format:

X A B

Output

Print delicious if Takahashi found the food delicious; print safe if he neither found it delicious nor got a stomachache; print dangerous if he got a stomachache.

Sample Input 1

4 3 6

Sample Output 1

safe

He ate the food three days after the "best-by" date. It was not delicious or harmful for him.

Sample Input 2

6 5 1

Sample Output 2

delicious

He ate the food by the "best-by" date. It was delicious for him.

Sample Input 3

3 7 12

Sample Output 3

dangerous

He ate the food five days after the "best-by" date. It was harmful for him.


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

int main() {
  int N;
  cin >> N;
  vector<int> vec(N);
  for(int i=0;i<N;i++){
    cin >> vec.at(i);
  }
  int a = 0,ans = -1;
  for(int i=1;i<=N;i++){
    if(vec.at(a) == 2){
      ans = i;
      break;
    }
    a = vec.at(a)-1;
  }
  cout << ans << endl;
}

Score : 200 points

Problem Statement

Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.

The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up.
These buttons are numbered 1 through N.
When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It is possible that i=a_i.
When Button i is not lighten up, nothing will happen by pressing it.

Initially, Button 1 is lighten up. Takahashi wants to quit pressing buttons when Button 2 is lighten up.

Determine whether this is possible. If the answer is positive, find the minimum number of times he needs to press buttons.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

Print -1 if it is impossible to lighten up Button 2.
Otherwise, print the minimum number of times we need to press buttons in order to lighten up Button 2.

Sample Input 1

3
3
1
2

Sample Output 1

2

Press Button 1, then Button 3.

Sample Input 2

4
3
4
1
2

Sample Output 2

-1

Pressing Button 1 lightens up Button 3, and vice versa, so Button 2 will never be lighten up.

Sample Input 3

5
3
3
4
2
4

Sample Output 3

3


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

#define int long long

#define inf 1000000007LL
#define mod 1000000007LL

#define rep(i, n) for(int i = 0; i < (n); i++)
#define trep(i, n) for(int i = 0; i <= (n); i++)
#define rrep(i, n) for(int i = (n) - 1; i >= 0; i--)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define mfor(i, s, t) for(int i = (s); i < (t); i++)
#define tfor(i, s, t) for(int i = (s); i <= (t); i++)
#define rfor(i, s, t) for(int i = (t) - 1; i >= (s); i--)

int d[114514];

signed main() {
  int n;
  cin >> n;
  rep(i, n) {
    cin >> d[i];
  }
  int ma = 0;
  rep(i, n) {
    ma = max(ma, d[i]);
  }
  int f = 0;
  int h = 0;
  rep(i, n) {
    if(d[i] == ma) {
      f++;
    }
    else if(d[i] == ma - 1) {
      h++;
    }
    else {
      cout << "No" << endl;
      return 0;
    }
  }
  if(h == 0) {
    if(1 <= ma && ma <= f / 2) {
      cout << "Yes" << endl;
    }
    else if(ma == f - 1) {
      cout << "Yes" << endl;
    }
    else {
      cout << "No" << endl;
    }
  }
  else {
    if(f == 1) {
      cout << "No" << endl;
    }
    else if(h + 1 <= ma && ma <= h + f / 2) {
      cout << "Yes" << endl;
    }
    else {
      cout << "No" << endl;
    }
  }
}

Score : 700 points

Problem Statement

There are N cats.
We number them from 1 through N.

Each of the cats wears a hat.
Cat i says: "there are exactly a_i different colors among the N - 1 hats worn by the cats except me."

Determine whether there exists a sequence of colors of the hats that is consistent with the remarks of the cats.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N-1

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print Yes if there exists a sequence of colors of the hats that is consistent with the remarks of the cats; print No otherwise.

Sample Input 1

3
1 2 2

Sample Output 1

Yes

For example, if cat 1, 2 and 3 wears red, blue and blue hats, respectively, it is consistent with the remarks of the cats.

Sample Input 2

3
1 1 2

Sample Output 2

No

From the remark of cat 1, we can see that cat 2 and 3 wear hats of the same color.
Also, from the remark of cat 2, we can see that cat 1 and 3 wear hats of the same color.
Therefore, cat 1 and 2 wear hats of the same color, which contradicts the remark of cat 3.

Sample Input 3

5
4 3 4 3 4

Sample Output 3

No

Sample Input 4

3
2 2 2

Sample Output 4

Yes

Sample Input 5

4
2 2 2 2

Sample Output 5

Yes

Sample Input 6

5
3 3 3 3 3

Sample Output 6

No


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

const int MAXN=405;
const int MAXM=1e5+5;

int n,m;
int S[MAXN][MAXN],alive[MAXN];
pair<int,int> a[MAXM];

int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++) scanf("%d%d",&a[i].first,&a[i].second);
    for(int i=1;i<=n;i++){
        alive[i]=1;
        S[i][i]=1;
        for(int j=m;j>=1;j--){
            int x=a[j].first,y=a[j].second;
            if(!S[i][x]&&!S[i][y]) continue;
            if(S[i][x]&&S[i][y]){
                alive[i]=0;
                break;
            }
            S[i][x]=S[i][y]=1;
        }
    }
    int ans=0;
    for(int i=1;i<=n;i++)
        for(int j=i+1;j<=n;j++){
            if(!alive[i]||!alive[j]) continue;
            bool flag=1;
            for(int k=1;k<=n;k++)
                if(S[i][k]&&S[j][k]){
                    flag=0;
                    break;
                }
            if(flag) ans++;
        }
    printf("%d",ans);
}

Score : 1400 points

Problem Statement

There are N turkeys.
We number them from 1 through N.

M men will visit here one by one.
The i-th man to visit will take the following action:

If both turkeys x_i and y_i are alive: selects one of them with equal probability, then eats it.

If either turkey x_i or y_i is alive (but not both): eats the alive one.

If neither turkey x_i nor y_i is alive: does nothing.

Find the number of pairs (i,\ j) (1 ≤ i < j ≤ N) such that the following condition is held:

The probability of both turkeys i and j being alive after all the men took actions, is greater than 0.

Constraints

2 ≤ N ≤ 400

1 ≤ M ≤ 10^5

1 ≤ x_i < y_i ≤ N

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the number of pairs (i,\ j) (1 ≤ i < j ≤ N) such that the condition is held.

Sample Input 1

3 1
1 2

Sample Output 1

2

(i,\ j) = (1,\ 3), (2,\ 3) satisfy the condition.

Sample Input 2

4 3
1 2
3 4
2 3

Sample Output 2

1

(i,\ j) = (1,\ 4) satisfies the condition.
Both turkeys 1 and 4 are alive if:

The first man eats turkey 2.

The second man eats turkey 3.

The third man does nothing.

Sample Input 3

3 2
1 2
1 2

Sample Output 3

0

Sample Input 4

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

Sample Output 4

5


#include<bits/stdc++.h>
using namespace std;
int main(){
    int a,b,c;
    cin>>a>>b>>c;
    if((a*100+b*10+c)%4!=0) cout<<"Yes"<<endl;
    else cout<<"No"<<endl;
}

Score : 100 points

Problem Statement

AtCoDeer has three cards, one red, one green and one blue.

An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card.

We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer.

Is this integer a multiple of 4?

Constraints

1 ≤ r, g, b ≤ 9

Input

Input is given from Standard Input in the following format:

r g b

Output

If the three-digit integer is a multiple of 4, print YES (case-sensitive); otherwise, print NO.

Sample Input 1

4 3 2

Sample Output 1

YES

432 is a multiple of 4, and thus YES should be printed.

Sample Input 2

2 3 4

Sample Output 2

NO

234 is not a multiple of 4, and thus NO should be printed.


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

int N;
string S;

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

    string ans = "";
    bool f = false;
    int a = 0, b = 0;
    int j = 0;
    for (int i = 0; i < N; i++) {
        if (S[i] == '(') {
            if (f) {
                if (b > a) {
                    ans = string(b-a, '(') + ans;
                    ans += S.substr(j, i-j);
                    j = i;
                    f = false;
                    a = 0;
                    b = 0;
                }
            }
            a++;
        }
        else {
            f = true;
            b++;
        }
    }

    if (b > a) {
        ans = string(b-a, '(') + ans;
        ans += S.substr(j, N-j);
    }
    else {
        ans += S.substr(j, N-j);
        ans += string(a-b, ')');
    }

    cout << ans << endl;

    return 0;
}

Score : 400 points

Problem Statement

You are given a string S of length N consisting of ( and ). Your task is to insert some number of ( and ) into S to obtain a correct bracket sequence.

Here, a correct bracket sequence is defined as follows:

() is a correct bracket sequence.

If X is a correct bracket sequence, the concatenation of (, X and ) in this order is also a correct bracket sequence.

If X and Y are correct bracket sequences, the concatenation of X and Y in this order is also a correct bracket sequence.

Every correct bracket sequence can be derived from the rules above.

Find the shortest correct bracket sequence that can be obtained. If there is more than one such sequence, find the lexicographically smallest one.

Constraints

The length of S is N.

1 ≤ N ≤ 100

S consists of ( and ).

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the lexicographically smallest string among the shortest correct bracket sequences that can be obtained by inserting some number of ( and ) into S.

Sample Input 1

3
())

Sample Output 1

(())

Sample Input 2

6
)))())

Sample Output 2

(((()))())

Sample Input 3

8
))))((((

Sample Output 3

(((())))(((())))


#include <iostream>
using namespace std;

int main()
{
  int num1, num2, agg;
  agg = 0;

  cin >> num1 >> num2;
  agg = num1 + num2;

  if(agg >= 10)
  cout << "error" << endl;
  else
  cout << agg << endl;
}

Score : 100 points

Problem Statement

You are given two integers A and B as the input. Output the value of A + B.

However, if A + B is 10 or greater, output error instead.

Constraints

A and B are integers.

1 ≤ A, B ≤ 9

Input

Input is given from Standard Input in the following format:

A B

Output

If A + B is 10 or greater, print the string error (case-sensitive); otherwise, print the value of A + B.

Sample Input 1

6 3

Sample Output 1

9

Sample Input 2

6 4

Sample Output 2

error


#include <bits/stdc++.h>
#include <complex>
#include <iomanip>
using namespace std;
#define reps(i,s,n) for(int i = s; i < n; i++)
#define rep(i,n) reps(i,0,n)
#define fi first
#define se second
#define mp make_pair
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;

ll N,M,H,W,K,Q,A,B,C,L,R;
string S,T;
const ll MOD = (1e+9) + 7;
const ll INF = 1LL << 60;
const long double EPS = 1e-9;
typedef pair<ll,ll> P;

typedef vector<P> vp;
typedef vector<vp> matP;

int main() {
    cin>>N;
    vec s(N);
    rep(i,N) cin>>s[i];
    ll sum = 0;
    rep(i,N) sum += s[i];
    ll ans = 0;
    sort(s.begin(), s.end());
    reverse(s.begin(), s.end());
    rep(i,N){
        if((sum - s[i])%10 != 0) ans = sum - s[i];
    }
    if(sum%10 != 0) ans = sum;
    cout<<ans<<endl;
}

Score : 300 points

Problem Statement

You are taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When you finish answering the questions, your answers will be immediately judged and your grade will be displayed... if everything goes well.

However, the examination system is actually flawed, and if your grade is a multiple of 10, the system displays 0 as your grade. Otherwise, your grade is displayed correctly. In this situation, what is the maximum value that can be displayed as your grade?

Constraints

All input values are integers.

1 ≤ N ≤ 100

1 ≤ s_i ≤ 100

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the maximum value that can be displayed as your grade.

Sample Input 1

3
5
10
15

Sample Output 1

25

Your grade will be 25 if the 10-point and 15-point questions are answered correctly and the 5-point question is not, and this grade will be displayed correctly. Your grade will become 30 if the 5-point question is also answered correctly, but this grade will be incorrectly displayed as 0.

Sample Input 2

3
10
10
15

Sample Output 2

35

Your grade will be 35 if all the questions are answered correctly, and this grade will be displayed correctly.

Sample Input 3

3
10
20
30

Sample Output 3

0

Regardless of whether each question is answered correctly or not, your grade will be a multiple of 10 and displayed as 0.


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

#define fill(a,val) memset(a, (val), sizeof a)
#define pb push_back
#define lli long long int
#define scantype int
#define endl "\n"
#define unique(x) x.erase(unique(x.begin(),x.end()), x.end())
#define debug(x) cerr << #x " = " << (x) << '\n'
#define what_is(x) cerr << #x << " is " << x << endl;

lli MOD  = 1000000007;
lli inf = 1e15;

void scan(scantype &x);

lli powermod(lli _a,lli _b,lli _m){lli _r=1;while(_b){if(_b%2==1)_r=(_r*_a)%_m;_b/=2;_a=(_a*_a)%_m;}return _r;}
lli string_to_number(string s){lli x=0; stringstream convert(s); convert>>x; return x;}
lli add(lli a,lli b){lli x = (a+b)%MOD; return x; }
lli mul(lli a,lli b){lli x = (a*b)%MOD; return x; }
lli sub(lli a,lli b){lli x = (a-b+MOD)%MOD; return x; }
lli div(lli a,lli b){lli x = a;lli y = powermod(b,MOD-2,MOD);lli res = (x*y)%MOD;return res;}

bool isprime(long long int n)
{
    if(n ==1 )
        return false;
    if(n == 2)
        return true;
    for(long long int i =2;i<=n/i;i++)
    {
        if(n%i == 0)
            return false;
    }
    return true;
}
lli h[100003];
int n;

lli a,b;
bool chk(lli t)
{
    lli te[n];
    for(int i = 0;i<n;i++)
        te[i] = h[i]-t*b;
    lli temp = 0;
    for(int i = 0;i<n;i++)
        temp += ceil((float)te[i]/(a-b));
    if(temp >t)
        return false;
    return true;
}

int main(void)
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    t = 1;
    while(t--)
    {
        cin>>n>>a>>b;
        for(int i = 0;i<n;i++)
            cin>>h[i];
        int s= 1;
        int ed = 1000000000;
        int ans =0;
        while(s<ed)
        {
            int t = (s+ed)>>1;
            if(chk(t))
            {
                ans = t;
                ed = t;
            }
            else
                s = t+1;
        }
        cout<<ans;

    }

    return 0;
}

void scan(scantype &x)
{
    register int c = getchar(); //for negative/positive
    x = 0;
    int neg = 0;
    for(;((c<48 || c>57) && c != '-');c = getchar());
    if(c=='-') {neg=1;c=getchar();}
    for(;c>47 && c<58;c = getchar()) {x = (x<<1) + (x<<3) + c - 48;}
    if(neg) x=-x;
}

Score : 400 points

Problem Statement

You are going out for a walk, when you suddenly encounter N monsters. Each monster has a parameter called health, and the health of the i-th monster is h_i at the moment of encounter. A monster will vanish immediately when its health drops to 0 or below.

Fortunately, you are a skilled magician, capable of causing explosions that damage monsters. In one explosion, you can damage monsters as follows:

Select an alive monster, and cause an explosion centered at that monster. The health of the monster at the center of the explosion will decrease by A, and the health of each of the other monsters will decrease by B. Here, A and B are predetermined parameters, and A > B holds.

At least how many explosions do you need to cause in order to vanish all the monsters?

Constraints

All input values are integers.

1 ≤ N ≤ 10^5

1 ≤ B < A ≤ 10^9

1 ≤ h_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N A B
h_1
h_2
:
h_N

Output

Print the minimum number of explosions that needs to be caused in order to vanish all the monsters.

Sample Input 1

4 5 3
8
7
4
2

Sample Output 1

2

You can vanish all the monsters in two explosion, as follows:

First, cause an explosion centered at the monster with 8 health. The healths of the four monsters become 3, 4, 1 and -1, respectively, and the last monster vanishes.

Second, cause an explosion centered at the monster with 4 health remaining. The healths of the three remaining monsters become 0, -1 and -2, respectively, and all the monsters are now vanished.

Sample Input 2

2 10 4
20
20

Sample Output 2

4

You need to cause two explosions centered at each monster, for a total of four.

Sample Input 3

5 2 1
900000000
900000000
1000000000
1000000000
1000000000

Sample Output 3

800000000


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define F first
#define S second
#define int long long
#define pii pair<int, int>
#define ins insert
#define sz size()

using namespace std;

template<typename T>
using ordered_set = __gnu_pbds::tree<T,__gnu_pbds::null_type,std::less<T>,__gnu_pbds::rb_tree_tag,__gnu_pbds::tree_order_statistics_node_update>;

ordered_set < pii > st;
const int maxn = 2e5+5;
int n, k, ans, a[maxn];

void Speed() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
}

main(){
    Speed();
    cin >> n >> k;
    for(int i = 1; i <= n; ++ i) {
        cin >> a[i];
        a[i] -= k;
        a[i] += a[i - 1];
    }
    for(int i = 0; i <= n; ++ i) {
        int cnt = st.order_of_key({a[i] + 1, -1});
        ans += cnt;
        st.ins({a[i], i});
    }
    cout << ans;
}

Score : 600 points

Problem Statement

You are given an integer sequence of length N, a = {a_1, a_2, …, a_N}, and an integer K.

a has N(N+1)/2 non-empty contiguous subsequences, {a_l, a_{l+1}, …, a_r} (1 ≤ l ≤ r ≤ N). Among them, how many have an arithmetic mean that is greater than or equal to K?

Constraints

All input values are integers.

1 ≤ N ≤ 2 \times 10^5

1 ≤ K ≤ 10^9

1 ≤ a_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N K
a_1
a_2
:
a_N

Output

Print the number of the non-empty contiguous subsequences with an arithmetic mean that is greater than or equal to K.

Sample Input 1

3 6
7
5
7

Sample Output 1

5

All the non-empty contiguous subsequences of a are listed below:

{a_1} = {7}

{a_1, a_2} = {7, 5}

{a_1, a_2, a_3} = {7, 5, 7}

{a_2} = {5}

{a_2, a_3} = {5, 7}

{a_3} = {7}

Their means are 7, 6, 19/3, 5, 6 and 7, respectively, and five among them are 6 or greater. Note that {a_1} and {a_3} are indistinguishable by the values of their elements, but we count them individually.

Sample Input 2

1 2
1

Sample Output 2

0

Sample Input 3

7 26
10
20
30
40
30
20
10

Sample Output 3

13


Score : 700 points

Problem Statement

Nuske has a grid with N rows and M columns of squares. The rows are numbered 1 through N from top to bottom, and the columns are numbered 1 through M from left to right.
Each square in the grid is painted in either blue or white. If S_{i,j} is 1, the square at the i-th row and j-th column is blue; if S_{i,j} is 0, the square is white.
For every pair of two blue square a and b, there is at most one path that starts from a, repeatedly proceeds to an adjacent (side by side) blue square and finally reaches b, without traversing the same square more than once.

Phantom Thnook, Nuske's eternal rival, gives Q queries to Nuske. The i-th query consists of four integers x_{i,1}, y_{i,1}, x_{i,2} and y_{i,2} and asks him the following: when the rectangular region of the grid bounded by (and including) the x_{i,1}-th row, x_{i,2}-th row, y_{i,1}-th column and y_{i,2}-th column is cut out, how many connected components consisting of blue squares there are in the region?

Process all the queries.

Constraints

1 ≤ N,M ≤ 2000

1 ≤ Q ≤ 200000

S_{i,j} is either 0 or 1.

S_{i,j} satisfies the condition explained in the statement.

1 ≤ x_{i,1} ≤ x_{i,2} ≤ N(1 ≤ i ≤ Q)

1 ≤ y_{i,1} ≤ y_{i,2} ≤ M(1 ≤ i ≤ Q)

Input

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

N M Q
S_{1,1}..S_{1,M}
:
S_{N,1}..S_{N,M}
x_{1,1} y_{i,1} x_{i,2} y_{i,2}
:
x_{Q,1} y_{Q,1} x_{Q,2} y_{Q,2}

Output

For each query, print the number of the connected components consisting of blue squares in the region.

Sample Input 1

3 4 4
1101
0110
1101
1 1 3 4
1 1 3 1
2 2 3 4
1 2 2 4

Sample Output 1

3
2
2
2

In the first query, the whole grid is specified. There are three components consisting of blue squares, and thus 3 should be printed.

In the second query, the region within the red frame is specified. There are two components consisting of blue squares, and thus 2 should be printed.
Note that squares that belong to the same component in the original grid may belong to different components.

Sample Input 2

5 5 6
11010
01110
10101
11101
01010
1 1 5 5
1 2 4 5
2 3 3 4
3 3 3 3
3 1 3 5
1 1 3 4

Sample Output 2

3
2
1
1
3
2


#include<bits/stdc++.h>

using namespace std;

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

  int g[13] = {};
  g[4] = g[6] = g[9] = g[11] = 1;
  g[2] = 2;

  if(g[x] == g[y]) cout << "Yes" << endl;
  else cout << "No" << endl;
}

Score : 100 points

Problem Statement

Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below.
Given two integers x and y (1 ≤ x < y ≤ 12), determine whether they belong to the same group.

Constraints

x and y are integers.

1 ≤ x < y ≤ 12

Input

Input is given from Standard Input in the following format:

x y

Output

If x and y belong to the same group, print Yes; otherwise, print No.

Sample Input 1

1 3

Sample Output 1

Yes

Sample Input 2

2 4

Sample Output 2

No


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

int main() {
  int H, W;
  cin >> H >> W;

  for(int i = 0; i < W + 2; i++) cout << '#';
  cout << endl;

  string A;
  for(int i = 0; i < H; i++){
    cin >> A;
    cout << '#' << A << '#' << endl;
  }

  for(int i = 0; i < W + 2; i++) cout << '#';
  cout << endl;

}

Score : 200 points

Problem Statement

You are given a image with a height of H pixels and a width of W pixels.
Each pixel is represented by a lowercase English letter.
The pixel at the i-th row from the top and j-th column from the left is a_{ij}.

Put a box around this image and output the result. The box should consist of # and have a thickness of 1.

Constraints

1 ≤ H, W ≤ 100

a_{ij} is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

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

Output

Print the image surrounded by a box that consists of # and has a thickness of 1.

Sample Input 1

2 3
abc
arc

Sample Output 1

#####
#abc#
#arc#
#####

Sample Input 2

1 1
z

Sample Output 2

###
#z#
###


#include "bits/stdc++.h"
using namespace std;
#define FOR(i,a,b) for(int i =(a);i<(b);i++)
#define REP(i,n) for(int i=0;i<(n);i++)
#define REPm(i,n) for(int i=(n)-1;i>=0;i--)
#define REP1(i,n) for(int i=1;i<=(n);i++)
typedef long long ll;
int main(){
    int H,W;
    string a[100];
    cin >> H >> W;
    REP(i,H) cin >> a[i];
    REP(i,W+2) cout << '#';
    cout << endl;
    REP(i,H) cout << '#' << a[i] << '#' << endl;
    REP(i,W+2) cout << '#';
    cout << endl;
    return 0;
}


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

struct Fast {Fast(){std::cin.tie(0);ios::sync_with_stdio(false);}} fast;

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
typedef deque<int> dqi;

#define reps(i, a, b) for (int i = a; i < b; ++i)
#define rep(i, n) reps(i, 0, n)
#define REPS(i, a, b) reps(i, a, b)
#define REP(i, n) rep(i, n)
#define deps(i, a, b) for (int i = a; i >= b; --i)
#define dep(i, n) deps(i, n, 0)
#define DEPS(i, a, b) deps(i, a, b)
#define DEP(i, n) dep(i, n)

#define pf push_front
#define pb push_back
#define mp make_pair
#define fst first
#define FST fst
#define sec second
#define SEC sec
#define sz(obj) ((int)(obj).size())
#define all(v) (v).begin(), (v).end()
#define ALL(v) all(v)

const int INF = 999999999;
const int MOD = 1e9 + 7;
const int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};

inline bool inside(int y, int x, int H, int W) {return y >= 0 && x >= 0 && y < H && x < W;}
inline int in() {int x; std::cin >> x; return x;}
template <typename T>
void print(std::vector<T>& v, char c = ' ') {
  REP(i, v.size()) {
    if (i != 0) std::cout << c;
    std::cout << v[i];
  }
  std::cout << endl;
}
template <typename T> void print(T x) { std::cout << x << '\n'; }

signed main()
{
  int H, W;
  cin >> H >> W;

  if (H % 3 == 0 or W % 3 == 0) {
    cout << 0 << endl;
    return 0;
  }

  long long int h = min(H, W), w = max(H, W), wl = w/2;
  long long int ans = LLONG_MAX;

  for (int i = 1; i < h; i++) {
    vector<long long> v = {i*w, (h - i)*wl, (h - i)*(w - wl)};
    ans = min(ans, *max_element(v.begin(), v.end()) - *min_element(v.begin(), v.end()));
    int hl = (h - i)/2;
    v = {i*w, hl*w, (h - hl)*wl};
    ans = min(ans, *max_element(v.begin(), v.end()) - *min_element(v.begin(), v.end()));
  }
  h = max(H, W), w = min(H, W), wl = w/2;

  for (int i = 1; i < h; i++) {
    vector<long long> v = {i*w, (h - i)*wl, (h - i)*(w - wl)};
    ans = min(ans, *max_element(v.begin(), v.end()) - *min_element(v.begin(), v.end()));
    int hl = (h - i)/2;
    v = {i*w, hl*w, (h - hl)*wl};
    ans = min(ans, *max_element(v.begin(), v.end()) - *min_element(v.begin(), v.end()));
  }
  cout << ans << endl;

  return (0);
}

Score : 400 points

Problem Statement

There is a bar of chocolate with a height of H blocks and a width of W blocks.
Snuke is dividing this bar into exactly three pieces.
He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.

Snuke is trying to divide the bar as evenly as possible.
More specifically, he is trying to minimize S_{max} - S_{min}, where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece.
Find the minimum possible value of S_{max} - S_{min}.

Constraints

2 ≤ H, W ≤ 10^5

Input

Input is given from Standard Input in the following format:

H W

Output

Print the minimum possible value of S_{max} - S_{min}.

Sample Input 1

3 5

Sample Output 1

0

In the division below, S_{max} - S_{min} = 5 - 5 = 0.

Sample Input 2

4 5

Sample Output 2

2

In the division below, S_{max} - S_{min} = 8 - 6 = 2.

Sample Input 3

5 5

Sample Output 3

4

In the division below, S_{max} - S_{min} = 10 - 6 = 4.

Sample Input 4

100000 2

Sample Output 4

1

Sample Input 5

100000 100000

Sample Output 5

50000


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

int main(){
  long n, a, sumf = 0, sumr = 0;  cin >> n;
  priority_queue<long, vector<long>, greater<long>> fr;
  vector<int> mid(n);
  priority_queue<long> re;

  for(int i=0; i<n; i++){
    cin >> a;
    sumf += a;
    fr.push(a);
  }
  for(int i=0; i<n; i++)  cin >> mid[i];
  for(int i=0; i<n; i++){
    cin >> a;
    sumr += a;
    re.push(a);
  }
  vector<long> sf(n+1), sr(n+1);  sf[0] = sumf, sr[n] = sumr;
  for(int i=0; i<n; i++){
    sumf -= fr.top();  fr.pop();
    sumf += mid[i];
    fr.push(mid[i]);
    sf[i+1] = sumf;
  }
  for(int i=n-1; i>=0; i--){
    sumr -= re.top();  re.pop();
    sumr += mid[i];
    re.push(mid[i]);
    sr[i] = sumr;
  }
  long ans = -1e18;
  for(int i=0; i<=n; i++)
    ans = max(ans, sf[i]-sr[i]);

  cout << ans << endl;

  return 0;
}

Score : 500 points

Problem Statement

Let N be a positive integer.

There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}).
Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements.
Here, the score of a' is defined as follows: (the sum of the elements in the first half of a') - (the sum of the elements in the second half of a').

Find the maximum possible score of a'.

Constraints

1 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Partial Score

In the test set worth 300 points, N ≤ 1000.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the maximum possible score of a'.

Sample Input 1

2
3 1 4 1 5 9

Sample Output 1

1

When a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3 + 4) - (1 + 5) = 1.

Sample Input 2

1
1 2 3

Sample Output 2

-1

For example, when a_1 are removed, a' will be (2, 3), which has a score of 2 - 3 = -1.

Sample Input 3

3
8 2 2 7 4 6 5 3 8

Sample Output 3

5

For example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3), which has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5.


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

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

LL a[300000],l[100001],r[100001];
int n;

int main(){
  cin>>n;
  REP(i,3*n)
    cin>>a[i];

  LL su=accumulate(a,a+n,0);
  priority_queue<LL,vector<LL>,greater<LL>> q;
  REP(i,n)
    q.push(a[i]);
  REP(i,n+1){
    l[i]=su;
    q.push(a[n+i]);
    su+=a[n+i]-q.top();
    q.pop();
  }

  su=accumulate(a+2*n,a+3*n,0);
  priority_queue<LL> q2;
  REP(i,n)
    q2.push(a[2*n+i]);
  REP(i,n+1){
    r[n-i]=su;
    q2.push(a[2*n-1-i]);
    su+=a[2*n-1-i]-q2.top();
    q2.pop();
  }

  LL ret=-1e15;
  REP(i,n+1){
    //cerr<<i<<" "<<l[i]<<" "<<r[i]<<endl;
    ret=max(ret,l[i]-r[i]);
  }
  cout<<ret<<endl;
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
  ll n,k;
  cin>>n>>k;
  set<ll> se;
  map<ll,ll> ma;
  for(ll i=0;i<n;i++){
    ll a,b;
    cin>>a>>b;
    ma[a]+=b;
    se.insert(a);
  }
  ll c=0;
  for(ll s:se){
    c+=ma[s];
    if(c>=k){
      cout<<s;
      return 0;
    }
  }
}

Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


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

int main(){
  int N, K;
  cin >> N >> K;
  vector<int> a(N), b(N);
  for(int i=0; i<N; i++) cin >> a[i] >> b[i];

  map<int,int> m;
  int v=0;
  for(int i=0; i<N; i++){
    m[a[i]] = v+b[i];
    v += b[i];
  }

for(auto itr=m.begin(); itr!=m.end(); itr++){
    //cout << itr->first <<" "<< itr->second <<" "<< K << endl;
    if(K <= itr->second){
      cout << itr->first << endl;
    }
  }

}


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

#define dump(...) do{print_vars(cout<<"# "<<#__VA_ARGS__<<'=',__VA_ARGS__);cout<<endl;}while(0)
#define repi(i,a,b) for(int i=int(a);i<int(b);i++)
#define peri(i,a,b) for(int i=int(b);i-->int(a);)
#define rep(i,n) repi(i,0,n)
#define per(i,n) peri(i,0,n)
#define all(c) begin(c),end(c)
#define mp make_pair
#define mt make_tuple

using uint=unsigned;
using ll=long long;
using ull=unsigned long long;
using vi=vector<int>;
using vvi=vector<vi>;
using vl=vector<ll>;
using vvl=vector<vl>;
using vd=vector<double>;
using vvd=vector<vd>;
using vs=vector<string>;

void print_vars(ostream&){}
template<typename Car,typename... Cdr>
void print_vars(ostream& os,const Car& car,const Cdr&... cdr){
	print_vars(os<<car<<(sizeof...(cdr)?",":""),cdr...);
}

template<typename T1,typename T2>
ostream& operator<<(ostream& os,const pair<T1,T2>& p){
	return os<<'('<<p.first<<','<<p.second<<')';
}

template<int I,typename Tuple>
void print_tuple(ostream&,const Tuple&){}
template<int I,typename Car,typename... Cdr,typename Tuple>
void print_tuple(ostream& os,const Tuple& t){
	os<<get<I>(t)<<(sizeof...(Cdr)?",":"");
	print_tuple<I+1,Cdr...>(os,t);
}
template<typename... Args>
ostream& operator<<(ostream& os,const tuple<Args...>& t){
	print_tuple<0,Args...>(os<<'(',t);
	return os<<')';
}

template<typename Ch,typename Tr,typename C>
basic_ostream<Ch,Tr>& operator<<(basic_ostream<Ch,Tr>& os,const C& c){
	os<<'[';
	for(auto i=begin(c);i!=end(c);++i)
		os<<(i==begin(c)?"":" ")<<*i;
	return os<<']';
}

constexpr int INF=1e9;
constexpr int MOD=1e9+7;
constexpr double EPS=1e-9;

int main()
{
	#ifndef _GLIBCXX_DEBUG
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	constexpr char endl='\n';
	#endif

	for(ll n,k;cin>>n>>k&&n|k;){
		vl f(100001),g(100002);
		rep(i,n){
			int a,b; cin>>a>>b;
			f[a]+=b;
		}
		rep(i,f.size()) g[i+1]=g[i]+f[i];
		int res=upper_bound(all(g),k-1)-begin(g)-1;
		cout<<res<<endl;
	}
}


#include<iostream>
using namespace std;

int main()
{
	long long N, K;
	cin >> N >> K;
	unsigned long long num[100001] = { 0 };
	for (long long i = 0; i < N; i++) {
		long long a, b;
		cin >> a >> b;
		num[a] += b;
	}
	unsigned long long sum = 0;
	for (long long i = 1; i < 100001; i++) {
		sum += num[i];
		if (K <= sum) {
			cout << i << endl;
			return 0;
		}
	}
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
#define LIMIT1 200010
#define INF (1<<29)
#define LLINF (1LL<<60)
typedef long long ll;
#define rep(i,n) for((i)=0;(i)<(n);(i)++)
const ll MAX_E = LIMIT1;
const ll MAX_V = LIMIT1;

struct edge { ll from,to,cost; };
edge es[MAX_E];

ll d[MAX_V];
int V,E;

bool negative[LIMIT1];

void shortest_path(int s){
    for(int i=0;i<V;i++){
        d[i]=LLINF;
        negative[i]=false;
    }
    d[s] = 0;
    for(int loop=0;loop<V-1;loop++){
        for(int i=0;i<E;i++){
            edge e=es[i];
            if(d[e.from] != LLINF && d[e.to] > d[e.from]+e.cost){
                d[e.to] = d[e.from] + e.cost;
            }
        }
    }
}
bool find_negative_loop(){
  for(int i=0;i<V;i++) negative[i]=false;
  for(int loop=0;loop<V;loop++){
    for(int i=0;i<E;i++){
      if(d[es[i].from] == LLINF) continue;

      if(d[es[i].to] > d[es[i].from] + es[i].cost){
        d[es[i].to] = d[es[i].from] + es[i].cost;
        negative[es[i].to] = true;
      }
      if(negative[es[i].from]==true){
        negative[es[i].to] = true;
      }
    }
  }
  return negative[V-1];
}

int main(){
    int i,j;
    ll result=0;
    cin >> V >> E;
    rep(i,E){
        cin >> es[i].from >> es[i].to >> es[i].cost;
        es[i].from--;
        es[i].to--;
        es[i].cost *= -1;
    }
    shortest_path(0);
    result = -d[V-1];
    if(find_negative_loop()){
      cout << "inf" << endl;
      return 0;
    }
    cout << result << endl;

    return 0;
}

Score : 400 points

Problem Statement

There is a directed graph with N vertices and M edges.
The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i.
We will play the following single-player game using this graph and a piece.

Initially, the piece is placed at vertex 1, and the score of the player is set to 0.
The player can move the piece as follows:

When the piece is placed at vertex a_i, move the piece along the i-th edge to vertex b_i. After this move, the score of the player is increased by c_i.

The player can end the game only when the piece is placed at vertex N.
The given graph guarantees that it is possible to traverse from vertex 1 to vertex N.

When the player acts optimally to maximize the score at the end of the game, what will the score be?
If it is possible to increase the score indefinitely, print inf.

Constraints

2≤N≤1000

1≤M≤min(N(N-1),2000)

1≤a_i,b_i≤N (1≤i≤M)

a_i≠b_i (1≤i≤M)

a_i≠a_j or b_i≠b_j (1≤i<j≤M)

-10^9≤c_i≤10^9 (1≤i≤M)

c_i is an integer.

In the given graph, there exists a path from vertex 1 to vertex N.

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print inf.

Sample Input 1

3 3
1 2 4
2 3 3
1 3 5

Sample Output 1

7

There are two ways to move the piece to vertex N=3:

vertex 1 → vertex 2 → vertex 3 : score 4+3=7

vertex 1 → vertex 3 : score 5

Thus, the maximum possible score at the end of the game is 7.

Sample Input 2

2 2
1 2 1
2 1 1

Sample Output 2

inf

It is possible to increase the score indefinitely by alternating between vertex 1 and 2.

Sample Input 3

6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000

Sample Output 3

-5000000000


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(ll i = 0, i##_len = (n); i < i##_len; i++)
#define reps(i, s, n) for(ll i = (s), i##_len = (n); i < i##_len; i++)
#define rrep(i, n) for(ll i = (n) - 1; i >= 0; i--)
#define rreps(i, e, n) for(ll i = (n) - 1; i >= (e); i--)
#define all(x) (x).begin(), (x).end()
#define sz(x) ((ll)(x).size())
#define len(x) ((ll)(x).length())

template<class T>
struct BellmanFord {
private:
    struct Edge { int to, cost; };
    int n;
    vector<vector<Edge>> edges;
    vector<vector<bool>> reachable;

    void get_reachable_dfs(int from, int to) {
        if (reachable[from][to]) return;
        reachable[from][to] = true;
        for (auto e : edges[to]) {
            get_reachable_dfs(from, e.to);
        }
    }

    bool is_reachable(int from, int to) {
        if (reachable.size() == 0) {
            reachable.resize(n, vector<bool>(n, false));
            for (int i = 0; i < reachable.size(); i++) {
                get_reachable_dfs(i, i);
            }
        }
        return reachable[from][to];
    }

public:
    const T inf = numeric_limits<T>::max() / 2 - 1;
    vector<T> dist;
    vector<bool> negative;

    BellmanFord() {}
    BellmanFord(int _n) : edges(_n), dist(_n), negative(_n) {
        n = _n;
    }

    void add_edge(int from, int to, int cost) {
        edges[from].push_back((Edge){to, cost});
    }

    void get_distance(int _from, int _to = -1) {
        for (int i = 0; i < n; i++) {
            dist[i] = inf;
            negative[i] = false;
        }
        dist[_from] = 0;
        for (int i = 0; i < (n - 1); i++) {
            for (int from = 0; from < n; from++) {
                for (int j = 0, el = sz(edges[from]); j < el; j++) {
                    int to = edges[from][j].to;
                    int cost = edges[from][j].cost;
                    if ((dist[from] != inf) && (dist[to] > (dist[from] + cost))) {
                        dist[to] = dist[from] + cost;
                    }
                }
            }
        }
        vector<T> tmp(n);
        for (int i = 0; i < n; i++) tmp[i] = dist[i];
        for (int i = 0; i < n; i++) {
            for (int from = 0; from < n; from++) {
                for (int j = 0, el = sz(edges[from]); j < el; j++) {
                    int to = edges[from][j].to;
                    int cost = edges[from][j].cost;
                    if ((tmp[from] != inf) && (tmp[to] > (tmp[from] + cost))) {
                        tmp[to] = tmp[from] + cost;
                        negative[from] = negative[to] = true;
                    }
                }
            }
        }
        for (int i = 0; i < n; i++) {
            if ((is_reachable(_from, i)) && (tmp[i] != dist[i])) {
                if (_to == -1) {
                    negative[_from] = negative[i] = true;
                }
                else if (is_reachable(i, _to)) {
                    negative[_from] = negative[_to] = negative[i] = true;
                }
            }
        }
    }
};

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    // ifstream in("input.txt");
    // cin.rdbuf(in.rdbuf());
    ll n, m;
    cin >> n >> m;
    BellmanFord<ll> bf(n);
    rep(i, n) {
        ll a, b, c;
        cin >> a >> b >> c;
        a--; b--;
        bf.add_edge(a, b, -c);
    }
    bf.get_distance(0, n - 1);
    if (bf.negative[n - 1]) {
        cout << "inf" << endl;
    }
    else {
        cout << (-bf.dist[n - 1]) << endl;
    }
    return 0;
}


#include<iostream>
#include<iomanip>
#include<algorithm>
#include<cassert>
#include<vector>
#include<fstream>
#include<string>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<queue>
#include<map>
#include<set>
#include<bitset>
#include<cmath>
#include<typeinfo>

using namespace std;
#define rep(i,m,n) for(int i=m;i<n;++i)
#define llrep(i,m,n) for(ll i=m;i<n;++i)
#define inf 1000000000
#define llinf 1000000000000000000
#define MOD 1000000007
#define ll long long
#define mp make_pair
#define all(v) v.begin(),v.end()

ll edge[1100][1100], dist[1100];
queue<int>q;

int main() {
	int n, m;
	cin >> n >> m;
	rep(i, 0, 1100) {
		rep(j, 0, 1100) {
			edge[i][j] = -llinf;
		}
	}
	rep(i, 0, m) {
		ll a, b, c;
		cin >> a >> b >> c;
		edge[a][b] = c;
	}
	rep(i, 0, 1100) {
		dist[i] = -llinf;
	}
	dist[1] = 0;
	q.push(1);
	int co = 0;
	while (!q.empty()) {
		int hoge = q.front();
		q.pop();
		if (co > 2 * m) {
			cout << "inf" << endl;
			return 0;
		}
		co++;
		rep(i, 1, n + 1) {
			if (edge[hoge][i] != -llinf && dist[i] < dist[hoge] + edge[hoge][i]) {
				q.push(i);
				dist[i] = dist[hoge] + edge[hoge][i];
			}
		}
	}
	cout << dist[n] << endl;
	return 0;
}


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

using namespace std;

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

template<typename T>
bool BellmanFord(int s, int V, vector<vector<pair<T, int>>> edge, vector<T> &dist) {
    if (typeid(T) == typeid(int)) dist = vector<T>(V, INF);
    else dist = vector<T>(V, LONG_LONG_MAX / 4);
    dist[s] = 0;
    bool ischange;
    int cnt = 0;
    vector<bool> used;
//
//    rep(i, V) {
//        rep(j, M) {
//            if (dist[i] <)
//        }
//    }

    do {
        used = vector<bool>(V, false);
        queue<pair<T, int>> que;
        cnt++;
        ischange = false;
        for (pair<T, int> e:edge[s]) {
            que.push(make_pair(dist[s] + e.first, e.second));
        }
        used[s] = true;
        while (!que.empty()) {
            T d;
            int t;
            tie(d, t) = que.front();
            que.pop();
            if (d < dist[t]) {
                dist[t] = d;
                ischange = true;
            }
            if (used[t]) continue;
            for (pair<T, int> e: edge[t]) {
                que.push(make_pair(dist[t] + e.first, e.second));
            }
            used[t] = true;
        }
    } while (ischange && cnt <= V);
    return !ischange;
}

template<typename T>
void BellmanFord2(int s, int V, int E, vector<int> from, vector<int> to, vector<T> d, vector<T> &dist,
                  vector<bool> &negative) {
    if (typeid(T) == typeid(int)) dist = vector<T>(V, INF);
    else dist = vector<T>(V, LONG_LONG_MAX / 4);
    dist[s] = 0;
    bool ischange;
    int cnt = 0;
    vector<bool> used;

    rep(i, V - 1) {
        ischange = false;
        rep(j, E) {
            if (dist[from[j]] + d[j] < dist[to[j]]) {
                ischange = true;
                dist[to[j]] = dist[from[j]] + d[j];
            }
        }
        if (!ischange) break;
    }

    negative = vector<bool>(V, false);

    rep(i, V) {
        ischange = false;
        rep(j, E) {
            if (dist[from[j]] + d[j] < dist[to[j]]) {
                ischange = true;
                dist[to[j]] = dist[from[j]] + d[j];
                negative[to[j]] = true;
            }
        }
        if (!ischange) break;
    }
}

int main() {
    int N, M;
    cin >> N >> M;

    vi a(M), b(M);
    vl c(M);
    rep(i, M) {
        cin >> a[i] >> b[i] >> c[i];
        a[i]--;
        b[i]--;
        c[i] *= -1;
    }
    vl dist;
    vb negative;
    BellmanFord2(0, N, M, a, b, c, dist,negative);
    if(!negative[N-1]){
        cout << -dist[N - 1] << endl;
    } else {
        cout << "inf" << endl;
    }

//    vector<vector<pair<ll, int>>> edge(N);
//    rep(i, M) {
//        int a, b, c;
//        cin >> a >> b >> c;
//        a--;
//        b--;
//        c *= -1;
//        edge[a].push_back(make_pair(c, b));
//    }
//    vl dist;
//    if (BellmanFord(0, N, edge, dist)) {
//        cout << -dist[N - 1] << endl;
//    } else {
//        cout << "inf" << endl;
//    }

    return 0;
}


//by The_One_Solver
#include<bits/stdc++.h>
using namespace std;
long long  n,m,c,h,a,b,d;
int main()
{
  cin>>a>>b>>c;
  while(m<700)
  {    n=a,d=b,h=c;
      a=(d/2)+(h/2);
      b=(n/2)+(h/2);
      c=(d/2)+(n/2);
      m++;
      if(a%2==1||b%2==1||c%2==1)break;

  }
  if(m<700)
  cout<<m;
  else cout<<-1;
    return 0;
}

Score : 300 points

Problem Statement

Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below:

Each person simultaneously divides his cookies in half and gives one half to each of the other two persons.

This action will be repeated until there is a person with odd number of cookies in hand.

How many times will they repeat this action?
Note that the answer may not be finite.

Constraints

1 ≤ A,B,C ≤ 10^9

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times the action will be performed by the three people, if this number is finite.
If it is infinite, print -1 instead.

Sample Input 1

4 12 20

Sample Output 1

3

Initially, Takahashi, Aoki and Snuke have 4, 12 and 20 cookies. Then,

After the first action, they have 16, 12 and 8.

After the second action, they have 10, 12 and 14.

After the third action, they have 13, 12 and 11.

Now, Takahashi and Snuke have odd number of cookies, and therefore the answer is 3.

Sample Input 2

14 14 14

Sample Output 2

-1

Sample Input 3

454 414 444

Sample Output 3

1


#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")

#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/rope>

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;

typedef long long ll;
typedef long double ld;
typedef complex<ld> cd;

typedef pair<int, int> pi;
typedef pair<ll,ll> pl;
typedef pair<ld,ld> pd;

typedef vector<int> vi;
typedef vector<ld> vd;
typedef vector<ll> vl;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<cd> vcd;

template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>;

#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define F0R(i, a) for (int i = 0; i < (a); i++)
#define FORd(i,a,b) for (int i = (b)-1; i >= (a); i--)
#define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--)
#define trav(a, x) for (auto& a : x)

#define mp make_pair
#define pb push_back
#define f first
#define s second
#define lb lower_bound
#define ub upper_bound

#define sz(x) (int)x.size()
#define beg(x) x.begin()
#define en(x) x.end()
#define all(x) beg(x), en(x)
#define resz resize

const int MOD = 1000000007;
const ll INF = 1e18;
const int MX = 100001;
const ld PI = 4*atan((ld)1);

template<class T> void ckmin(T &a, T b) { a = min(a, b); }
template<class T> void ckmax(T &a, T b) { a = max(a, b); }

namespace io {
    // TYPE ID (StackOverflow)

    template<class T> struct like_array : is_array<T>{};
    template<class T, size_t N> struct like_array<array<T,N>> : true_type{};
    template<class T> struct like_array<vector<T>> : true_type{};
    template<class T> bool is_like_array(const T& a) { return like_array<T>::value; }

    // I/O

    void setIn(string s) { freopen(s.c_str(),"r",stdin); }
    void setOut(string s) { freopen(s.c_str(),"w",stdout); }
    void setIO(string s = "") {
        ios_base::sync_with_stdio(0); cin.tie(0);
        if (sz(s)) { setIn(s+".in"), setOut(s+".out"); }
    }

    // INPUT

    template<class T> void re(T& x) { cin >> x; }
    template<class Arg, class... Args> void re(Arg& first, Args&... rest);
    void re(double& x) { string t; re(t); x = stod(t); }
    void re(ld& x) { string t; re(t); x = stold(t); }

    template<class T> void re(complex<T>& x);
    template<class T1, class T2> void re(pair<T1,T2>& p);
    template<class T> void re(vector<T>& a);
    template<class T, size_t SZ> void re(array<T,SZ>& a);

    template<class Arg, class... Args> void re(Arg& first, Args&... rest) { re(first); re(rest...); }
    template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = cd(a,b); }
    template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); }
    template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
    template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }

    // OUTPUT

    template<class T1, class T2> ostream& operator<<(ostream& os, const pair<T1,T2>& a) {
        os << '{' << a.f << ", " << a.s << '}'; return os;
    }
    template<class T> ostream& printArray(ostream& os, const T& a, int SZ) {
        os << '{';
        F0R(i,SZ) {
            if (i) {
                os << ", ";
                if (is_like_array(a[i])) cout << "\n";
            }
            os << a[i];
        }
        os << '}';
        return os;
    }
    template<class T, size_t SZ> ostream& operator<<(ostream& os, const array<T,SZ>& a) {
        return printArray(os,a,SZ);
    }
    template<class T> ostream& operator<<(ostream& os, const vector<T>& a) {
        return printArray(os,a,sz(a));
    }
    template<class T> ostream& operator<<(ostream& os, const set<T>& a) {
        os << vector<T>(all(a)); return os;
    }
    template<class T1, class T2> ostream& operator<<(ostream& os, const map<T1,T2>& a) {
        os << vector<pair<T1,T2>>(all(a)); return os;
    }

    template<class T> void pr(const T& x) { cout << x << '\n'; }
    template<class Arg, class... Args> void pr(const Arg& first, const Args&... rest) {
        cout << first << ' '; pr(rest...);
    }
}

using namespace io;

int A,B,C;

int main() {
    // you should actually read the stuff at the bottom
    re(A,B,C);
    if (A == B && B == C && C == A && A % 2 == 0) {
        pr(-1);
        exit(0);
    }
    int ans = 0;
    while (A % 2 == 0 && B % 2 == 0 && C % 2 == 0) {
        int a = (A+B)/2, b = (B+C)/2, c = (C+A)/2;
        swap(A,a), swap(B,b), swap(C,c);
        ans ++;
    }
    pr(ans);
    // you should actually read the stuff at the bottom
}

/* stuff you should look for
    * int overflow, array bounds
    * special cases (n=1?), set tle
    * do smth instead of nothing and stay organized
*/


#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b, c;
  int aa, bb, cc;
  int ans = 0;
  cin >> a >> b >> c;
  aa = a;
  bb = b;
  cc = c;
  if (a == b && b == c) {
    cout << -1 << endl;
    return 0;
  }
  while (aa % 2 == 0 && bb % 2 == 0 && cc % 2 == 0) {
    a = (bb + cc) / 2;
    b = (cc + aa) / 2;
    c = (aa + bb) / 2;
    aa = a;
    bb = b;
    cc = a;
    ans++;
  }
  cout << ans << endl;
}


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

#define mp make_pair
#define pb push_back

using namespace std;

typedef pair<const int, int> pii;

const int MAXN = 1e5 + 1;
const int inf = 1e9 + 5;
const long double eps = 1e-8;

vector<int> g[MAXN];

void removeNode(map<int, int> &q, int v) {
    for (int i = 0; i < g[v].size(); i++) {
        if (q.find(g[v][i]) != q.end()) {
            q[g[v][i]]--;
        }
    }
    q.erase(v);
}

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

    int n;
    cin >> n;
    for (int i = 0; i < n - 1; i++) {
        int a, b;
        cin >> a >> b;
        a--, b--;
        g[a].pb(b);
        g[b].pb(a);
    }

    map<int, int> q;

    for (int i = 0; i < n; i++)
        q[i] = g[i].size();

    while (!q.empty()) {
        pii p = *(q.begin());
        if (p.second == 0) {
            cout << "First";
            return 0;
        }
        if (p.second > 1) {
            cout << "Second";
            return 0;
        }
        for (int i = 0; i < g[p.first].size(); i++) {
            if (q.find(g[p.first][i]) != q.end()) {
                removeNode(q, g[p.first][i]);
            }
        }
        q.erase(p.first);
    }

    cout << "Second";

    return 0;
}

Score : 900 points

Problem Statement

There is a tree with N vertices numbered 1 through N.
The i-th of the N-1 edges connects vertices a_i and b_i.

Initially, each vertex is uncolored.

Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi:

Select a vertex that is not painted yet.

If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki.

Then, after all the vertices are colored, the following procedure takes place:

Repaint every white vertex that is adjacent to a black vertex, in black.

Note that all such white vertices are repainted simultaneously, not one at a time.

If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins.
Determine the winner of the game, assuming that both persons play optimally.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i,b_i ≤ N

a_i ≠ b_i

The input graph is a tree.

Input

Input is given from Standard Input in the following format:

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

Output

Print First if Takahashi wins; print Second if Aoki wins.

Sample Input 1

3
1 2
2 3

Sample Output 1

First

Below is a possible progress of the game:

First, Takahashi paint vertex 2 white.

Then, Aoki paint vertex 1 black.

Lastly, Takahashi paint vertex 3 white.

In this case, the colors of vertices 1, 2 and 3 after the final procedure are black, black and white, resulting in Takahashi's victory.

Sample Input 2

4
1 2
2 3
2 4

Sample Output 2

First

Sample Input 3

6
1 2
2 3
3 4
2 5
5 6

Sample Output 3

Second


#define _GLIBCXX_IOSTREAM
#include<bits/stdc++.h>

typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef double lf;
typedef long double llf;
typedef std::pair<int,int> pii;

#define xx first
#define yy second

template<typename T> inline T max(T a,T b){return a>b?a:b;}
template<typename T> inline T min(T a,T b){return a<b?a:b;}
template<typename T> inline T abs(T a){return a>0?a:-a;}
template<typename T> inline bool repr(T &a,T b){return a<b?a=b,1:0;}
template<typename T> inline bool repl(T &a,T b){return a>b?a=b,1:0;}
template<typename T> inline T gcd(T a,T b){T t;if(a<b){while(a){t=a;a=b%a;b=t;}return b;}else{while(b){t=b;b=a%b;a=t;}return a;}}
template<typename T> inline T sqr(T x){return x*x;}
#define mp(a,b) std::make_pair(a,b)
#define pb push_back
#define I inline
#define mset(a,b) memset(a,b,sizeof(a))
#define mcpy(a,b) memcpy(a,b,sizeof(a))

#define fo0(i,n) for(int i=0,i##end=n;i<i##end;i++)
#define fo1(i,n) for(int i=1,i##end=n;i<=i##end;i++)
#define fo2(i,n) for(int i=2,i##end=n;i<=i##end;i++)
#define fo(i,a,b) for(int i=a,i##end=b;i<=i##end;i++)
#define fd0(i,n) for(int i=(n)-1;~i;i--)
#define fd1(i,n) for(int i=n;i;i--)
#define fd(i,a,b) for(int i=a,i##end=b;i>=i##end;i--)
#define foe(i,x)for(__typeof(x.end())i=x.begin();i!=x.end();++i)

struct Cg{I char operator()(){return getchar();}};
struct Cp{I void operator()(char x){putchar(x);}};
#define OP operator
#define RT return *this;
#define RX x=0;char t=P();while((t<'0'||t>'9')&&t!='-')t=P();bool f=0;\
if(t=='-')t=P(),f=1;x=t-'0';for(t=P();t>='0'&&t<='9';t=P())x=x*10+t-'0'
#define RL if(t=='.'){lf u=0.1;for(t=P();t>='0'&&t<='9';t=P(),u*=0.1)x+=u*(t-'0');}if(f)x=-x
#define RU x=0;char t=P();while(t<'0'||t>'9')t=P();x=t-'0';for(t=P();t>='0'&&t<='9';t=P())x=x*10+t-'0'
#define TR *this,x;return x;
I bool IS(char x){return x==10||x==13||x==' ';}template<typename T>struct Fr{T P;I Fr&OP,(int &x)
{RX;if(f)x=-x;RT}I OP int(){int x;TR}I Fr&OP,(ll &x){RX;if(f)x=-x;RT}I OP ll(){ll x;TR}I Fr&OP,(char &x)
{for(x=P();IS(x);x=P());RT}I OP char(){char x;TR}I Fr&OP,(char *x){char t=P();for(;IS(t);t=P());if(~t){for(;!IS
(t)&&~t;t=P())*x++=t;}*x++=0;RT}I Fr&OP,(lf &x){RX;RL;RT}I OP lf(){lf x;TR}I Fr&OP,(llf &x){RX;RL;RT}I OP llf()
{llf x;TR}I Fr&OP,(uint &x){RU;RT}I OP uint(){uint x;TR}I Fr&OP,(ull &x){RU;RT}I OP ull(){ull x;TR}};Fr<Cg>in;
#define WI(S) if(x){if(x<0)P('-'),x=-x;char s[S],c=0;while(x)s[c++]=x%10+'0',x/=10;while(c--)P(s[c]);}else P('0')
#define WL if(y){lf t=0.5;for(int i=y;i--;)t*=0.1;if(x>=0)x+=t;else x-=t,P('-');*this,(ll)(abs(x));P('.');if(x<0)\
x=-x;while(y--){x*=10;x-=floor(x*0.1)*10;P(((int)x)%10+'0');}}else if(x>=0)*this,(ll)(x+0.5);else *this,(ll)(x-0.5);
#define WU(S) if(x){char s[S],c=0;while(x)s[c++]=x%10+'0',x/=10;while(c--)P(s[c]);}else P('0')
template<typename T>struct Fw{T P;I Fw&OP,(int x){WI(10);RT}I Fw&OP()(int x){WI(10);RT}I Fw&OP,(uint x){WU(10);RT}
I Fw&OP()(uint x){WU(10);RT}I Fw&OP,(ll x){WI(19);RT}I Fw&OP()(ll x){WI(19);RT}I Fw&OP,(ull x){WU(20);RT}I Fw&OP()
(ull x){WU(20);RT}I Fw&OP,(char x){P(x);RT}I Fw&OP()(char x){P(x);RT}I Fw&OP,(const char *x){while(*x)P(*x++);RT}
I Fw&OP()(const char *x){while(*x)P(*x++);RT}I Fw&OP()(lf x,int y){WL;RT}I Fw&OP()(llf x,int y){WL;RT}};Fw<Cp>out;

const int N=200007;

int n,s[N],t[N],f[N],v[N];

inline bool cmp(int x,int y)
{
	return s[x]>s[y];
}

inline void modify(int x,int y)
{
	for(;x<=n;x+=x&-x)repr(f[x],y);
}

inline int query(int x)
{
	int r=0;
	for(;x;x^=x&-x)repr(r,f[x]);
	return r;
}

int main()
{
	in,n;
	fo1(i,n)in,s[i];
	fo1(i,n)t[i]=i;
	std::sort(t+1,t+n+1,cmp);
	int x=0,c;
	fo1(i,n)
	{
		modify(t[i],v[i]=query(t[i])+1);
		if(v[i]>x)x=v[i],c=1;else if(v[i]==x)c++;
		//out,v[i],'\n';
	}
	if(v[n]==x)
	{
		if(c>1)out,x+1;
		else out,x-1;
	}
	else out,x;
}

Score : 2400 points

Problem Statement

Takahashi loves sorting.

He has a permutation (p_1,p_2,...,p_N) of the integers from 1 through N. Now, he will repeat the following operation until the permutation becomes (1,2,...,N):

First, we will define high and low elements in the permutation, as follows. The i-th element in the permutation is high if the maximum element between the 1-st and i-th elements, inclusive, is the i-th element itself, and otherwise the i-th element is low.

Then, let a_1,a_2,...,a_k be the values of the high elements, and b_1,b_2,...,b_{N-k} be the values of the low elements in the current permutation, in the order they appear in it.

Lastly, rearrange the permutation into (b_1,b_2,...,b_{N-k},a_1,a_2,...,a_k).

How many operations are necessary until the permutation is sorted?

Constraints

1 ≤ N ≤ 2×10^5

(p_1,p_2,...,p_N) is a permutation of the integers from 1 through N.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print the number of operations that are necessary until the permutation is sorted.

Sample Input 1

5
3 5 1 2 4

Sample Output 1

3

The initial permutation is (3,5,1,2,4), and each operation changes it as follows:

In the first operation, the 1-st and 2-nd elements are high, and the 3-rd, 4-th and 5-th are low. The permutation becomes: (1,2,4,3,5).

In the second operation, the 1-st, 2-nd, 3-rd and 5-th elements are high, and the 4-th is low. The permutation becomes: (3,1,2,4,5).

In the third operation, the 1-st, 4-th and 5-th elements are high, and the 2-nd and 3-rd and 5-th are low. The permutation becomes: (1,2,3,4,5).

Sample Input 2

5
5 4 3 2 1

Sample Output 2

4

Sample Input 3

10
2 10 5 7 3 6 4 9 8 1

Sample Output 3

6


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

int main() {

  string a, b, c;
  cin >> a >> b >> c;

  int ai = a.size() - 1;
  int bi = b.size() - 1;

  if (a[ai] == b[0] && b[bi] == c[0]) cout << "YES" << endl;
  else cout << "NO" << endl;

}

Score : 100 points

Problem Statement

You are given three strings A, B and C. Check whether they form a word chain.

More formally, determine whether both of the following are true:

The last character in A and the initial character in B are the same.

The last character in B and the initial character in C are the same.

If both are true, print YES. Otherwise, print NO.

Constraints

A, B and C are all composed of lowercase English letters (a - z).

1 ≤ |A|, |B|, |C| ≤ 10, where |A|, |B| and |C| are the lengths of A, B and C, respectively.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

A and B form a word chain, but B and C do not.

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO


#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <queue>
using namespace std;

int main(){
    //freopen("in.txt","r",stdin);
    char A[15],B[15],C[15];
    scanf("%s%s%s",A,B,C);
    int lenA=strlen(A);
    int lenB=strlen(B);
    if(A[lenA-1]==B[0]&&B[lenB-1]==C[0]){
        printf("YES\n");
    }else printf("NO\n");
    return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
#include <cmath>
using namespace std;
typedef long long i64;
typedef long double ld;
typedef pair<i64,i64> P;
#define rep(i,s,e) for(int i = (s);i <= (e);i++)

int main()
{
    int a;
    int b;
    int c;
    cin >> a >> b >> c;

    rep(i,1,b)
    {
        if((a * i) % b == c)
        {
            cout << "YES" << endl;
            return 0;
        }
    }
    cout << "NO" << endl;

}

Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int n,w;
int maxvalue = 0;

int nowvalue = 0;
int nowweight = 0;

int value[101];
int weight[101];

int standweight = 0;
vector<int> w1, w2, w3, w4;
vector <int> s1, s2, s3, s4;
int main () {

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

    for (int i = 0; i < n; i++) {
        scanf("%d%d", weight + i, value + i);
        if (i == 0) {
            standweight = weight[i];
            w1.push_back(value[i]);
        }
        else {
            if (weight[i] == standweight) {
                w1.push_back(value[i]);
            }
            else if (weight[i] == standweight + 1){
                w2.push_back(value[i]);
            }
            else if (weight[i] == standweight + 2){
                w3.push_back(value[i]);
            }
            else if (weight[i] == standweight + 3){
                w4.push_back(value[i]);
            }
        }

    }
    sort (w1.begin(), w1.end());
    reverse (w1.begin(), w1.end());
    sort (w2.begin(), w2.end());
    reverse (w2.begin(), w2.end());
    sort (w3.begin(), w3.end());
    reverse (w3.begin(), w3.end());
    sort (w4.begin(), w4.end());
    reverse (w4.begin(), w4.end());

    s1.push_back(0);
    s2.push_back(0);
    s3.push_back(0);
    s4.push_back(0);

    int sum = 0;
    for (int i = 0; i < w1.size(); i++) {
        sum += w1[i];
        s1.push_back(sum);
    }
    sum = 0;
    for (int i = 0; i < w2.size(); i++) {
        sum += w2[i];
        s2.push_back(sum);
    }
    sum = 0;
    for (int i = 0; i < w3.size(); i++) {
        sum += w3[i];
        s3.push_back(sum);
    }
    sum = 0;
    for (int i = 0; i < w4.size(); i++) {
        sum += w4[i];
        s4.push_back(sum);
    }
    nowweight = 0;
    for (int i = 0; i <= w1.size() && i * standweight <= w; i++) {
        nowweight += i * standweight;
        for (int j = 0; j <= w2.size() && j * (standweight + 1) + nowweight <= w; j++) {
            nowweight += j * (standweight + 1);
            for (int k = 0; k <= w3.size() && k * (standweight + 2) + nowweight <= w; k++) {
                nowweight += k * (standweight + 2);

                int l = (w - nowweight) / (standweight + 3);
                if (l > w4.size()) {
                    l = w4.size();
                }
                nowvalue = s1[i] + s2[j] + s3[k] + s4[l];
                if (nowvalue > maxvalue)
                    maxvalue = nowvalue;

                nowweight -= k * (standweight + 2);
            }
            nowweight -= j * (standweight + 1);
        }
        nowweight -= i * standweight;
    }

    printf("%d", maxvalue);
}

Score : 400 points

Problem Statement

You have N items and a bag of strength W.
The i-th item has a weight of w_i and a value of v_i.

You will select some of the items and put them in the bag.
Here, the total weight of the selected items needs to be at most W.

Your objective is to maximize the total value of the selected items.

Constraints

1 ≤ N ≤ 100

1 ≤ W ≤ 10^9

1 ≤ w_i ≤ 10^9

For each i = 2,3,...,N, w_1 ≤ w_i ≤ w_1 + 3.

1 ≤ v_i ≤ 10^7

W, each w_i and v_i are integers.

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible total value of the selected items.

Sample Input 1

4 6
2 1
3 4
4 10
3 4

Sample Output 1

11

The first and third items should be selected.

Sample Input 2

4 6
2 1
3 7
4 10
3 6

Sample Output 2

13

The second and fourth items should be selected.

Sample Input 3

4 10
1 100
1 100
1 100
1 100

Sample Output 3

400

You can take everything.

Sample Input 4

4 1
10 100
10 100
10 100
10 100

Sample Output 4

0

You can take nothing.