#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;
typedef pair<ll,ll> pll;
const ll mod=1e9+7;
//const ll mod=998244353;
const ll inf=1LL<<62;

int main() {
  ll h,w,y,x;
  cin >> h >> w >> y >> x;
  if(h%y==0&&w%x==0) {
    cout << "No" << endl;
    return 0;
  }
  cout << "Yes" << endl;
  if(w%x) {
    vec s(w+1);
    for(ll i=w;i>=0;i--) {
      if(w-i<x) {
        s[i]=1;
      }
      else {
        s[i]=s[i+x]+1;
      }
    }
    s[0]=0;
    for(ll i=x;i<w;i+=y) {
      s[i]=s[i-x]-1;
    }
    vec a(w);
    for(ll i=0;i<w;i++) {
      a[i]=s[i+1]-s[i];
    }
    for(ll i=0;i<h;i++) {
      for(ll j=0;j<w;j++) {
        if(j) cout << " ";
        cout << a[j];
      }
      cout << endl;
    }
  }
  else {
    vec s(h+1);
    for(ll i=h;i>=0;i--) {
      if(w-i<y) {
        s[i]=1;
      }
      else {
        s[i]=s[i+y]+1;
      }
    }
    s[0]=0;
    for(ll i=y;i<h;i+=y) {
      s[i]=s[i-y]-1;
    }
    vec a(h);
    for(ll i=0;i<h;i++) {
      a[i]=s[i+1]-s[i];
    }
    for(ll i=0;i<h;i++) {
      for(ll j=0;j<w;j++) {
        if(j) cout << " ";
        cout << a[i];
      }
      cout << endl;
    }
  }
}

Score : 700 points

Problem Statement

You are given four integers: H, W, h and w (1 ≤ h ≤ H, 1 ≤ w ≤ W).
Determine whether there exists a matrix such that all of the following conditions are held, and construct one such matrix if the answer is positive:

The matrix has H rows and W columns.

Each element of the matrix is an integer between -10^9 and 10^9 (inclusive).

The sum of all the elements of the matrix is positive.

The sum of all the elements within every subrectangle with h rows and w columns in the matrix is negative.

Constraints

1 ≤ h ≤ H ≤ 500

1 ≤ w ≤ W ≤ 500

Input

Input is given from Standard Input in the following format:

H W h w

Output

If there does not exist a matrix that satisfies all of the conditions, print No.

Otherwise, print Yes in the first line, and print a matrix in the subsequent lines in the following format:

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

Here, a_{ij} represents the (i,\ j) element of the matrix.

Sample Input 1

3 3 2 2

Sample Output 1

Yes
1 1 1
1 -4 1
1 1 1

The sum of all the elements of this matrix is 4, which is positive.
Also, in this matrix, there are four subrectangles with 2 rows and 2 columns as shown below. For each of them, the sum of all the elements inside is -1, which is negative.

Sample Input 2

2 4 1 2

Sample Output 2

No

Sample Input 3

3 4 2 3

Sample Output 3

Yes
2 -5 8 7
3 -5 -4 -5
2 1 -1 7


#include <iostream>
using namespace std;

int main(){
  int n,m,x,y;
  cin >> n >> m >> x >> y;
  int a=(n/x)*(m/y);
  int b=n*m-a;
  if(n%x==0&&m%y==0){
    cout << "No" << endl;
  }
  else{
    cout << "Yes" << endl;
    int c=1e9/b;
    b*=c;
    for(int i=1;i<=n;i++){
      for(int j=1;j<=m;j++){
        if(i%x==0&&j%y==0){
          cout << -b;
        }
        else{
          cout << (b-1)/(x*y-1);
        }
        cout << " ";
      }
      cout << endl;
    }
  }
}

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

Submitted source-code file size, in bytes.

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

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


#include<cstdio>
using namespace std;
const int maxn = 1000000000;
int main()
{
	int a,b,c,d;
	scanf("%d%d%d%d",&a,&b,&c,&d);
	if(a % c == 0 && b % d == 0)
	{
		printf("No\n");
	}
	else
	{
		int nz = maxn / (c * d - 1);
		int nf = (c * d - 1) * nz + 1;
		printf("Yes\n");
		for(int i = 1;i <= a;++i)
		{
			for(int j = 1;j <= b;++j)
			{
				if(i % c == 0 && j % d == 0)
					printf("-%d ",nf);
				else
					printf("%d ",nz);
			}
			putchar('\n');
		}
	}
	return 0;
}


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

inline bool chmin(T &a, T b)
{
    if (a > b)
    {
        a = b;
        return true;
    }
    return false;
}
template <class T>
inline bool chmax(T &a, T b)
{
    if (a < b)
    {
        a = b;
        return true;
    }
    return false;
}
const long long INF = 1LL << 60;
int cnt = 0;
int main()
{
    int r, g, b;
    cin >> r >> g >> b;
    int x = 100 * r + 10 * g + b;
    if (x % 4 == 0)
    {
        cout << "YES" << endl;
    }
    else
    {
        cout << "No" << endl;
    }
    return 0;
}

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<iostream>
using namespace std;
int main()
{
    int a,b,c;
    cin>>a>>b>>c;
      if(((a*100)+(b*10)+c)%2==0)
      cout<<"Yes";
      else
      cout<<"No";
           }


Score : 300 points

Problem Statement

In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows:

Rating 1-399 : gray

Rating 400-799 : brown

Rating 800-1199 : green

Rating 1200-1599 : cyan

Rating 1600-1999 : blue

Rating 2000-2399 : yellow

Rating 2400-2799 : orange

Rating 2800-3199 : red

Other than the above, a person whose rating is 3200 or higher can freely pick his/her color, which can be one of the eight colors above or not.

Currently, there are N users who have participated in a contest in AtCoder, and the i-th user has a rating of a_i.

Find the minimum and maximum possible numbers of different colors of the users.

Constraints

1 ≤ N ≤ 100

1 ≤ a_i ≤ 4800

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 minimum possible number of different colors of the users, and the maximum possible number of different colors, with a space in between.

Sample Input 1

4
2100 2500 2700 2700

Sample Output 1

2 2

The user with rating 2100 is "yellow", and the others are "orange". There are two different colors.

Sample Input 2

5
1100 1900 2800 3200 3200

Sample Output 2

3 5

The user with rating 1100 is "green", the user with rating 1900 is blue and the user with rating 2800 is "red".

If the fourth user picks "red", and the fifth user picks "blue", there are three different colors. This is one possible scenario for the minimum number of colors.

If the fourth user picks "purple", and the fifth user picks "black", there are five different colors. This is one possible scenario for the maximum number of colors.

Sample Input 3

20
800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990

Sample Output 3

1 1

All the users are "green", and thus there is one color.


#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
#include<map>
#include<cstdio>
#include<stack>
#include<queue>
#include<fstream>
#include<cstdio>

using namespace std;
#define ok1 printf("ok1\n");
#define ok2 printf("ok2\n");
#define M 1000000
#define rep(i,n) for(int i=0;i<n;i++)
#define REP(i,s,n) for(int i=(s);i<(n);i++)
#define repr(i,n) for(int i=n-1;i>=0;i--)
#define REPR(i,s,n) for(int i=(s);i>=(g);(i)--)
#define all(a) (a).begin(),(a).end()
#define reall(a) (a).rbegin(),(a).rend()
#define pb push_back
#define MIN(a,b) a=min((a),(b))
#define MAX(a,b) a=max((a),(b))
#define SIZE(v) (int)v.size()

typedef vector<int> vi;
typedef vector<string> vs;
typedef long long ll;
typedef vector<ll> vll;

#ifdef TESTING
#define DEBUG fprintf(stderr,"====TESTING====\n")
#define VALUE(x) cerr << "The value of " << #x << " is " << x << endl
#define debug(...) fprintf(stderr, __VA_ARGS__)
#else
#define DEBUG
#define VALUE(x)
#define debug(...)
#endif
/*
inline string IntToString(ll a) {
	char x[100];
	sprintf_s(x, "%lld", a); string s = x;
	return s;
}

inline ll StringToInt(string a) {
	char x[100]; ll res;
	strcpy_s(x, a.c_str()); sscanf_s(x, "%lld", &res);
	return res;
}
*/

inline string uppercase(string s) {
	int n = SIZE(s);
	rep(i, n) if (s[i] >= 'a' && s[i] <= 'z') s[i] = s[i] - 'a' + 'A';
	return s;
}

inline string lowercase(string s) {
	int n = SIZE(s);
	rep(i, n) if (s[i] >= 'A' && s[i] <= 'Z') s[i] = s[i] - 'A' + 'a';
	return s;
}

int main()
{
	int n,ans = 0;
	cin >> n;
	vi v(n),a(8);
	int ex = 0;
	for (int i = 0; i < n; i++) {
		cin >> v[i];
		if (v[i] >= 1 && v[i] < 400)
			a[0]++;
		if (v[i] >= 400 && v[i] < 800)
			a[1]++;
		if (v[i] >= 800 && v[i] < 1200)
			a[2]++;
		if (v[i] >= 1200 && v[i] < 1600)
			a[3]++;
		if (v[i] >= 1600 && v[i] < 2000)
			a[4]++;
		if (v[i] >= 2000 && v[i] < 2400)
			a[5]++;
		if (v[i] >= 2400 && v[i] < 2700)
			a[6]++;
		if (v[i] >= 2800 && v[i] < 3200)
			a[7]++;
		if (v[i] >= 3200)
			ex++;
	}
	rep(i, 8) {
		if (a[i] != 0)
			ans++;
		//cout << a[i] << " ";
	}
	//cout << endl;
	//cout << ex << endl;//(to debug)
	cout << ans << " " << ans + ex << endl;
 	return 0;
}


#include <iostream>
#include <vector>

using namespace std;

typedef long long ll;
typedef vector<ll> vi;
typedef vector<vi> vvi;

int main(int argc, char ** argv) {
	ll n;
	cin >> n;
	vi a(n,0);
	vector<bool> col(8, false);
	ll num_pros = 0;
	for(ll i=0; i<n; i++) {
		cin >> a[i];
		if(a[i] < 3200) col[a[i]/400] = true;
		else num_pros++;
	}
	ll min_cols = 0;
	for(ll i=0; i<8; i++) if(col[i]) min_cols++;
	if(min_cols == 0) cout << 1 << " " << num_pros << endl;
	else cout << min_cols << " " << min_cols+num_pros << endl;
	return 0;
}


#include <bits/stdc++.h>
#define rep(i, a, n) for(int i = a; i < n; i++)
#define repb(i, a, b) for(int i = a; i >= b; i--)
#define all(a) a.begin(), a.end()
#define int long long
#define chmax(x, y) x = max(x, y)
#define chmin(x, y) x = min(x, y)
using namespace std;
typedef pair<int, int> P;
const int mod = 1000000007;

signed main(){
    int a, b;
    cin >> a >> b;
    if(a + b >= 10) cout << "error" << endl;
    else cout << a + b << 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 <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

int main(void) {

	string s;
	int a[26] = { 0 }, co = 0;

	cin >> s;

	for (int i = 0; i < s.size(); i++) {
		if (a[(int)s[i] - 'a'] != 0) {
			co = 1;
			break;
		}
		a[(int)s[i] - 'a']++;
	}

	if (co == 0) cout << "yes" << endl;
	else cout << "no" << endl;

	return 0;

}

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters. Determine whether all the characters in S are different.

Constraints

2 ≤ |S| ≤ 26, where |S| denotes the length of S.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If all the characters in S are different, print yes (case-sensitive); otherwise, print no.

Sample Input 1

uncopyrightable

Sample Output 1

yes

Sample Input 2

different

Sample Output 2

no

Sample Input 3

no

Sample Output 3

yes


#include<iostream>
#include<vector>
#include<algorithm>
#include <string>
using namespace std;
int main()
{
    int n,S,ans=0,hyouka;
	vector<int> s;
    cin >> n;
    for(int i=0;i<n;i++)
	{
		cin>>S;
		s.push_back(S);
		ans+=s[i];
	}
	sort(s.begin(),s.end());
	for(int i=0;i<n;i++)
	{
		if(ans%10==0&&s[i]%10!=0)
			ans-=s[i];
		else
		{
			cout<<ans;
			return 0;
		}
	}
	cout<<"0";
    return 0;
}

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 <algorithm>
#include <cstdio>
#include <iostream>
#include <cfloat>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <queue>
#include <sstream>
#include <stack>
#include <time.h>
#include <vector>
#include <complex>
#include <map>
#include <set>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
#include  <list>
#include  <utility>
#include  <memory>
#include  <cstring>
#include  <fstream>
#include  <numeric>
using namespace std;
long long monst[100003];
int main(){
  long long n,a,b,ans=0;
  cin>>n>>a>>b;
  for (long long i=0;i<n;i++)
    cin>>monst[i];
  sort (monst,monst+n);
  while (monst[n-1]>0){
    ans++;
  	monst[n-1]-=a;
  	for (long long i=n-2;i>=0;i--) monst[i]-=b;
  	sort (monst,monst+n);
  }
  cout<<ans;
  return 0;
}

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<cstdio>
#include<algorithm>
long long pow10[15];
long long mapL[1000005]; int sizeL = -1;
long long mapR[1000005]; int sizeR = -1;
//org: a[n],a[n-1]...a[2],a[1]
//rev: a[1],a[2]...a[n-1],a[n]
//dfs on rev, a[n]!=0
//end of left is (n+1)/2

void dfsL(int p,int n,long long sum){
    int mid = (n+1)/2;
    if(p==mid+1) mapL[++sizeL] = sum;
    else{
        for(long long i = 0; i <= 9; i++){
            long long add = i*pow10[n-p], minus = i*pow10[p-1];
            dfsL(p+1,n,sum+add-minus);
        }
    }
}

void dfsR(int p,int n,long long sum){
    if(p==n+1) mapR[++sizeR] = sum;
    else{
        int start = 0;
        if(p==n) start = 1;
        for(long long i = start; i <= 9; i++){
            long long add = i*pow10[n-p], minus = i*pow10[p-1];
            dfsR(p+1,n,sum+add-minus);
        }
    }
}

int getFirst(long long u,long long map[],int size){
    int L = 1, R = size;
    int res = -1;
    while(L<=R){
        int M = (L+R)/2;
        if(map[M]>=u){
            res = M;
            R = M-1;
        }
        else L = M+1;
    }
    return res;
}

int getLast(long long u,long long map[],int size){
    int L = 1, R = size;
    int res = -1;
    while(L<=R){
        int M = (L+R)/2;
        if(map[M]<=u){
            res = M;
            L = M+1;
        }
        else R = M-1;
    }
    return res;
}

int main(){
    pow10[0] = 1;
    for(int i = 1; i <= 13; i++) pow10[i] = pow10[i-1]*10ll;
    long long d;
    scanf("%lld",&d);
    long long ans = 0;
    for(int i = 1; i <= 10; i++){
        sizeL = sizeR = 0;
        int mid = (i+1)/2;
        dfsL(1,i,0);
        dfsR(mid+1,i,0);
        std::sort(mapL+1,mapL+1+sizeL);
        std::sort(mapR+1,mapR+1+sizeR);
        for(int j = 1; j <= sizeL; j++){
            long long u = mapL[j];
            long long need = d-u;
            int lower = getFirst(need,mapR,sizeR), upper = getLast(need,mapR,sizeR);
            if(lower!=-1 && upper!=-1 && mapR[lower]==need && mapR[upper]==need) ans += (long long)(upper-lower+1);
        }
    }
    printf("%lld\n",ans);
    return 0;
}

Score : 800 points

Problem Statement

For a positive integer n, we denote the integer obtained by reversing the decimal notation of n (without leading zeroes) by rev(n). For example, rev(123) = 321 and rev(4000) = 4.

You are given a positive integer D. How many positive integers N satisfy rev(N) = N + D?

Constraints

D is an integer.

1 ≤ D < 10^9

Input

Input is given from Standard Input in the following format:

D

Output

Print the number of the positive integers N such that rev(N) = N + D.

Sample Input 1

63

Sample Output 1

2

There are two positive integers N such that rev(N) = N + 63: N = 18 and 29.

Sample Input 2

75

Sample Output 2

0

There are no positive integers N such that rev(N) = N + 75.

Sample Input 3

864197532

Sample Output 3

1920


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

#define FOR(i,l,r) for(int i = (int) (l);i < (int) (r);i++)
template<typename T> bool chmax(T& a,const T& b){ return a < b ? (a = b,true) : false; }
template<typename T> bool chmin(T& a,const T& b){ return b < a ? (a = b,true) : false; }
typedef long long ll;

int N;
ll D;
ll powTable [15];
ll dp [20] [2];

int digit_count(ll x)
{
	int res = 0;
	do{
		res++;
	}while(x /= 10);
	return res;
}

ll dfs(int n,vector<int>& v)
{
	ll res = 0;
	if(n == N / 2){
		ll sum = 0;
		FOR(i,0,n){
			sum += v [i] * (powTable [N - 1 - i] - powTable [i]);
		}
		if(sum == D){
			memset(dp,0,sizeof(dp));
			int M = N / 2;
			dp [0] [1] = 1;
			FOR(i,0,M) FOR(j,0,2){
				FOR(k,0,10){
					if(k + v [i] >= 0 && k + v [i] <= 9){
						if(j == 1 && k == 0) continue;
						dp [i + 1] [0] += dp [i] [j];
					}
				}
			}
			if(N % 2){
				dp [M] [0] *= 10;
			}
			res = dp [M] [0];
			return res;
		}
		return 0;
	}
	FOR(i,-9,10){
		v.push_back(i);
		res += dfs(n + 1,v);
		v.pop_back();
	}
	return res;
}

int main()
{
	scanf("%lld",&D);

	N = digit_count(D);
	powTable [0] = 1;
	for(int i = 1;i < 15;i++){
		powTable [i] = powTable [i - 1] * 10;
	}
	vector<int> v;
	ll ans = dfs(0,v);

	printf("%lld\n",ans);

	return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
const int N=2e5+10;
const int inf=1e9;
const int mod=1e9+7;
typedef pair<int,int> pii;
int gi() {
    int x=0,o=1;char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
    if(ch=='-') o=-1,ch=getchar();
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*o;
}
int n,st[N],pre[N],suf[N],top=0,f[N],sum[N];
pii a[N];
vector<int> v[N];
int main() {
    cin>>n;
    for(int i=1;i<=n;i++) a[i].fi=gi(),a[i].se=gi(),st[++top]=a[i].se;
    sort(st+1,st+top+1);
    for(int i=1;i<=n;i++) a[i].se=lower_bound(st+1,st+top+1,a[i].se)-st;
    sort(a+1,a+n+1);
    for(int i=1;i<=n;i++) pre[i]=max(pre[i-1],a[i].se);
    suf[n+1]=inf;
    for(int i=n;i;i--) suf[i]=min(suf[i+1],a[i].se);
    for(int i=1;i<=n;i++) v[pre[i]].pb(suf[i]);
    f[0]=sum[0]=1;
    for(int i=1;i<=n;i++) {
        sum[i]=sum[i-1];
        for(int j:v[i]) {
            f[i]=(f[i]+sum[i])%mod;
            if(j>=2) f[i]=(f[i]-sum[j-2]+mod)%mod;
            sum[i]=(sum[i-1]+f[i])%mod;
        }
    }
    printf("%d\n",f[n]);
    return 0;
}
//orzgzy
//鸡贼明年进队超稳

Score : 1200 points

Problem Statement

Takahashi is an expert of Clone Jutsu, a secret art that creates copies of his body.

On a number line, there are N copies of Takahashi, numbered 1 through N.
The i-th copy is located at position X_i and starts walking with velocity V_i in the positive direction at time 0.

Kenus is a master of Transformation Jutsu, and not only can he change into a person other than himself, but he can also transform another person into someone else.

Kenus can select some of the copies of Takahashi at time 0, and transform them into copies of Aoki, another Ninja.
The walking velocity of a copy does not change when it transforms.
From then on, whenever a copy of Takahashi and a copy of Aoki are at the same coordinate, that copy of Takahashi transforms into a copy of Aoki.

Among the 2^N ways to transform some copies of Takahashi into copies of Aoki at time 0, in how many ways will all the copies of Takahashi become copies of Aoki after a sufficiently long time?
Find the count modulo 10^9+7.

Constraints

1 ≤ N ≤ 200000

1 ≤ X_i,V_i ≤ 10^9(1 ≤ i ≤ N)

X_i and V_i are integers.

All X_i are distinct.

All V_i are distinct.

Input

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

N
X_1 V_1
:
X_N V_N

Output

Print the number of the ways that cause all the copies of Takahashi to turn into copies of Aoki after a sufficiently long time, modulo 10^9+7.

Sample Input 1

3
2 5
6 1
3 7

Sample Output 1

6

All copies of Takahashi will turn into copies of Aoki after a sufficiently long time if Kenus transforms one of the following sets of copies of Takahashi into copies of Aoki: (2), (3), (1,2), (1,3), (2,3) and (1,2,3).

Sample Input 2

4
3 7
2 9
8 16
10 8

Sample Output 2

9


#include <iostream>
#include <vector>

using namespace std;

int main()
{
  int par[] = {-1, 1, 2, 1, 4, 1, 4, 1, 1, 4, 1, 4, 1};
  int x, y;
  cin >> x >> y;

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

  return 0;
}

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

int main(void)
{
	int N, M;

	std::cin >> N >> M;

	int a[M], b[M];
	int ans[N] = {0};

	for(int i = 0; i < M; i++){
		std::cin >> a[i] >> b[i];
		ans[a[i]-1]++;
		ans[b[i]-1]++;
	}

	for(int i = 0; i < N; i++)
		std::cout << ans[i] << std::endl;

	return EXIT_SUCCESS;
}

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2


#include <iostream>

using namespace std;

int main(int argc, char const *argv[]) {
  int n, m;
  cin >> n >> m;
  int a[m], b[m], ans[50]={0};
  for (size_t i = 0; i < m; i++) {
    cin >> a[i] >> b[i];
    ans[a[i]-1]++;
    ans[b[i]-1]++;
  }
  for (size_t i = 0; i < n; i++) cout << ans[i] << endl;;
  return 0;
}


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

const ll INF = 1e15;

struct edge {
  int u, v, cost;
};

ll dist[1010];

int main() {
  int N, M;
  cin >> N >> M;
  vector<edge> edges(M);
  for (auto &e : edges) {
    cin >> e.u >> e.v >> e.cost;
    e.u--, e.v--;
    e.cost = -e.cost;
  }

  vector<ll> dist(N, INF);
  dist[0] = 0;
  for (int i = 0; i < 2 * N; i++) {
    for (auto e : edges) {
      if (dist[e.u] == INF) continue;
      if (dist[e.u] + e.cost < dist[e.v]) {
        dist[e.v] = dist[e.u] + e.cost;
        if (i >= N - 1) dist[e.v] = -INF;
      }
    }
  }
  if (dist[N - 1] == -INF)
    cout << "inf" << endl;
  else
    cout << -dist[N - 1] << endl;
}

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;
int main(){
    int n,m;
    cin >> n >> m;
    vector<int>a(m);
    vector<int>b(m);
    vector<int>c(m);
    for(int i=0;i<m;i++){
        cin >> a[i] >> b[i] >> c[i];
    }
    vector<long>score(n+1,-999999999999);
    bool chk = true;
    int count = 0;
    score[1] = 0;
    while(chk){
        chk = false;
        count++;

        for(int i=0;i<m;i++){
            if(score[a[i]]+c[i] > score[b[i]]){
                score[b[i]] = score[a[i]] + c[i];
                chk = true;
            }
        }

        if(count > 2*m)break;
    }
    if(!chk)cout<<score[n]<<endl;
    else cout<<"inf"<<endl;
}


#include <bits/stdc++.h>
using namespace std;
struct edge {int from, to, cost; };

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

  edge es[m];
  for (int i=0; i<m; i++) {
    int a, b, c;
    cin>>a>>b>>c;
    --a;
    --b;
    edge e = {a, b, -c};
    es[i] = e;
  }
  long long d[n];
  for (int i=0; i<n; i++) d[i] = LLONG_MAX;

  d[0] = 0;
  for (int i=0; i<n; i++) {
    for (auto e: es) {
      if (d[e.from] != LLONG_MAX && d[e.to] > d[e.from] + e.cost) {
        d[e.to] = d[e.from] + e.cost;
        if (i == n - 1) {
          cout<<"inf"<<endl;
          return 0;
        }
      }
    }
  }
  cout<<-d[n-1]<<endl;

}


#include<bits/stdc++.h>
#include<iostream>
#include<cmath>
#include<vector>
#include<string>
#include<queue>
#include<set>
#include<map>
#include<algorithm>
#include<functional>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll, ll> pll;
typedef pair<ull, ull> pullull;
typedef pair<ll, int> plli;
typedef pair<int, pii> pipii;
typedef vector<vector<int> > mati;
typedef vector<vector<double> > matd;
typedef vector<ll> vll;
typedef vector<vector<ll>> vvll;
typedef vector<vector<vector<ll>>> vvvll;
typedef vector<bool> vb;
typedef vector<vector<bool>> vvb;
typedef vector<vector<vector<bool>>> vvvb;

#define FOR(i,x,y) for(ll i=(ll)x; i<(ll)y; ++i)
#define REP(i,y) FOR(i, 0, y)

template <typename T>
void vec_print(vector<T> VEC){
  REP(i, VEC.size()){
    cout << VEC[i] << " ";
  }
  cout << "\n";
};

template <typename T>
void mat_print(vector<vector<T> > MAT){
  REP(i, MAT.size()){
    REP(j, MAT[i].size()){
      cout << MAT[i][j] << " ";
    }
    cout << "\n";
  }
};

template <typename CLASS1, typename CLASS2>
class HOGE{
  public:
    CLASS1 key;
    CLASS2 value;
    HOGE(void){
      return;
    };
    HOGE(CLASS1 key, CLASS2 value){
      this->key = key;
      this->value = value;
    };
    ~HOGE(void){
      return;
    };

    void print(void){
      cout << "key : " << key << ", value : " << value << "\n";
      return;
    };

    bool operator==(const HOGE &obj){
      return (this->value == obj.value);
    };
    bool operator<(const HOGE &obj){
      return (this->value < obj.value);
    };
    bool operator>(const HOGE &obj){
      return (this->value > obj.value);
    };
};

constexpr int INF = (1<<30);
constexpr ll INFLL = 1LL<<62;
constexpr long double EPS = 1e-12;
constexpr ll MOD = (ll)((1E+9)+7);

constexpr ll MAX = 1LL<<55;

vector<vector<pair<ll, ll>>> edge;
vll dp;
vb path_flag;

void search(const ll pos, const ll tmp_cost){
  if(tmp_cost < dp[pos]) return;
  if(path_flag[pos]){
    if(dp[pos] < tmp_cost){
      dp[dp.size()-1] = MAX;
    }
    return;
  }
  path_flag[pos] = true;
  dp[pos] = max(tmp_cost, dp[pos]);
  for(auto tmp_pair : edge[pos]){
    search(tmp_pair.first, tmp_cost+tmp_pair.second);
  }
  path_flag[pos] = false;
  return;
}

int main(){
  cin.tie(0); // cut the cin and cout (default, std::flush is performed after std::cin)
  ios::sync_with_stdio(false); // cut the iostream and stdio (DON'T endl; BUT "\n";)

  ll N, M;
  cin >> N >> M;
  edge.resize(N);
  REP(i, M){
    ll a, b, c;
    cin >> a >> b >> c;
    a--;
    b--;
    pair<ll, ll> tmp(b, c);
    edge[a].push_back(tmp);
  }

  dp.resize(N, -MAX);
  path_flag.resize(N, false);

  search(0, 0);

  if(dp[N-1]==-MAX || dp[N-1]==MAX){
    cout << "inf\n";
  }else{
    cout << dp[N-1] << "\n";
  }

  return 0;
}


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

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;
typedef pair<P, ll> PPI;

#define fi first
#define se second
#define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++)
#define rep(i,n) repl(i,0,n)
#define each(itr,v) for(auto itr:v)
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<<#x"="<<x<<endl
#define mmax(x,y) (x>y?x:y)
#define mmin(x,y) (x<y?x:y)
#define maxch(x,y) x=mmax(x,y)
#define minch(x,y) x=mmin(x,y)
#define uni(x) x.erase(unique(all(x)),x.end())
#define exist(x,y) (find(all(x),y)!=x.end())
#define bcnt __builtin_popcount

#define INF INT_MAX/3

int h,w,k;
char a[810][810];
int dd[]={1,0,-1,0,1};
int si,sj;
int dist[810][810],dist2[810][810];

bool valid(int i,int j){
  return i>=0&&i<h&&j>=0&&j<w;
}

int manh(int i,int j){
  return abs(i-si)+abs(j-sj);
}

int main(){
	cin.sync_with_stdio(false);
  cin>>h>>w>>k;
  rep(i,h){
    cin>>a[i];
    rep(j,w)if(a[i][j]=='S'){
      si=i; sj=j;
      a[i][j]='.';
    }
  }
  rep(i,h)rep(j,w)dist[i][j]=INF;
  queue<PPI> que;
  que.push(PPI(P(si,sj),0));
  while(que.size()){
    PPI np=que.front(); que.pop();
    int ni=np.fi.fi, nj=np.fi.se;
    if(dist[ni][nj]!=INF)continue;
    dist[ni][nj]=np.se;
    rep(d,4){
      int pi=ni+dd[d],pj=nj+dd[d+1];
      if(valid(pi,pj)&&a[pi][pj]!='#')que.push(PPI(P(pi,pj),np.se+1));
    }
  }
  int mind=INF;
  rep(i,h){
    minch(mind,min(dist[i][0],manh(i,0)+k));
    minch(mind,min(dist[i][w-1],manh(i,w-1)+k));
  }
  rep(i,w){
    minch(mind,min(dist[0][i],manh(0,i)));
    minch(mind,min(dist[h-1][i],manh(h-1,i)));
  }
  //dbg(mind);
  cout<<ceil((double)mind/k)<<endl;
	return 0;
}

Score : 700 points

Problem Statement

Takahashi is locked within a building.

This building consists of H×W rooms, arranged in H rows and W columns.
We will denote the room at the i-th row and j-th column as (i,j). The state of this room is represented by a character A_{i,j}. If A_{i,j}= #, the room is locked and cannot be entered; if A_{i,j}= ., the room is not locked and can be freely entered.
Takahashi is currently at the room where A_{i,j}= S, which can also be freely entered.

Each room in the 1-st row, 1-st column, H-th row or W-th column, has an exit.
Each of the other rooms (i,j) is connected to four rooms: (i-1,j), (i+1,j), (i,j-1) and (i,j+1).

Takahashi will use his magic to get out of the building. In one cast, he can do the following:

Move to an adjacent room at most K times, possibly zero. Here, locked rooms cannot be entered.

Then, select and unlock at most K locked rooms, possibly zero. Those rooms will remain unlocked from then on.

His objective is to reach a room with an exit. Find the minimum necessary number of casts to do so.

It is guaranteed that Takahashi is initially at a room without an exit.

Constraints

3 ≤ H ≤ 800

3 ≤ W ≤ 800

1 ≤ K ≤ H×W

Each A_{i,j} is # , . or S.

There uniquely exists (i,j) such that A_{i,j}= S, and it satisfies 2 ≤ i ≤ H-1 and 2 ≤ j ≤ W-1.

Input

Input is given from Standard Input in the following format:

H W K
A_{1,1}A_{1,2}...A_{1,W}
:
A_{H,1}A_{H,2}...A_{H,W}

Output

Print the minimum necessary number of casts.

Sample Input 1

3 3 3
#.#
#S.
###

Sample Output 1

1

Takahashi can move to room (1,2) in one cast.

Sample Input 2

3 3 3
###
#S#
###

Sample Output 2

2

Takahashi cannot move in the first cast, but can unlock room (1,2).
Then, he can move to room (1,2) in the next cast, achieving the objective in two casts.

Sample Input 3

7 7 2
#######
#######
##...##
###S###
##.#.##
###.###
#######

Sample Output 3

2


#include <iostream>
#include <string>

using namespace std;

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

  string a, b, c;
  cin >> a >> b >> c;
  if (a.back() == b[0] && b.back() == c[0])
    cout << "YES" << endl;
  else
    cout << "NO" << endl;

  return 0;
}

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 <bits/stdc++.h>
using namespace std;

int64_t gcd(int64_t a, int64_t m);
int main(void) {
    int64_t A, B, C;
    int64_t d;

    cin >> A >> B >> C;

    // Ax mod B = C
    d = gcd(A,B);
    if( d == 1) {
        cout << "YES\n";
    } else {
        if(C % d) {
            cout << "NO\n";
        } else {
            cout << "YES\n";
        }
    }

    return 0;
}
int64_t gcd(int64_t a, int64_t m) {
    int64_t tmp;
    int64_t r;

    if(a < m) {
        tmp = a;
        a = m;
        m = tmp;
    }

    r = a % m;
    while(r!=0) {
        a = m;
        m = r;
        r = a % m;
    }

    return m;
}

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 <bits/stdc++.h>
using namespace std;
int main(){
	int A,B,C;
  	cin >> A >> B >> C;
  	bool ans = false;
  	for(int i =1;i <B;i++){
    	if(i*A%B == C)ans = true;
    }
  	if(ans)cout << "YES" << endl;
  	else cout << "NO" <<endl;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int max_n=200005;
int n,T,t[max_n];
int main(){
    scanf("%d%d",&n,&T);
    for(int i=1;i<=n;i++)scanf("%d",t+i);
    int ans=t[n]+T;
    for(int i=2;i<=n;i++){
        ans-=max(0,t[i]-(t[i-1]+T));
    }
    printf("%d\n",ans);
    return 0;
}

Score : 300 points

Problem Statement

In a public bath, there is a shower which emits water for T seconds when the switch is pushed.

If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for T seconds.
Note that it does not mean that the shower emits water for T additional seconds.

N people will push the switch while passing by the shower.
The i-th person will push the switch t_i seconds after the first person pushes it.

How long will the shower emit water in total?

Constraints

1 ≤ N ≤ 200,000

1 ≤ T ≤ 10^9

0 = t_1 < t_2 < t_3 < , ..., < t_{N-1} < t_N ≤ 10^9

T and each t_i are integers.

Input

Input is given from Standard Input in the following format:

N T
t_1 t_2 ... t_N

Output

Assume that the shower will emit water for a total of X seconds. Print X.

Sample Input 1

2 4
0 3

Sample Output 1

7

Three seconds after the first person pushes the water, the switch is pushed again and the shower emits water for four more seconds, for a total of seven seconds.

Sample Input 2

2 4
0 5

Sample Output 2

8

One second after the shower stops emission of water triggered by the first person, the switch is pushed again.

Sample Input 3

4 1000000000
0 1000 1000000 1000000000

Sample Output 3

2000000000

Sample Input 4

1 1
0

Sample Output 4

1

Sample Input 5

9 10
0 3 5 7 100 110 200 300 311

Sample Output 5

67


#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
#ifndef FAST_IO
 #define IOS ios_base::sync_with_stdio(false);cin.tie(nullptr);
#endif

#define int long long
#define FILE_IO freopen("input.txt","r",stdin)/#define int long long
#define f first
#define s second
#define endl '\n'
#define all(c) c.begin(),c.end()
#define bp __builtin_popcount
#define debug(x) cerr << #x << " = " << x << endl;

const int MOD = 1e9 + 7;
const int INF = 1000000000;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
template <typename T>void print(T t){for(auto &it : t)cout<<it<<" ";}
inline int powerexp(int a, int b, int m = MOD){ int res = 1;while(b){if(b&1)res = res * a % m;a = a * a % m,b >>= 1;}return res % m;}
inline int modinv(int a){ return powerexp(a,MOD-2,MOD);}
inline int lcm(int a, int b){ int g = __gcd(a,b);return a/g*b;}
inline int add(int x, int y){ x += y; if (x >= MOD) x -=  MOD; return x;}
inline int mul(int x, int y){ return (x * 1ll * y) % MOD;}
inline int sub(int x, int y){ x -= y; if (x<0) x += MOD; return x ;}

//-------------------< start here >-------------------------//

void solve(){
    string a, b;
    cin >> a >> b;
    if (a == b) cout << "EQUAL" << endl;
    else if (a < b) cout << "LESS" << endl;
    else cout << "GREATER" << endl;
}

//-----------------------------
//comment from here for TOPCODER
int32_t main(){
   IOS;
   solve();
   //find();
   #ifdef LOCAL_DEFINE
   cerr << "time elapsed " << (double)clock()/CLOCKS_PER_SEC << endl;
   #endif
}

Score : 200 points

Problem Statement

You are given two positive integers A and B. Compare the magnitudes of these numbers.

Constraints

1 ≤ A, B ≤ 10^{100}

Neither A nor B begins with a 0.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print GREATER if A>B, LESS if A<B and EQUAL if A=B.

Sample Input 1

36
24

Sample Output 1

GREATER

Since 36>24, print GREATER.

Sample Input 2

850
3777

Sample Output 2

LESS

Sample Input 3

9720246
22516266

Sample Output 3

LESS

Sample Input 4

123456789012345678901234567890
234567890123456789012345678901

Sample Output 4

LESS


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

int n, option;
ll ch[2];

int main() {
    cin.sync_with_stdio(0); cin.tie(0);
    cin >> n;
    vector<ll> a(n);
    for (auto& i : a) cin >> i;

    for (int i = 0; i < n; ++i) {
        if (a[i] >= 0)
            ch[i % 2] += a[i] + 1;
    }

    // Which is going to be negative
    option = (ch[0] >= ch[1]);
    ll cur = 0, ans = 0;
    for (int i = 0; i < n; ++i) {
        cur += a[i];
        if (i % 2 == option && cur >= 0) {
            ans += cur + 1;
            cur = -1;
        } else if (i % 2 != option && cur <= 0) {
            ans += -1ll * (cur - 1);
            cur = 1;
        }
    }
    cout << ans;
}

Score : 300 points

Problem Statement

You are given an integer sequence of length N. The i-th term in the sequence is a_i.
In one operation, you can select a term and either increment or decrement it by one.

At least how many operations are necessary to satisfy the following conditions?

For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.

For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Constraints

2 ≤ n ≤ 10^5

|a_i| ≤ 10^9

Each 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 minimum necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

For example, the given sequence can be transformed into 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1, respectively, which satisfy the conditions.

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8


#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iomanip>

using namespace std;

long long MOD = 1000000007;

int main(){
    long long X, Y;
    cin >> X >> Y;
    if(abs(X-Y)<=1){
        cout << "Brown" << endl;
    }else{
        cout << "Alice" << endl;
    }
}

Score : 500 points

Problem Statement

Alice and Brown loves games. Today, they will play the following game.

In this game, there are two piles initially consisting of X and Y stones, respectively.
Alice and Bob alternately perform the following operation, starting from Alice:

Take 2i stones from one of the piles. Then, throw away i of them, and put the remaining i in the other pile. Here, the integer i (1≤i) can be freely chosen as long as there is a sufficient number of stones in the pile.

The player who becomes unable to perform the operation, loses the game.

Given X and Y, determine the winner of the game, assuming that both players play optimally.

Constraints

0 ≤ X, Y ≤ 10^{18}

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the winner: either Alice or Brown.

Sample Input 1

2 1

Sample Output 1

Brown

Alice can do nothing but taking two stones from the pile containing two stones. As a result, the piles consist of zero and two stones, respectively. Then, Brown will take the two stones, and the piles will consist of one and zero stones, respectively. Alice will be unable to perform the operation anymore, which means Brown's victory.

Sample Input 2

5 0

Sample Output 2

Alice

Sample Input 3

0 0

Sample Output 3

Brown

Sample Input 4

4 8

Sample Output 4

Alice


#include <bits/stdc++.h>

using namespace std;
#define FOR(i, a, b) for (int i = (a), _##i = (b); i < _##i; ++i)
#define REP(i, a) for (int i = 0, _##i = (a); i < _##i; ++i)
#define pb push_back
typedef long long LL;

int n;
LL a[100004];

LL solve(LL sum){

	LL res = 0;
	FOR(i,2,n){
		if(sum < 0){
			if( sum + a[i] > 0){
				sum += a[i];
				continue;
			}
			res+= 1 - (sum + a[i]);
			sum = 1;
		}else{
			if( sum + a[i] < 0) {
				sum += a[i];
				continue;
			}
			res+= (sum + a[i]) + 1;
			sum = -1;
		}
	}
	return res;
}

int main(){
//	freopen("test.in","r",stdin);
	cin>> n;
	REP(i,n){
		cin >> a[i];
	}
	LL sum = a[0] + a[1];
	if(sum){
		if( sum > 0){
			LL res = min( solve(-1) + sum + 1, solve(sum) );
			cout << min( solve(1) + sum - 1, res ) << endl;
		}else{
			LL res = min( solve(1)  - sum + 1, solve(sum) );
			cout << min( solve(-1)  - sum - 1, res ) << endl;
		}
	}else{
		cout << min( solve(1), solve(-1) ) + 1 << endl;
	}
	return 0;
}


#include <stdio.h>
#include <cstdlib>

void scanData(int *array, int size) {
    for (int i = 0; i < size; ++i) {
        char buffer[100001];
        char *remain;
        scanf("%s", &buffer[0]);
        array[i] = (int)atol(buffer);
    }
}

void print_array(int *array, int size) {
    if (size == 0) return;
    printf("%d ", array[0]);
    print_array(array + 1, size - 1);
}

int count(const int *array, int size) {
    enum Arranged {
        None = -1,
        Ascending,
        Descending
    };

    int splitNum = 0;
    Arranged arranged = array[0] < array[1] ? Ascending : Descending;
    Arranged prevState = arranged;
    for (int i = 1; i < size - 1; ++i) {
        if ((arranged == Ascending && array[i] > array[i + 1]) || (arranged == Descending && array[i] < array[i + 1])) {
            splitNum++;
            i++;
            arranged = array[i] < array[i + 1] ? Ascending : Descending;
        }
    }

    return splitNum + 1;
}

int main() {
    int *array;
    int array_len;

    scanf("%d", &array_len);
    if (array_len == 1) {
        printf("0");
        return 0;
    }
    array = (int*)malloc(sizeof(int) * (size_t)array_len);

    scanData(array, array_len);
    printf("%d", count(array, array_len));

    free(array);

    return 0;
}

Score : 300 points

Problem Statement

You are given an array A of length N.
Your task is to divide it into several contiguous subarrays.
Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order.
At least how many subarrays do you need to divide A into?

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Each 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 minimum possible number of subarrays after division of A.

Sample Input 1

6
1 2 3 2 2 1

Sample Output 1

2

One optimal solution is to divide the array into [1,2,3] and [2,2,1].

Sample Input 2

9
1 2 1 2 1 2 1 2 1

Sample Output 2

5

Sample Input 3

7
1 2 3 2 1 999999999 1000000000

Sample Output 3

3


#include<cstdio>
long long a[100000];
int main()
{
	int t,sum1=0,i;
	scanf("%d",&t);
	for(i=0;i<t;i++){
		scanf("%lld",&a[i]);
	}
	for(i=1;i<t;i++){
		if(a[i]>a[i-1])
			if(a[i]>a[i+1])
				sum1++;
	}
	printf("%d\n",sum1+1);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 100000 + 5, P = 1e9 + 7;
int n, m, x[N], y[N];
int main() {
    scanf("%d%d", &n, &m);
    ll ans = 0, psum = 0;
    for (int i = 1; i <= n; ++i) {
        scanf ("%d", &x[i]);
        ans += 1ll * (i - 1) * x[i] - psum;
        ans %= P;
        psum += x[i];
    }
    ll ans1 = 0;
    psum = 0;
    for (int i = 1; i <= m; ++i) {
        scanf ("%d", &y[i]);
        ans1 += 1ll * (i - 1) * y[i] - psum;
        ans1 %= P;
        psum += y[i];
    }
    cout << (ll)ans1 * ans % P << '\n';
    return 0;
}

Score : 500 points

Problem Statement

On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis.
Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i.
Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i.

For every rectangle that is formed by these lines, find its area, and print the total area modulo 10^9+7.

That is, for every quadruple (i,j,k,l) satisfying 1\leq i < j\leq n and 1\leq k < l\leq m, find the area of the rectangle formed by the lines x=x_i, x=x_j, y=y_k and y=y_l, and print the sum of these areas modulo 10^9+7.

Constraints

2 \leq n,m \leq 10^5

-10^9 \leq x_1 < ... < x_n \leq 10^9

-10^9 \leq y_1 < ... < y_m \leq 10^9

x_i and y_i are integers.

Input

Input is given from Standard Input in the following format:

n m
x_1 x_2 ... x_n
y_1 y_2 ... y_m

Output

Print the total area of the rectangles, modulo 10^9+7.

Sample Input 1

3 3
1 3 4
1 3 6

Sample Output 1

60

The following figure illustrates this input:

The total area of the nine rectangles A, B, ..., I shown in the following figure, is 60.

Sample Input 2

6 5
-790013317 -192321079 95834122 418379342 586260100 802780784
-253230108 193944314 363756450 712662868 735867677

Sample Output 2

835067060


#include <bits/stdc++.h>
#define rep(i,a,b) for(int i=int(a);i<int(b);++i)
#define SIZE 200005
#define INF 1000000005LL
#define MOD 1000000007
using namespace std;
typedef long long int ll;
typedef pair <int,int> P;
int main(){
    ll n,m;
    cin >> n>>m;
    vector<pair<ll,ll>> student(n);
    vector<pair<ll,ll>> check(m);
    rep(i,0,n){
        cin >> student[i].first;
        cin >> student[i].second;
    }
    rep(i,0,m){
        cin>>check[i].first;
        cin>>check[i].second;
    }
    vector<int> ans(n);
    //cout<<check[0].first<<endl;
    rep(i,0,n){
        ll k = 1000000000;
        rep(j,0,m){
            ll now = abs(student[i].first-check[j].first)+abs(student[i].second-check[j].second);
            if(now<k){
                k = now;
                ans[i]=j;

            }
        }
    }
    rep(i,0,n){
        cout<<ans[i]+1<<endl;
    }
  return 0;
}

Score : 200 points

Problem Statement

There are N students and M checkpoints on the xy-plane.

The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j).

When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance.

The Manhattan distance between two points (x_1,y_1) and (x_2,y_2) is |x_1-x_2|+|y_1-y_2|.

Here, |x| denotes the absolute value of x.

If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index.

Which checkpoint will each student go to?

Constraints

1 \leq N,M \leq 50

-10^8 \leq a_i,b_i,c_j,d_j \leq 10^8

All input values are integers.

Input

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

N M
a_1 b_1
:
a_N b_N
c_1 d_1
:
c_M d_M

Output

Print N lines.

The i-th line (1 \leq i \leq N) should contain the index of the checkpoint for the i-th student to go.

Sample Input 1

2 2
2 0
0 0
-1 0
1 0

Sample Output 1

2
1

The Manhattan distance between the first student and each checkpoint is:

For checkpoint 1: |2-(-1)|+|0-0|=3

For checkpoint 2: |2-1|+|0-0|=1

The nearest checkpoint is checkpoint 2. Thus, the first line in the output should contain 2.

The Manhattan distance between the second student and each checkpoint is:

For checkpoint 1: |0-(-1)|+|0-0|=1

For checkpoint 2: |0-1|+|0-0|=1

When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain 1.

Sample Input 2

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

Sample Output 2

3
1
2

There can be multiple checkpoints at the same coordinates.

Sample Input 3

5 5
-100000000 -100000000
-100000000 100000000
100000000 -100000000
100000000 100000000
0 0
0 0
100000000 100000000
100000000 -100000000
-100000000 100000000
-100000000 -100000000

Sample Output 3

5
4
3
2
1


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
#include <stack>
#include <deque>
#include <cmath>
#include <map>
using ll = long long;
using namespace std;

int main() {
  int n, m;
  cin >> n >> m;
  int a[n], b[n], c[m], d[m];
  for (int i = 0; i < n; i++) cin >> a[i] >> b[i];
  for (int i = 0; i < m; i++) cin >> c[i] >> d[i];

  for (int i = 0; i < n; i++) {
    int ans = 1;
    ll mind = 1<<15;
    for (int j = 0; j < m; j++) {
      int dist = abs(a[i] - c[j]) + abs(b[i] - d[j]);
      if (dist < mind) {
        ans = j+1;
        mind = dist;
      }
    }
    cout << ans << endl;
  }
}


#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
#define INF (1<<30)
#define INFLL (1ll<<60)
typedef pair<ll, int> P;
#define MOD (1000000007ll)
#define l_ength size

ll sq(ll x){
	return x*x;
}

void mul_mod(ll& a, ll b){
	a *= b;
	a %= MOD;
}

bool isvowel(char c){
	int i;
	string v="aeiou";
	for(i = (v.size()-1); i>=0; --i){
		if(c == v[i]){
			return true;
		}
	}
	return false;
}

int main(void){
	char a,b;
	cin >> a >> b;
	cout << ((a==b)?"H":"D") << endl;
	return 0;
}

Score : 100 points

Problem Statement

Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest.
In this game, an honest player always tells the truth, and an dishonest player always tell lies.
You are given two characters a and b as the input. Each of them is either H or D, and carries the following information:

If a=H, AtCoDeer is honest; if a=D, AtCoDeer is dishonest.
If b=H, AtCoDeer is saying that TopCoDeer is honest; if b=D, AtCoDeer is saying that TopCoDeer is dishonest.

Given this information, determine whether TopCoDeer is honest.

Constraints

a=H or a=D.

b=H or b=D.

Input

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

a b

Output

If TopCoDeer is honest, print H. If he is dishonest, print D.

Sample Input 1

H H

Sample Output 1

H

In this input, AtCoDeer is honest. Hence, as he says, TopCoDeer is honest.

Sample Input 2

D H

Sample Output 2

D

In this input, AtCoDeer is dishonest. Hence, contrary to what he says, TopCoDeer is dishonest.

Sample Input 3

D D

Sample Output 3

H


#include <bits/stdc++.h>

using namespace std;

#define endl "\n"
#define pb(s) push_back(s)
#define mp(a,b) make_pair(a,b)
#define f first
#define se second
#define ALL(v) v.begin(), v.end()
#define ALLA(arr, sz) arr, arr + sz
#define SORT(v) sort(ALL(v))
#define REVERSE(v) reverse(ALL(v))
#define SORTA(arr, sz) sort(ALLA(arr, sz))
#define REVERSEA(arr, sz) reverse(ALLA(arr, sz))
#define PI 3.14159265358979323846264338327950L
#define MOD 1000000007

typedef long long ll;

void solve(){
    int W,a,b;
    cin>>W>>a>>b;
    int firstL=a;
    int firstR=a+W;
    int secondL=b;
    int secondR=b+W;
    if(firstL>secondR){
        cout<<firstL-secondR<<endl;
    }
    else if(firstR<secondL){
        cout<<secondL-firstR<<endl;
    }
    else cout<<0<<endl;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    //int t;
    //cin>>t;
    //while(t--)
        solve();
    return 0;
}

Score : 200 points

Problem Statement

AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W.
If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the horizontal range of [b,b+W], as shown in the following figure:

AtCoDeer will move the second rectangle horizontally so that it connects with the first rectangle.
Find the minimum distance it needs to be moved.

Constraints

All input values are integers.

1≤W≤10^5

1≤a,b≤10^5

Input

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

W a b

Output

Print the minimum distance the second rectangle needs to be moved.

Sample Input 1

3 2 6

Sample Output 1

1

This input corresponds to the figure in the statement. In this case, the second rectangle should be moved to the left by a distance of 1.

Sample Input 2

3 1 3

Sample Output 2

0

The rectangles are already connected, and thus no move is needed.

Sample Input 3

5 10 1

Sample Output 3

4


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

using namespace std;

#define REP(i, n) for(ll i = 0;i < n;i++)
#define REPR(i, n) for(ll i = n;i >= 0;i--)
#define FOR(i, m, n) for(ll i = m;i < n;i++)
#define FORR(i, m, n) for(int i = m;i >= n;i--)
#define REPO(i, n) for(ll i = 1;i <= n;i++)
#define ll long long
#define INF (ll)1 << 60
#define MINF (-1 * INF)
#define ALL(n) n.begin(),n.end()
#define MOD (ll)1000000007
#define P pair<ll, ll>

ll n, k, s[5100], ans;
ll dat[1100010];
void add(ll x, ll a) {
	x++;
	for (ll i = x; i <= 5100; i += i & -i) dat[i] += a;
}

ll sum(ll x) {
	if (x < 0)return 0;
	x++;
	ll res = 0;
	for (int i = x; i > 0; i -= i & -i) res += dat[i];
	return res;
}

bool dp[5100][5100]; //上限5001
int main() {
	cin >> n >> k;
	REP(i, n)cin >> s[i];
	dp[0][0] = 1;
	add(0, 1);
	REP(i, n) {
		REP(j, k + 1) {
			if (dp[i][j]) {
				dp[i + 1][j] = true;
				dp[i + 1][min((ll)5001, j + s[i])] = true;
			}
		}
	}
	REPR(i, n - 1) {
		bool ok = true;
		REP(j, k) {
			if (dp[i][j]) {
				if (sum(max(0ll, k - 1 - j)) - sum(k - s[i] - 1 - j) > 0) {
					ok = false;
				}
			}
		}
		if (ok)ans++;
		REPR(j, 5001) {
			if (sum(j) - sum(j - 1) > 0)add(min((ll)5001, j + s[i]), 1);
		}
	}
	cout << ans << endl;
}

Score : 600 points

Problem Statement

AtCoDeer the deer has N cards with positive integers written on them. The number on the i-th card (1≤i≤N) is a_i.
Because he loves big numbers, he calls a subset of the cards good when the sum of the numbers written on the cards in the subset, is K or greater.

Then, for each card i, he judges whether it is unnecessary or not, as follows:

If, for any good subset of the cards containing card i, the set that can be obtained by eliminating card i from the subset is also good, card i is unnecessary.

Otherwise, card i is NOT unnecessary.

Find the number of the unnecessary cards. Here, he judges each card independently, and he does not throw away cards that turn out to be unnecessary.

Constraints

All input values are integers.

1≤N≤5000

1≤K≤5000

1≤a_i≤10^9 (1≤i≤N)

Partial Score

300 points will be awarded for passing the test set satisfying N,K≤400.

Input

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

N K
a_1 a_2 ... a_N

Output

Print the number of the unnecessary cards.

Sample Input 1

3 6
1 4 3

Sample Output 1

1

There are two good sets: {2,3} and {1,2,3}.

Card 1 is only contained in {1,2,3}, and this set without card 1, {2,3}, is also good. Thus, card 1 is unnecessary.

For card 2, a good set {2,3} without card 2, {3}, is not good. Thus, card 2 is NOT unnecessary.

Neither is card 3 for a similar reason, hence the answer is 1.

Sample Input 2

5 400
3 1 4 1 5

Sample Output 2

5

In this case, there is no good set. Therefore, all the cards are unnecessary.

Sample Input 3

6 20
10 4 3 10 25 2

Sample Output 3

3


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> Pii;
typedef pair<ll,ll> Pll;
#define rep(i,n) for (ll i=0;i<n;++i)
#define rep2(i,a,b) for (ll i=a;i<b;++i)
const ll MOD=1000000007;
string alp="abcdefghijklmnopqrstuvwxyz";

ll N;
vector<ll> A(100000),B(100000);

bool can(int n){
    auto itr=upper_bound(A.begin(),A.begin()+N,2*B[n]);
    itr--;
    if (itr-A.begin()==N-1){
        return true;
    }
    else if (itr-A.begin()==n){
        return false;
    }
    else {
        return can(itr-A.begin());
    }
}

int main(){
    cin >> N;
    rep(i,N){
        cin >> A[i];
    }
    sort(A.begin(),A.begin()+N);
    B[0]=A[0];
    rep(i,N-1){
        B[i+1]=B[i]+A[i+1];
    }
    ll lb=-1,ub=N;
    while(ub-lb>1){
        ll mid=(ub+lb)/2;
        if (can(mid)){
            ub=mid;
        }
        else {
            lb=mid;
        }
    }
    cout << N-ub << endl;
}

Score : 400 points

Problem Statement

Snuke found N strange creatures.
Each creature has a fixed color and size. The color and size of the i-th creature are represented by i and A_i, respectively.

Every creature can absorb another creature whose size is at most twice the size of itself.
When a creature of size A and color B absorbs another creature of size C and color D (C \leq 2 \times A), they will merge into one creature of size A+C and color B.
Here, depending on the sizes of two creatures, it is possible that both of them can absorb the other.

Snuke has been watching these creatures merge over and over and ultimately become one creature.
Find the number of the possible colors of this creature.

Constraints

2 \leq N \leq 100000

1 \leq A_i \leq 10^9

A_i is an integer.

Input

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

N
A_1 A_2 … A_N

Output

Print the number of the possible colors of the last remaining creature after the N creatures repeatedly merge and ultimately become one creature.

Sample Input 1

3
3 1 4

Sample Output 1

2

The possible colors of the last remaining creature are colors 1 and 3.
For example, when the creature of color 3 absorbs the creature of color 2, then the creature of color 1 absorbs the creature of color 3, the color of the last remaining creature will be color 1.

Sample Input 2

5
1 1 1 1 1

Sample Output 2

5

There may be multiple creatures of the same size.

Sample Input 3

6
40 1 30 2 7 20

Sample Output 3

4


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

#define pb         push_back

typedef long long ll;
const ll INF = 1000000000000000000ll;
const ll MOD = 1000000007ll;
const double EPS = 1e-8;

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

	ll n;
	cin >> n;

	vector<ll> x;
	for(int i=0; i<n; i++){
		ll t;
		cin >> t;
		x.pb(t);
	}

	/*
	for(int i=0; i<n; i++){
		printf("%d ", x[i]);
	}
	puts("");
	*/

	ll ans = 1;

	int sn = n;
	for(int k=0; k<sn; k++){
		map<ll, int> use;
		if(x[0] > 1) x[0] = 1;
		use[x[0]] = 1;
		for(int i=1; i<n; i++){
			if(x[i-1] + 2 < x[i]){
				x[i] = x[i-1] + 2;
			}
			//printf("%d ", x[i]);
			use[x[i]] = 1;
		}

		ll cnt = 0;
		for(int i=2; i<n; i++){
			for(int j=0; j<i; j++){
				if(use.find(x[j]-1) != use.end()){
					cnt++;
					break;
				}else{
				}
			}
		}

		vector<ll> next;
		for(int i=1; i<n;i ++){
			next.pb(x[i]);
		}
		x = next;
		ans *= (n-cnt);
		ans %= MOD;
		n--;
	}

	//printf("cnt:%d\n", cnt);
	/*
	ll ans = n - cnt;
	for(int i=1; i<=n-1; i++){
		ans *= i;
		ans %= MOD;
	}
	*/

	cout << ans << endl;

	return 0;
}

Score : 900 points

Problem Statement

You are developing frog-shaped robots, and decided to race them against each other.

First, you placed N robots onto a number line.
These robots are numbered 1 through N.
The current coordinate of robot i is x_i.
Here, all x_i are integers, and 0 < x_1 < x_2 < ... < x_N.

You will repeatedly perform the following operation:

Select a robot on the number line. Let the coordinate of the robot be x. Select the destination coordinate, either x-1 or x-2, that is not occupied by another robot. The robot now jumps to the selected coordinate.

When the coordinate of a robot becomes 0 or less, the robot is considered finished and will be removed from the number line immediately.
You will repeat the operation until all the robots finish the race.

Depending on your choice in the operation, the N robots can finish the race in different orders.
In how many different orders can the N robots finish the race?
Find the answer modulo 10^9+7.

Constraints

2 ≤ N ≤ 10^5

x_i is an integer.

0 < x_1 < x_2 < ... < x_N ≤ 10^9

Partial Score

In a test set worth 500 points, N ≤ 8.

Input

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

N
x_1 x_2 ... x_N

Output

Print the number of the different orders in which the N robots can finish the race, modulo 10^9+7.

Sample Input 1

3
1 2 3

Sample Output 1

4

There are four different orders in which the three robots can finish the race:

(Robot 1 → Robot 2 → Robot 3)

(Robot 1 → Robot 3 → Robot 2)

(Robot 2 → Robot 1 → Robot 3)

(Robot 2 → Robot 3 → Robot 1)

Sample Input 2

3
2 3 4

Sample Output 2

6

There are six different orders in which the three robots can finish the race:

(Robot 1 → Robot 2 → Robot 3)

(Robot 1 → Robot 3 → Robot 2)

(Robot 2 → Robot 1 → Robot 3)

(Robot 2 → Robot 3 → Robot 1)

(Robot 3 → Robot 1 → Robot 2)

(Robot 3 → Robot 2 → Robot 1)

For example, the order (Robot 3 → Robot 2 → Robot 1) can be achieved as shown in the figure below:

Sample Input 3

8
1 2 3 5 7 11 13 17

Sample Output 3

10080

Sample Input 4

13
4 6 8 9 10 12 14 15 16 18 20 21 22

Sample Output 4

311014372

Remember to print the answer modulo 10^9+7.
This case is not included in the test set for the partial score.


#include<iostream>
#include<cstdio>
#include<algorithm>
#define P 1000000007
#define ll long long
using namespace std;
ll n,a[100005];
int main()
{
	scanf("%lld",&n);
	for (ll i=1;i<=n;i++)
		scanf("%lld",&a[i]);
	sort(a+1,a+n+1);
	ll Ans=1,sum=0;
	for (ll i=1;i<=n;i++)
	{
	//	cout<<Ans<<' '<<sum<<endl;
		if (sum*2+1>a[i]+1)
			Ans=Ans*sum%P;
		else
		if (sum*2+1==a[i]+1) Ans=Ans*(sum+1)%P;
		else sum++;
	//cout<<Ans<<' '<<sum<<endl;
	}
	while(sum) Ans=Ans*(sum--)%P;
	printf("%lld\n",Ans);
}


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

char mas[510][510];

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

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

    int last = 0;
    for(int j = 0;j < n;j++){
        int cnt = 0;
        for(int i = 0;i < n;i++){
            cnt += mas[i][j] == '.' ? 1 : 0;
        }
        if(cnt != 0) last++;
    }

    int ans = INT_MAX;
    for(int i = 0;i < n;i++){
        int cnt = 0;
        for(int j = 0;j < n;j++){
            if(mas[i][j] == '.'){
                cnt++;
            }
        }
        if(cnt != n){
            if(mas[i][i] == '.'){
                cnt++;
            }
            ans = min(ans, cnt);
        }
    }

    if(ans == INT_MAX){
        cout << -1 << endl;
    }else{
        cout << ans + last << endl;
    }

    return 0;
}

Score : 1300 points

Problem Statement

There is a square-shaped grid with N vertical rows and N horizontal columns.
We will denote the square at the i-th row from the top and the j-th column from the left as (i,\ j).

Initially, each square is either white or black.
The initial color of the grid is given to you as characters a_{ij}, arranged in a square shape.
If the square (i,\ j) is white, a_{ij} is .. If it is black, a_{ij} is #.

You are developing a robot that repaints the grid.
It can repeatedly perform the following operation:

Select two integers i, j (1 ≤ i,\ j ≤ N). Memorize the colors of the squares (i,\ 1), (i,\ 2), ..., (i,\ N) as c_1, c_2, ..., c_N, respectively. Then, repaint the squares (1,\ j), (2,\ j), ..., (N,\ j) with the colors c_1, c_2, ..., c_N, respectively.

Your objective is to turn all the squares black.
Determine whether it is possible, and find the minimum necessary number of operations to achieve it if the answer is positive.

Constraints

2 ≤ N ≤ 500

a_{ij} is either . or #.

Partial Score

In a test set worth 300 points, N ≤ 3.

Input

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

N
a_{11}...a_{1N}
:
a_{N1}...a_{NN}

Output

If it is possible to turn all the squares black, print the minimum necessary number of operations to achieve the objective.
If it is impossible, print -1 instead.

Sample Input 1

2
#.
.#

Sample Output 1

3

For example, perform the operation as follows:

Select i = 1, j = 2.

Select i = 1, j = 1.

Select i = 1, j = 2.

The transition of the colors of the squares is shown in the figure below:

Sample Input 2

2
..
..

Sample Output 2

-1

Sample Input 3

2
##
##

Sample Output 3

0

Sample Input 4

3
.#.
###
.#.

Sample Output 4

2

Sample Input 5

3
...
.#.
...

Sample Output 5

5


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

int n;
string s[3];
int dp[512];

int encode(vector<string> ss) {
	int ret = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			int type = (ss[i][j] == '.' ? 1 : 0);
			ret += (type << (i * n + j));
		}
	}
	return ret;
}

void print(vector<string> ss) {
	for (int i = 0; i < 3; i++) {
		cout << ss[i] << endl;
	}
	cout << endl;
}

int INF = 11451419;

int dfs(vector<string> ss) {
	//print(ss);
	int state = encode(ss);
	if (state == 0) return 0;				//完成
	if (dp[state] == -1) return INF;		//探索中
	if (dp[state] >= 0) return dp[state];	//答えが分かっている

	dp[state] = -1;
	int i, j, k;
	int ret = INF;

	for (i = 0; i < n; i++) {
		for (j = 0; j < n; j++) {
			vector<string> ns = ss;
			for (k = 0; k < n; k++) {
				ns[k][j] = ss[i][k];
			}
			ret = min(ret, dfs(ns) + 1);
		}
	}
	dp[state] = ret;
	return ret;
}

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

	vector<string> ss;
	for (int i = 0; i < n; i++) ss.push_back(s[i]);
	for (int i = 0; i < 512; i++) dp[i] = -2;

	int res = dfs(ss);
	if (res < INF) cout << res - 1 << endl;
	else { cout << -1 << endl; }
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
int n,total;
int main () {
cin >> n;
total = n*800 - n/15*200;
cout << total << endl;

}

Score : 100 points

Problem Statement

Snuke has a favorite restaurant.

The price of any meal served at the restaurant is 800 yen (the currency of Japan), and each time a customer orders 15 meals, the restaurant pays 200 yen back to the customer.

So far, Snuke has ordered N meals at the restaurant.
Let the amount of money Snuke has paid to the restaurant be x yen, and let the amount of money the restaurant has paid back to Snuke be y yen.
Find x-y.

Constraints

1 ≤ N ≤ 100

Input

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

N

Output

Print the answer.

Sample Input 1

20

Sample Output 1

15800

So far, Snuke has paid 16000 yen, and the restaurant has paid back 200 yen. Thus, the answer is 15800.

Sample Input 2

60

Sample Output 2

47200

Snuke has paid 48000 yen for 60 meals, and the restaurant has paid back 800 yen.


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

int main(){
  ll n;
  cin >> n;
  ll ans = 1;
  for(int i = 1; i <= n; ++i){
    ans *= i;
    ans %= mod;
  }
  cout << ans << endl;
}

Score : 200 points

Problem Statement

Snuke loves working out. He is now exercising N times.

Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.

Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.

Constraints

1 ≤ N ≤ 10^{5}

Input

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

N

Output

Print the answer modulo 10^{9}+7.

Sample Input 1

3

Sample Output 1

6

After Snuke exercises for the first time, his power gets multiplied by 1 and becomes 1.

After Snuke exercises for the second time, his power gets multiplied by 2 and becomes 2.

After Snuke exercises for the third time, his power gets multiplied by 3 and becomes 6.

Sample Input 2

10

Sample Output 2

3628800

Sample Input 3

100000

Sample Output 3

457992974

Print the answer modulo 10^{9}+7.


#include<bits/stdc++.h>
#define fast ios::sync_with_stdio(false), cin.tie(0);
#define ll long long
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define endl '\n'

const int M = 1e9+7;

using namespace std;

main()
{
    fast;
    ll n,m;
    cin>>n>>m;
    if (n==m/2)
        cout<<n<<endl;
    else if (n<m/2)
    {
        m-=2*n;
        cout<<n+m/4<<endl;
    }
    else
        cout<<m/2<<endl;
}

Score : 300 points

Problem Statement

Snuke loves puzzles.

Today, he is working on a puzzle using S- and c-shaped pieces.
In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below:

Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped pieces.

Find the maximum number of Scc groups that can be created when Snuke has N S-shaped pieces and M c-shaped pieces.

Constraints

1 ≤ N,M ≤ 10^{12}

Input

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

N M

Output

Print the answer.

Sample Input 1

1 6

Sample Output 1

2

Two Scc groups can be created as follows:

Combine two c-shaped pieces into one S-shaped piece

Create two Scc groups, each from one S-shaped piece and two c-shaped pieces

Sample Input 2

12345 678901

Sample Output 2

175897


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#include <queue>
#include <climits>
#include <set>
#include <map>
#include <stack>
#include <iomanip>
#include <tuple>
#define ll long long
using namespace std;
ll factorial(ll n){
    if(n==0){
        return 1;
    }
    else{
        return n*factorial(n-1);
    }
}

double dist(pair<double,double> a,pair<double,double> b){
	return sqrt(pow((a.first - b.first) ,2) + pow((a.second - b.second),2));
}
//繰り返し自乗法
double ism(double aa,ll p){
    double ap=aa;
    double ans=1;
    while(p>0){
        //cout<<"p="<<p<<",ap="<<ap<<endl;
        if(p&1){//奇数が真
            ans*=ap;
        }
        p/=2;
        ap=ap*ap;
    }
    return ans;

}
//繰り返し自乗法(アマリトリバージョン)
ll ismm(ll aa,ll p,ll m){
    ll ap=aa;
    ll ans=1;
    while(p>0){
        //cout<<"p="<<p<<",ap="<<ap<<endl;
        if(p&1){//奇数が真
            ans=(ans*ap)%m;
        }
        p/=2;
        ap=(ap*ap)%m;
    }
    return ans;

}

struct all_init
{
    all_init()
    {
        cout << fixed << setprecision(9);
    }
} All_init;

int main()
{
    ll n,m,ans=0;
    cin>>n>>m;
    ans=min(n,m/2);
    m-=ans*2;
    ans+=m/4;
    cout<<ans<<endl;

}


#include <bits/stdc++.h>
#define ls (o << 1)
#define rs (o << 1 | 1)
#define mid ((L + R + 1) >> 1)
using namespace std;
const int MAXN = 200050;
const int mod = 998244353;
typedef long long LL;
int main() {
#ifdef TEST
	freopen("input.txt", "r", stdin);
#endif
	LL a, b;
	cin >> a >> b;
	LL L = 0, R = a + b;
	while (L < R) {
		if (b >= mid + mid && a + (b - mid - mid) / 2 >= mid) {
			L = mid;
		} else {
			R = mid - 1;
		}
	}
	cout << L << endl;
	return 0;
}


#include<bits//stdc++.h>
using namespace std;
#define rep(i,n) for(int i = 0; i < n;i++)
int main() {
	int n, m;cin >> n >> m;
	char a[50][50],b[50][50];bool h = false;
	rep(i, n) rep(j,n) cin >> a[i][j];
	rep(j, m) rep(i,m) cin >> b[j][i];
	for (int i = 0; i < n;i++) {
		for (int j = 0;j < n;j++) {
			if (i + m - 1 >= n || j + m - 1>= n) continue;
			bool ch = true;
			rep(k, m) {
				rep(l, m) {
					if (a[i + k][l + j] != b[k][l]) ch = false;
				}
			}
			if (ch) h = true;
		}
	}
	if (h) cout << "Yes" << endl;
	else cout << "No" << endl;
}

Score : 200 points

Problem Statement

You are given an image A composed of N rows and N columns of pixels, and a template image B composed of M rows and M columns of pixels.

A pixel is the smallest element of an image, and in this problem it is a square of size 1×1.

Also, the given images are binary images, and the color of each pixel is either white or black.

In the input, every pixel is represented by a character: . corresponds to a white pixel, and # corresponds to a black pixel.

The image A is given as N strings A_1,...,A_N.

The j-th character in the string A_i corresponds to the pixel at the i-th row and j-th column of the image A (1≦i,j≦N).

Similarly, the template image B is given as M strings B_1,...,B_M.

The j-th character in the string B_i corresponds to the pixel at the i-th row and j-th column of the template image B (1≦i,j≦M).

Determine whether the template image B is contained in the image A when only parallel shifts can be applied to the images.

Constraints

1≦M≦N≦50

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

B_i is a string of length M consisting of # and ..

Input

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

N M
A_1
A_2
:
A_N
B_1
B_2
:
B_M

Output

Print Yes if the template image B is contained in the image A. Print No otherwise.

Sample Input 1

3 2
#.#
.#.
#.#
#.
.#

Sample Output 1

Yes

The template image B is identical to the upper-left 2 × 2 subimage and the lower-right 2 × 2 subimage of A. Thus, the output should be Yes.

Sample Input 2

4 1
....
....
....
....
#

Sample Output 2

No

The template image B, composed of a black pixel, is not contained in the image A composed of white pixels.


#include<bits/stdc++.h>
using namespace std;
char x[55][55];
char y[55][55];
int main(){
	int n,m,w,count=0;
	cin>>n>>m;
	for(int i=0;i<n;i++){
		for(int j=0;j<n;j++){
			cin>>x[i][j];
		}
	}
		for(int i=0;i<m;i++){
		for(int j=0;j<m;j++){
			cin>>y[i][j];
		}
	}
	for(int i=0;i<m-n;i++){
	for(int j=0;j<m-n;j++){
	for(int k=0;k<n;k++){
	for(int l=0;l<n;l++){
			if(y[i+k][l+j]==x[i+k][l+j]){
				count++;
			}
		}
	}

	w=m*m;
	if(count==w)
	return cout<<"Yes" ,0;

		}
	}

	return cout<<"No" ,0;
}/**

3 2
#.#
.#.
#.#
#.
.#
*/


#include <stdio.h>

int num[8], n, ans = 0;
bool r[8][8], flg[8];

void saiki(int a) {
  int i;
  if(a == n) {
    bool b = true;
    for(i = 1; i < n; ++i) if(!r[num[i - 1]][num[i]]) b = false;
    if(b) ++ans;
    return;
  }
  for(i = 1; i < n; ++i) if(flg[i]) {
    num[a] = i, flg[i] = false;
    saiki(a + 1);
    flg[i] = true;
  }
}

int main(void) {
  int i, m, j, x, y;
  scanf("%d%d", &n, &m);
  for(i = 0; i < n; ++i) for(j = 0; j < n; ++j) r[i][j] = false;
  for(i = 0; i < n; ++i) flg[i] = true;
  for(i = 0; i < m; ++i) {
    scanf("%d%d", &x, &y);
    x--, y--;
    r[x][y] = r[y][x] = true;
  }
  num[0] = 0;
  saiki(1);
  printf("%d", ans);
  return 0;
}

Score : 300 points

Problem Statement

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

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

How many different paths start from vertex 1 and visit all the vertices exactly once?

Here, the endpoints of a path are considered visited.

For example, let us assume that the following undirected graph shown in Figure 1 is given.

Figure 1: an example of an undirected graph

The following path shown in Figure 2 satisfies the condition.

Figure 2: an example of a path that satisfies the condition

However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices.

Figure 3: an example of a path that does not satisfy the condition

Neither the following path shown in Figure 4, because it does not start from vertex 1.

Figure 4: another example of a path that does not satisfy the condition

Constraints

2≦N≦8

0≦M≦N(N-1)/2

1≦a_i<b_i≦N

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

Input

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

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once.

Sample Input 1

3 3
1 2
1 3
2 3

Sample Output 1

2

The given graph is shown in the following figure:

The following two paths satisfy the condition:

Sample Input 2

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

Sample Output 2

1

This test case is the same as the one described in the problem statement.


#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <utility>
#include <set>
#include <cctype>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#define all(v) (v).begin(),(v).end()
#define rep(i,n) for(int i=0;i<(n);i++)
#define reps(i,f,n) for(int i=(f);i<(n);i++)
#define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++)
#define MAX(a,b) (a>b?a:b)
using namespace std;

int main(){
  int N, num;
  cin >> N;
  int cnt =0;
  rep(i, N){
    cin >> num;
    if(num%2==1) cnt++;
  }
  if(cnt%2==0) cout << "YES" << endl;
  else  cout << "NO" << endl;
  return 0;
}

Score : 300 points

Problem Statement

There are N integers written on a blackboard. The i-th integer is A_i.

Takahashi will repeatedly perform the following operation on these numbers:

Select a pair of integers, A_i and A_j, that have the same parity (that is, both are even or both are odd) and erase them.

Then, write a new integer on the blackboard that is equal to the sum of those integers, A_i+A_j.

Determine whether it is possible to have only one integer on the blackboard.

Constraints

2 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

A_i is an integer.

Input

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

N
A_1 A_2 … A_N

Output

If it is possible to have only one integer on the blackboard, print YES. Otherwise, print NO.

Sample Input 1

3
1 2 3

Sample Output 1

YES

It is possible to have only one integer on the blackboard, as follows:

Erase 1 and 3 from the blackboard, then write 4. Now, there are two integers on the blackboard: 2 and 4.

Erase 2 and 4 from the blackboard, then write 6. Now, there is only one integer on the blackboard: 6.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

NO


#include<bits/stdc++.h>

using namespace std;

#define pb push_back
#define mp make_pair
#define F first
#define S second

#define fo(i, n) for(int i = 1; i <= n; ++i)
#define rep(i, a, b) for(int (i) = (a); (i) < (b); ++(i))

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

const int N = 200200;
const int mod = 1e9 + 7;
const ll INF = 1e18;
int n,cnt;

int main()
{
	ios::sync_with_stdio(0); cin.tie(0);
		cin>>n;
		fo(i,n)
		{
			int x;
			cin>>x;
			if(x%2==1)
				++cnt;
		}
		if(cnt&1)
		cout<<"NO";
		else cout<<"YES";
	return 0;
}


#include<iostream>
#define abs(a) a>0?a:-a
using namespace std;
int a[100005];
int b[100005];

int main(){
	int n,m=0;
	int i,j,k;
	bool miss=false;
	cin>>n;
	for(i=0;i<n;i++){
		cin>>a[i];
	}
	for(i=0;i<n;i++){
		if(i==n-1){
			b[n-1]=a[n-1]-a[0];
		}else{
			b[i]=a[i]-a[i+1];
		}
		if(b[i]<0){
			j=(-b[i])/n+1;
			b[i]+=j*n;
		}
	}
	k=b[0]%n;
	for(i=0;i<n;i++){
		if(b[i]%n!=k){
			miss=true;
			break;
		}
	}
	if(miss){
		cout<<"NO"<<endl;
	}else{
		cout<<"YES"<<endl;
	}
	return 0;
}

Score : 500 points

Problem Statement

There are N boxes arranged in a circle. The i-th box contains A_i stones.

Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation:

Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-th box. Here, the (N+k)-th box is identified with the k-th box.

Note that the operation cannot be performed if there is a box that does not contain enough number of stones to be removed.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

Input

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

N
A_1 A_2 … A_N

Output

If it is possible to remove all the stones from the boxes, print YES. Otherwise, print NO.

Sample Input 1

5
4 5 1 2 3

Sample Output 1

YES

All the stones can be removed in one operation by selecting the second box.

Sample Input 2

5
6 9 12 10 8

Sample Output 2

YES

Sample Input 3

4
1 2 3 1

Sample Output 3

NO


#include <bits/stdc++.h>

using namespace std;

#define INF 1001000100010001000
#define MOD 1000000007
#define EPS 1e-10
#define int long long
#define rep(i, N) for (int i = 0; i < N; i++)
#define Rep(i, N) for (int i = 1; i < N; i++)
#define For(i, a, b) for (int i = (a); i < (b); i++)
#define pb push_back
#define mp make_pair
#define i_i pair<int, int>
#define vi vector<int>
#define vvi vector<vi >
#define vb vector<bool>
#define vvb vector<vb >
#define vp vector< i_i >
#define all(a) (a).begin(), (a).end()
#define Int(x) int x; scanf("%lld", &x);

//int dxy[5] = {0, 1, 0, -1, 0};
// assign

signed main()
{
    Int(n);
    int sum = 0;
    vi data(n, 0);
    rep(i, n) {
        cin >> data[i];
        sum += data[i];
    }

    int k = sum / (n * (n + 1) / 2);
    if (k * (n * (n + 1) / 2) != sum) {
        cout << "NO" << endl;
        return 0;
    }

    vi dist(n, 0);

    rep(i, n-1) {
        dist[i] = data[i+1] - data[i] - k;
    }
    dist[n-1] = data[0] - data[n-1] - k;

    rep(i, n) {
        if (dist[i] <= 0 && (-dist[i]) % n) {
            cout << "NO" << endl;
            return 0;
        }
    }
    cout << "YES" << endl;
    return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>

using namespace std;

#define x first
#define y second
#define mp make_pair
#define pb push_back

#define no {printf("NO\n"); return 0;}

typedef long long ll;

const ll MOD = 1e9+7;

int a[100005];

vector <int> v[100005];

int br[100005];

void dfs(int x, int par) {
	int uk = 2*a[x];
	for (int i=0 ; i<v[x].size() ; i++) {
		if (v[x][i] == par) continue;
		dfs(v[x][i], x);
		uk -= br[v[x][i]];
	}
	br[x] = uk;
	if (v[x].size() == 1) br[x]/=2;
}

int main() {
	int n;
	scanf("%d", &n);
	for (int i=1 ; i<=n ; i++) {
		scanf("%d", a+i);
	}
	for (int i=0 ; i<n-1 ; i++) {
		int x,y;
		scanf("%d%d", &x, &y);
		v[x].pb(y);
		v[y].pb(x);
	}
	dfs(1, 0);
	//for (int i=1 ; i<=n ; i++) cout <<br[i]<<" ";
	if (br[1]) no;
	for (int i=2 ; i<=n ; i++) {
		if (br[i] > a[i]) no;
	}
	printf("YES\n");
	return 0;
}

Score : 700 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.

Currently, there are A_i stones placed on vertex i.
Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation:

Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices.
Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them.

Note that the operation cannot be performed if there is a vertex with no stone on the path.

Constraints

2 ≦ N ≦ 10^5

1 ≦ a_i,b_i ≦ N

0 ≦ A_i ≦ 10^9

The given graph is a tree.

Input

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

N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

If it is possible to remove all the stones from the vertices, print YES. Otherwise, print NO.

Sample Input 1

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

Sample Output 1

YES

All the stones can be removed, as follows:

Select vertices 4 and 5. Then, there is one stone remaining on each vertex except 4.

Select vertices 1 and 5. Then, there is no stone on any vertex.

Sample Input 2

3
1 2 1
1 2
2 3

Sample Output 2

NO

Sample Input 3

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

Sample Output 3

YES


#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cassert>
#include <iomanip>
#include <cstdio>
#include <float.h>
#include <queue>
#include <set>
#include <map>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <stack>
#include <functional>

using namespace std;

#define endl '\n'
#define MOD 1000000007
#define INF 1ll<<30

// #define MAX 100010

#define eps 1e-11
#define bit_max 1ll<<32
#define _USE_MATH_DEFINES

int a[1234567];
vector<int> g[1234567];
bool poss;

int dfs(int u,int v)
{
    int sum = 0;
    int cnt = 0;
    int mx = 0;
    for(int i=0;i<g[u].size();i++)
    {
        int zolo = g[u][i];
        if(zolo==v)
            continue;
        cnt++;
        int temp = dfs(zolo,u);
        sum+=temp;
        mx = max(mx,temp);
    }
    if(cnt == 0)
        return a[u];
    if(a[u]>sum||a[u]<mx||(2*a[u])<sum)
    {
        poss = true;
        return 0;
    }
    return 2*a[u]-sum;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    // #ifndef ONLINE_JUDGE
        // freopen("input.txt","r",stdin);
        // freopen("output.txt","w",stdout);
    // #endif
    long long int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
    }
    if(n==2)
    {
        if(a[0]==a[1])
            cout<<"YES";
        else
            cout<<"NO";
        cout<<endl;
        return 0;
    }
    for(int i=0;i<n-1;i++)
    {
        int x,y;
        cin>>x>>y;
        x--;y--;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    poss = false;
    int temp=1;
    for(int i=0;i<n;i++)
    {
        if(g[i].size()>1)
        {
            temp = dfs(i,-1);
            break;
        }
    }
    if(temp==0&&!poss)
        cout<<"YES";
    else
        cout<<"NO";
    cout<<endl;
    return 0;
}


#include <iostream>
#include <vector>
#include <cstdio>
#include <sstream>
#include <map>
#include <string>
#include <algorithm>
#include <queue>
#include <cmath>
#include <functional>
#include <set>
#include <ctime>
#include <random>
#include <chrono>
#include <cassert>
#include <tuple>
#include <utility>
using namespace std;

namespace {
  using Integer = long long; //__int128;
  template<class T, class S> istream& operator >> (istream& is, pair<T,S>& p){return is >> p.first >> p.second;}
  template<class T> istream& operator >> (istream& is, vector<T>& vec){for(T& val: vec) is >> val; return is;}
  template<class T> istream& operator ,  (istream& is, T& val){ return is >> val;}
  template<class T, class S> ostream& operator << (ostream& os, const pair<T,S>& p){return os << p.first << " " << p.second;}
  template<class T> ostream& operator << (ostream& os, const vector<T>& vec){for(size_t i=0; i<vec.size(); i++) os << vec[i] << (i==vec.size()-1?"":" "); return os;}
  template<class T> ostream& operator ,  (ostream& os, const T& val){ return os << " " << val;}

  template<class H> void print(const H& head){ cout << head; }
  template<class H, class ... T> void print(const H& head, const T& ... tail){ cout << head << " "; print(tail...); }
  template<class ... T> void println(const T& ... values){ print(values...); cout << endl; }

  template<class H> void eprint(const H& head){ cerr << head; }
  template<class H, class ... T> void eprint(const H& head, const T& ... tail){ cerr << head << " "; eprint(tail...); }
  template<class ... T> void eprintln(const T& ... values){ eprint(values...); cerr << endl; }

  class range{ Integer start_, end_, step_; public: struct range_iterator{ Integer val, step_; range_iterator(Integer v, Integer step) : val(v), step_(step) {} Integer operator * (){return val;} void operator ++ (){val += step_;} bool operator != (range_iterator& x){return step_ > 0 ? val < x.val : val > x.val;} }; range(Integer len) : start_(0), end_(len), step_(1) {} range(Integer start, Integer end) : start_(start), end_(end), step_(1) {} range(Integer start, Integer end, Integer step) : start_(start), end_(end), step_(step) {} range_iterator begin(){ return range_iterator(start_, step_); } range_iterator   end(){ return range_iterator(  end_, step_); } };

  inline string operator "" _s (const char* str, size_t size){ return move(string(str)); }
  constexpr Integer my_pow(Integer x, Integer k, Integer z=1){return k==0 ? z : k==1 ? z*x : (k&1) ? my_pow(x*x,k>>1,z*x) : my_pow(x*x,k>>1,z);}
  constexpr Integer my_pow_mod(Integer x, Integer k, Integer M, Integer z=1){return k==0 ? z%M : k==1 ? z*x%M : (k&1) ? my_pow_mod(x*x%M,k>>1,M,z*x%M) : my_pow_mod(x*x%M,k>>1,M,z);}
  constexpr unsigned long long operator "" _ten (unsigned long long value){ return my_pow(10,value); }

  inline int k_bit(Integer x, int k){return (x>>k)&1;} //0-indexed

  mt19937 mt(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count());

  template<class T> string join(const vector<T>& v, const string& sep){ stringstream ss; for(size_t i=0; i<v.size(); i++){ if(i>0) ss << sep; ss << v[i]; } return ss.str(); }

  inline string operator * (string s, int k){ string ret; while(k){ if(k&1) ret += s; s += s; k >>= 1; } return ret; }
}
constexpr long long mod = 9_ten + 7;

long long dfs(vector<vector<int>>& G, vector<long long>& a, int pos, int last){
  if(G[pos].size() == 1) return a[pos];

  long long mx  = 0;
  long long sum = 0;
  for(int nx : G[pos]){
    if(nx == last) continue;
    long long tmp = dfs(G, a, nx, pos);
    if(tmp == -1) return -1;
    mx = max(tmp, mx);
    sum += tmp;
  }

  long long p = sum - a[pos];
  long long max_p;
  if(sum/2 >= mx){
    max_p = sum/2;
  }else{
    max_p = sum - mx;
  }
  if(max_p < p){
    return -1;
  }
  long long d = sum - 2*p;
  if(d < 0 || p < 0){
    return -1;
  }
  if( d + p == a[pos] ){
    return d;
  }else{
    return -1;
  }

}

int main(){
  int n;
  cin >> n;
  vector<long long> a(n);
  cin >> a;
  vector<vector<int>> G(n);
  for(auto i : range(n-1) ){
    int u,v;
    cin >> u,v;
    u--; v--;
    G[u].push_back(v);
    G[v].push_back(u);
  }

  if(n == 2){
    println(a[0] == a[1] ? "YES" : "NO");
    return 0;
  }

  int root = -1;
  for(int i=0; i<n; i++){
    if(G[i].size() >= 2){
      root = i;
      break;
    }
  }

  auto res = dfs(G, a, root, -1);

  if(res == 0){
    println("YES");
  }else{
    println("NO");
  }
  return 0;
}


#include<cstdio>
#define N 110000
inline char gc(){
	static char now[1<<16],*T,*S;
	if (T==S){T=(S=now)+fread(now,1,1<<16,stdin);if (T==S) return EOF;}
	return *S++;
}
inline int read(){
	int x=0;char ch=gc();
	while (ch<'0'||ch>'9') ch=gc();
	while (ch<='9'&&ch>='0'){x=x*10+ch-'0';ch=gc();}
	return x;
}
inline int gcd(int x,int y){
	if (y==0) return x;return gcd(y,x%y);
}
int cur,n,a[N],mod,g1[N],g2[N];long long sum;
void printans(){
	if (!cur) printf("Second");else printf("First");
}
int main(){
	//freopen("d.in","r",stdin);
	n=read();
	for (int i=1;i<=n;++i) a[i]=read(),(mod+=a[i]%2)%=2;
	if (n%2&&!mod) {printf("First");return 0;}
	if (!n%2) {if (mod) printf("First");else printf("Second");return 0;}
	while (1){sum=0;
		for (int i=1;i<=n;++i) g1[i]=gcd(a[i],g1[i-1]);
		for (int i=n;i>=1;--i) g2[i]=gcd(a[i],g2[i+1]);
		for (int i=1;i<=n;++i) sum+=a[i];int g;
		for (int i=1;i<=n;++i){
			if (a[i]==1) {printans();return 0;}
			g=gcd(g1[i-1],gcd(a[i]-1,g2[i+1]));
			if (((sum-1)/g)%2) break;
		}
		if (g==1) {printans();return 0;}
		for (int i=1;i<=n;++i) a[i]/=g;
		cur^=1;
	}
	return 0;
}

Score : 1000 points

Problem Statement

There are N integers written on a blackboard. The i-th integer is A_i, and the greatest common divisor of these integers is 1.

Takahashi and Aoki will play a game using these integers. In this game, starting from Takahashi the two player alternately perform the following operation:

Select one integer on the blackboard that is not less than 2, and subtract 1 from the integer.

Then, divide all the integers on the black board by g, where g is the greatest common divisor of the integers written on the blackboard.

The player who is left with only 1s on the blackboard and thus cannot perform the operation, loses the game.
Assuming that both players play optimally, determine the winner of the game.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

The greatest common divisor of the integers from A_1 through A_N is 1.

Input

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

N
A_1 A_2 … A_N

Output

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

Sample Input 1

3
3 6 7

Sample Output 1

First

Takahashi, the first player, can win as follows:

Takahashi subtracts 1 from 7. Then, the integers become: (1,2,2).

Aoki subtracts 1 from 2. Then, the integers become: (1,1,2).

Takahashi subtracts 1 from 2. Then, the integers become: (1,1,1).

Sample Input 2

4
1 2 4 8

Sample Output 2

First

Sample Input 3

5
7 8 8 8 8

Sample Output 3

Second