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

int main(){
    int N;
    cin >> N;
    vector<int> A(N,0);

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

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

    int Temp = 1000000001;
    for(int i = 1; i < N; i++)
    {
        for(int j = 0; j < i; j++)
        {
            if (A[i] % A[j] == 1)
            {
                cout << 1 << endl;
                return 0;
            }
            else if(A[i] % A[j] < Temp && A[i] % A[j] > 1)
            {
                Temp = A[i] % A[j];
                A[i] = Temp;
                sort(A.begin(),A.end());
                i = 1;
            }

        }
    }
    if(Temp<1000000001) cout << Temp << endl;
    else cout << A[0] << endl;
    return 0;
}

Score : 300 points

Problem Statement

There are N monsters, numbered 1, 2, ..., N.

Initially, the health of Monster i is A_i.

Below, a monster with at least 1 health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


#include<iostream>
#include<vector>
#include<sstream>
#include<string>
#include<numeric>
#include <algorithm>
#include<math.h>
#include<cstdio>
#include<string.h>
#include<unistd.h>
#include <array>
#include <map>
#include<stdio.h>
#include<queue>
#include<set>
#include<tuple>
#include <iomanip>
#define ALL(a)  (a).begin(),(a).end()
const long long MOD = 1000000007;

//いろんなstlの使い方　https://qiita.com/tukejonny/items/f4013547df761a0b3523
//http://y-mazun.hatenablog.com/entry/20111202/1322840281

using namespace std;
struct point{
    int x;
    int y;

};
//https://ei1333.github.io/luzhiled/snippets/structure/union-find.html
template< typename T >
struct WeightedUnionFind {
  vector< int > data;
  vector< T > ws;

  WeightedUnionFind() {}

  WeightedUnionFind(int sz) : data(sz, -1), ws(sz) {}

  int find(int k) {
    if(data[k] < 0) return k;
    auto par = find(data[k]);
    ws[k] += ws[data[k]];
    return data[k] = par;
  }

  T weight(int t) {
    find(t);
    return ws[t];
  }

  bool unite(int x, int y, T w) {
    w += weight(x);
    w -= weight(y);
    x = find(x), y = find(y);
    if(x == y) return false;
    if(data[x] > data[y]) {
      swap(x, y);
      w *= -1;
    }
    data[x] += data[y];
    data[y] = x;
    ws[y] = w;
    return true;
  }

  T diff(int x, int y) {
    return weight(y) - weight(x);
  }
};

long long gcd(long long a, long long b)
{
    if(a>b){
        return gcd(b,a);
    }
    return a == 0 ? b : gcd(b % a, a);
}
long long lcm( long long m, long long n )
{
    // 引数に０がある場合は０を返す
    if ( ( 0 == m ) || ( 0 == n ) )
        return 0;

    return ((m / gcd(m, n)) * n); // lcm = m * n / gcd(m,n)
}//lcm
int input(){
    int x;
    cin>>x;
    return x;
}

int moji(char in)
{
    int ans = (int)in-(int)'a';
    if((ans < 0) || (ans > 25)){
        ans = 26;
    }
    return ans;
}
const int VV=1;//場合に応じてVVの値のみ変更する必要あり
//dijkstra(s)sがスタート地点でそこからの最短距離を配列dで表す。正の重みのみ使用可能
int cost[VV][VV];
int d[VV];
bool used[VV];
void dijkstra(int s){

    fill(d,d+VV,100000);
    fill(used,used+VV,false);
    d[s]=0;
    while(true){
        cout<<"Hello"<<endl;
        int v=-1;
        for(int u=0;u<VV;u++){
            if(!used[u]&&(v==-1||d[u]<d[v]))v=u;
        }
        if(v==-1)break;
        used[v]=true;
        for(int u=0;u<VV;u++){
            d[u]=min(d[u],d[v]+cost[v][u]);
        }
    }

}

int compare_int(const void *a, const void *b)//qsort(quick sort利用時に使用)
{
    return *(int*)a - *(int*)b;
}

int binary_searchh(long long x,long long k[],int n){
    int l=0;
    int r=n;
    while(r-l>=1){
        int i=(l+r)/2;
        if(k[i]==x)return i;
        else if(k[i]<x)l=i+1;
        else r=i;
    }
    return -1;
}

struct File {
    int aa;
    int bb;

    File(const int& aa, const int& bb)
            : aa(aa), bb(bb) {}
};

/*bool operator<(const File& a, const File& b)
{
    // ファイル種別、ファイル名の順番で優先順位を付けて比較
    return std::tie(a.aa, a.bb) < std::tie(b.aa, b.bb);
}*/

long long kaijo(long long x){
    long long l=10*10*10*10*10*10*10*10*10+7;
    long long sum=1;
    for(int i=x;i>0;i--){
        sum*=i;
        if(sum>l){
            sum%=l;
        }
    }
    return sum;
}

template<class T>void chmin(T &a,T b){
    if(a>b){
        a=b;
    }
}

//formerは前方のindex(自分自身を含んで良い)
template<class T>int former(const vector<T>&v,T x){
    return upper_bound(v.begin(),v.end(),x)-v.begin()-1;
}
//latterは後方のindex(自分自身を含んで良い)
template<class T>int latter(const vector<T>&v,T x){
    return lower_bound(v.begin(),v.end(),x)-v.begin();
}

struct UnionFind{
    //par[i]データiの属する木の親の番号。i==par[i]のときデータiは木の根ノードである
    vector<int>par;
    //sizes[i]:根ノードiの木に含まれるデータ数、iが根ノードでないときは無意味な値になる
    vector<int>sizes;

    UnionFind(int n):par(n),sizes(n,1){
        //最初は全てのデータiがグループiに存在するものとして初期化
        for(int i=0;i<n;i++){
            par[i]=i;
        }
    }
    //データxが属する木の根を得る
    int find(int x){
        if(x==par[x]){
            return x;
        }
        return par[x]=find(par[x]);

    }
    //2つのデータx,yが属する木をマージする
    void unite(int x,int y){
        //データの根ノードを得る
        x=find(x);
        y=find(y);
        //もしすでに同じ木に属しているならマージの必要はない
        if(x==y){
            return;
        }
        //xの木がyの木よりも大きくなるようにする
        if(sizes[x]<sizes[y]){
            swap(x,y);
        }
        //xがyの親になるように連結する
        par[y]=x;
        sizes[x]+=sizes[y];

    }
    //2つのデータx,yが属する木が同じならtrueを返す
    bool same(int x,int y){
        return find(x)==find(y);
    }
    //データxが含まれる木の大きさを返す
    int size(int x){
        return sizes[find(x)];
    }

};

//クラスカル法
//頂点a,bをつなぐコストcostの（無向）辺
struct Edge{
    int a,b,cost;
    //コストの大小で順序定義
    bool operator<(const Edge& o)const{
        return cost<o.cost;
    }
};
//頂点数と辺集合の組として定義したグラフ
/*struct Graph{
    int n;//頂点数
    vector<Edge>es;//辺集合
    //クラスカル法で無向最小全域木のコストの和を計算する
    //グラフが非連結の時は最小全域森のコストの和になる
    //使い方http://dai1741.github.io/maximum-algo-2012/docs/minimum-spanning-tree/
    int kruskal(){
        //コストが小さい順にソーと
        sort(es.begin(),es.end());
        UnionFind uf(n);
        int min_cost=0;
        for(int ei=0;ei<es.size();ei++){
            Edge& e=es[ei];
            if(!uf.same(e.a,e.b)){
                //その辺によって2つの木が連結される
                min_cost+=e.cost;
                uf.unite(e.a,e.b);

            }
        }
        return min_cost;
    }
};*/
//標準入力からグラフを読み込む
/*Graph input_graph(){
    Graph g;
    int m;
    cin>>g.n>>m;
    for(int i=0;i<m;i++){
        Edge e;
        cin>>e.a>>e.b>>e.cost;
        g.es.push_back(e);
    }
    return g;
}*/
long long labs(long long x){
    if(x<0){
        return -x;
    }
    return x;
}
// a^n mod を計算する
long long modpow(long long a, long long n, long long mod) {
    long long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}
//indexを用いてvectorから要素削除
template<typename T>
void remove(std::vector<T>& vector, unsigned int index)
{
    vector.erase(vector.begin() + index);
}

void modadd(long long &a,long long b){
    a+=b;
    if(a>=MOD){
        a%=MOD;

    }
}

const int MAX = 2;
long long fac[MAX], finv[MAX], inv[MAX];

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

// 二項係数計算
long long COM(int n, int k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}
using Graph = vector<vector<int> >;
int main(){
    map<int,int>joken;
    joken[1]=2;
    joken[2]=5;
    joken[3]=5;
    joken[4]=4;
    joken[5]=5;
    joken[6]=6;
    joken[7]=3;
    joken[8]=7;
    joken[9]=6;
    int N,M;
    cin>>N>>M;
    map<int,string>riyo;
    for(int i=0;i<M;i++){
        int a;
        cin>>a;
        riyo[joken[a]]=to_string(a);
    }
    string dp[N+1];
    string shoki="-";
    for(int i=0;i<N+1;i++){
        dp[i]=shoki;
    }
    dp[0]="";
    for(int i=1;i<N+1;i++){
        for(auto iter=riyo.begin();iter!=riyo.end();iter++){
            if(i-iter->first>=0){
                if(dp[i]=="-"){
                    if(dp[i-iter->first]=="-"){
                        continue;
                    }else{
                        dp[i]=dp[i-iter->first]+iter->second;
                    }

                }else{
                    if(dp[i-iter->first]=="-"){
                        continue;
                    }else{
                        if(dp[i].size()==(dp[i-iter->first]+iter->second).size()){
                            dp[i]=max(dp[i],dp[i-iter->first]+iter->second);
                        }else if(dp[i].size()<(dp[i-iter->first]+iter->second).size()){
                            dp[i]=dp[i-iter->first]+iter->second;

                        }
                    }

                }
            }
        }
    }
    cout<<dp[N]<<endl;

}

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

Score : 400 points

Problem Statement

Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:

Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).

The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectively.

Constraints

All values in input are integers.

2 \leq N \leq 10^4

1 \leq M \leq 9

1 \leq A_i \leq 9

A_i are all different.

There exists an integer that can be formed by exactly N matchsticks under the conditions.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

Print the largest integer that can be formed with exactly N matchsticks under the conditions in the problem statement.

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

The integer 777773 can be formed with 3 + 3 + 3 + 3 + 3 + 5 = 20 matchsticks, and this is the largest integer that can be formed by 20 matchsticks under the conditions.

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

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

Sample Input 3

15 3
5 4 6

Sample Output 3

654

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>
#include <algorithm>
using namespace std;
int n,k;
int abs(int x)
{
	return x>0?x:-x;
}
int main ()
{
	scanf("%d%d",&n,&k);
	if(abs(n)>=(k*2-1)) printf("YES");
	else printf("NO");
	return 0;
}

Score : 100 points

Problem Statement

Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1.

Constraints

1\leq N,K\leq 100

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

If we can choose K integers as above, print YES; otherwise, print NO.

Sample Input 1

3 2

Sample Output 1

YES

We can choose 1 and 3.

Sample Input 2

5 5

Sample Output 2

NO

Sample Input 3

31 10

Sample Output 3

YES

Sample Input 4

10 90

Sample Output 4

NO


#include<iostream>
#define loop(i,a,b) for(int i=a;i<b;i++)
#define rep(i,a) loop(i,0,a)
using namespace std;

int main(){
	int vertex[4];
	int a,b;
	rep(i,4)vertex[i]=0;
	rep(i,3){
		cin>>a>>b;
		vertex[a-1]++;
		vertex[b-1]++;
	}
	int even,odd;
	even=odd=0;
	bool check=true;
	rep(i,4){
		if(vertex[i]%2)odd++;
		else even++;
	}
	if(even==2&&odd==2)cout<<"YES"<<endl;
	else cout<<"NO"<<endl;
	return 0;
}

Score : 200 points

Problem Statement

There are four towns, numbered 1,2,3 and 4.
Also, there are three roads. The i-th road connects different towns a_i and b_i bidirectionally.
No two roads connect the same pair of towns. Other than these roads, there is no way to travel between these towns, but any town can be reached from any other town using these roads.

Determine if we can visit all the towns by traversing each of the roads exactly once.

Constraints

1 \leq a_i,b_i \leq 4(1\leq i\leq 3)

a_i and b_i are different. (1\leq i\leq 3)

No two roads connect the same pair of towns.

Any town can be reached from any other town using the roads.

Input

Input is given from Standard Input in the following format:

a_1 b_1
a_2 b_2
a_3 b_3

Output

If we can visit all the towns by traversing each of the roads exactly once, print YES; otherwise, print NO.

Sample Input 1

4 2
1 3
2 3

Sample Output 1

YES

We can visit all the towns in the order 1,3,2,4.

Sample Input 2

3 2
2 4
1 2

Sample Output 2

NO

Sample Input 3

2 1
3 2
4 3

Sample Output 3

YES


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

int main() {
    ll N, M;
    cin >> N >> M;
    vector<ll> X(M);
    for (int i = 0; i < M; i++) {
        cin >> X[i];
    }

    if (N >= M) cout << 0 << endl;
    else {
        sort(X.begin(), X.end());

        vector<ll> dist(M-1);
        for (int i = 0; i < M-1; i++) {
            dist[i] = X[i+1]-X[i];
        }

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

        ll sum = 0;
        for (int i = 0; i < M-N; i++) {
            sum += dist[i];
        }

        cout << sum << endl;
    }

    return 0;
}

Score : 300 points

Problem Statement

We will play a one-player game using a number line and N pieces.

First, we place each of these pieces at some integer coordinate.

Here, multiple pieces can be placed at the same coordinate.

Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:

Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.

Note that the coordinates where we initially place the pieces are already regarded as visited.

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

-10^5 \leq X_i \leq 10^5

X_1, X_2, ..., X_M are all different.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_M

Output

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

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.

Initially, put the two pieces at coordinates 1 and 10.

Move the piece at coordinate 1 to 2.

Move the piece at coordinate 10 to 11.

Move the piece at coordinate 11 to 12.

Move the piece at coordinate 12 to 13.

Move the piece at coordinate 13 to 14.

Sample Input 2

3 7
-10 -3 0 9 -100 2 17

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0


#include <bits/stdc++.h>
#include <numeric>
typedef long long ll;
#define rep(i,a,b) for(int i=a;i<b;++i)
#define rrep(i,a,b) for(int i=a;i>=b;--i)
using namespace std;

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

    int N, M; cin >> N >> M;
    if (N >= M) {
        cout << 0 << "\n";
        return 0;
    }

    vector<int> X(M);
    rep(i, 0, M) cin >> X[i];
    sort(X.begin(), X.end());

    vector<int> intervals(M-1);
    rep(i, 0, M-1) intervals[i] = X[i+1] - X[i];
    sort(intervals.begin(), intervals.end(), greater<int>());

    int res = X.back() - X.front();
    rep(i, 0, N-1) res -= intervals[i];

    cout << res << "\n";
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iomanip>
#include<vector>
#include<queue>
#include<deque>
#include<string>
#include<utility>
#include<cmath>
#include<algorithm>
#include<cctype>
#include<set>
#include<map>
#include<bitset>
#include<stack>
#include<ctime>
#include<cassert>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,int> pli;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vpii;
typedef vector<pli> vpli;

inline ll read(){
    ll Hashimoto=0;
	bool Kanna=1;
    char I_Love=getchar();
    while(I_Love<'0'||I_Love>'9'){
        if(I_Love=='-')Kanna=0;
        I_Love=getchar();
    }
    while(I_Love>='0'&&I_Love<='9'){
        Hashimoto=Hashimoto*10+I_Love-'0';
        I_Love=getchar();
    }
    return (Kanna?Hashimoto:-Hashimoto);
}
template<typename T1,typename T2> inline void Umax(T1 &a,T2 b){
	if(a<b)a=b;
}
template<typename T1,typename T2> inline void Umin(T1 &a,T2 b){
	if(a>b)a=b;
}

#define I_Love_Hashimoto_Kanna main
#define fastio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define filein(s) freopen(s,"r",stdin);
#define fileout(s) freopen(s,"w",stdout);
#define file freopen("I_Love_Hashimoto_Kanna.out","w",stdout);
#define RE cout<<"I_Love_Hashimoto_Kanna"<<endl;
#define Tone(Kanna) cout<<Kanna<<endl;
#define Tall(Hashimoto,Kanna) for(int I_Love=0;I_Love<(Kanna);++I_Love)cout<<Hashimoto[I_Love]<<(I_Love==(Kanna)-1?"\n":" ");
#define FOR(I_Love,Hashimoto,Kanna) for(int I_Love=Hashimoto;I_Love<(Kanna);++I_Love)
#define MP(Hashimoto,Kanna) make_pair(Hashimoto,Kanna)
#define REV(Kanna) reverse(Kanna.begin(),Kanna.end());
#define SORT(Kanna) sort(Kanna.begin(),Kanna.end());
#define UNIQUE(Kanna) Kanna.erase(unique(Kanna.begin(),Kanna.end()),Kanna.end());
#define inf (1000000000)
#define linf (1000000000000000000ll)
#define mod (1000000007)

int n,m;
int indegree[111111];
vi g[111111];
queue<int>q;
bool v[111111];
int ans[111111];

int I_Love_Hashimoto_Kanna() {
	//完全想清楚了再开始写。
	//写不顺、不知道怎么写、很乱的时候，停下来好好想想。
	//做得慢总比做不出好。
	fastio;
	n=read();m=read();
	FOR(i,1,n+m){
		int a=read()-1,b=read()-1;
		g[a].push_back(b);
		indegree[b]++;
	}
	int root=-1;
	FOR(i,0,n){
		if(indegree[i]==0)root=i;
	}
	assert(root!=-1);
	ans[root]=-1;
	v[root]=1;
	q.push(root);
	while(!q.empty()){
		int x=q.front();
		q.pop();
		FOR(i,0,g[x].size()){
			int to=g[x][i];
			ans[to]=x;
			if(v[to])continue;
			q.push(to);
			v[to]=1;
		}
	}
	FOR(i,0,n){
		printf("%d\n",ans[i]+1);
	}

	return 0;
}

Score : 500 points

Problem Statement

There is a rooted tree (see Notes) with N vertices numbered 1 to N.
Each of the vertices, except the root, has a directed edge coming from its parent.
Note that the root may not be Vertex 1.

Takahashi has added M new directed edges to this graph.
Each of these M edges, u \rightarrow v, extends from some vertex u to its descendant v.

You are given the directed graph with N vertices and N-1+M edges after Takahashi added edges.
More specifically, you are given N-1+M pairs of integers, (A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M}), which represent that the i-th edge extends from Vertex A_i to Vertex B_i.

Restore the original rooted tree.

Notes

For "tree" and other related terms in graph theory, see the article in Wikipedia, for example.

Constraints

3 \leq N

1 \leq M

N + M \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

If i \neq j, (A_i, B_i) \neq (A_j, B_j).

The graph in input can be obtained by adding M edges satisfying the condition in the problem statement to a rooted tree with N vertices.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_{N-1+M} B_{N-1+M}

Output

Print N lines.
In the i-th line, print 0 if Vertex i is the root of the original tree, and otherwise print the integer representing the parent of Vertex i in the original tree.

Note that it can be shown that the original tree is uniquely determined.

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

It can be seen that this graph is obtained by adding the edge 1 \rightarrow 3 to the rooted tree 1 \rightarrow 2 \rightarrow 3.

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2


/////////////////////////   _LeMur_
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cassert>
#include <bitset>
#include <cstdio>
#include <vector>
#include <string>
#include <ctime>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <list>
#include <map>
#include <set>

using namespace std;

const int N = 100005;
const int inf = 1000 * 1000 * 1000;
const int mod = 1000 * 1000 * 1000 + 7;

int n , m;
int cnt[N];

int a[N] , b[N] , c[N];

pair <int,int> p[N];
vector <int> g[N];
bool used[N];

int parent[N] , sz[N] , edge[N];
long long sum[N];

bool mark[N];

int findher(int a){
    if(a == parent[a])return a;
    return parent[a] = findher(parent[a]);
}

void tmerge(int a,int b){
    a = findher(a);
    b = findher(b);
    if(sz[a] < sz[b])
        swap(a , b);
    parent[b] = a;
    sum[a] += sum[b];
    sz[a] += sz[b];
    edge[a] += edge[b];
    for(int j=0;j<(int)g[b].size();j++){
        g[a].push_back(g[b][j]);
    }
    g[b].clear();
}

int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%d",&cnt[i]);
        ///
        parent[i] = i;
        sum[i] = cnt[i];
        sz[i] = 1;
    }
    for(int i=1;i<=m;i++){
        scanf("%d%d%d",&a[i],&b[i],&c[i]);
        p[i] = make_pair(c[i] , i);
    }
    sort(p + 1 , p + m + 1);
    int ind = -1;
    for(int i=1;i<=m;i++){
        int x = p[i].first;
        int id = p[i].second;
        int aa = a[id] , bb = b[id];
        if(findher(aa) != findher(bb)){
            tmerge(aa , bb);
        }
        int P = findher(aa);
        ++edge[P];
        if(sum[P] >= 1ll * x){
            mark[i] = true;
            ind = i;
        }
    }
    if(ind == -1){
        cout<<m<<endl;
        return 0;
    }
    for(int i=1;i<=n;i++){
        parent[i] = i;
        sum[i] = cnt[i];
        sz[i] = 1;
        g[i].push_back(i);
        edge[i] = 0;
    }
    for(int i=1;i<=ind;i++){
        int x = p[i].first;
        int id = p[i].second;
        int aa = a[id] , bb = b[id];
        if(findher(aa) != findher(bb)){
            tmerge(aa , bb);
        }
        int p = findher(aa);
        edge[p]++;
    }
    int answ = 0;
    for(int i=ind;i>=1;i--){
        int v = a[ p[i].second ];
        if(mark[i] && used[v] == false){
            v = findher(v);
            answ += edge[v];
            for(int j=0;j<(int)g[v].size();j++){
                int to = g[v][j];
                used[to] = true;
            }
        }
    }
    cout<<m - answ<<endl;
    return 0;
}

Score : 800 points

Problem Statement

There is a connected undirected graph with N vertices and M edges.
The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Also, each of these vertices and edges has a specified weight.
Vertex i has a weight of X_i; Edge i has a weight of Y_i and connects Vertex A_i and B_i.

We would like to remove zero or more edges so that the following condition is satisfied:

For each edge that is not removed, the sum of the weights of the vertices in the connected component containing that edge, is greater than or equal to the weight of that edge.

Find the minimum number of edges that need to be removed.

Constraints

1 \leq N \leq 10^5

N-1 \leq M \leq 10^5

1 \leq X_i \leq 10^9

1 \leq A_i < B_i \leq N

1 \leq Y_i \leq 10^9

(A_i,B_i) \neq (A_j,B_j) (i \neq j)

The given graph is connected.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_N
A_1 B_1 Y_1
A_2 B_2 Y_2
:
A_M B_M Y_M

Output

Find the minimum number of edges that need to be removed.

Sample Input 1

4 4
2 3 5 7
1 2 7
1 3 9
2 3 12
3 4 18

Sample Output 1

2

Assume that we removed Edge 3 and 4.
In this case, the connected component containing Edge 1 contains Vertex 1, 2 and 3, and the sum of the weights of these vertices is 2+3+5=10.
The weight of Edge 1 is 7, so the condition is satisfied for Edge 1.
Similarly, it can be seen that the condition is also satisfied for Edge 2.
Thus, a graph satisfying the condition can be obtained by removing two edges.

The condition cannot be satisfied by removing one or less edges, so the answer is 2.

Sample Input 2

6 10
4 4 1 1 1 7
3 5 19
2 5 20
4 5 8
1 6 16
2 3 9
3 6 16
3 4 1
2 6 20
2 4 19
1 2 9

Sample Output 2

4

Sample Input 3

10 9
81 16 73 7 2 61 86 38 90 28
6 8 725
3 10 12
1 4 558
4 9 615
5 6 942
8 9 918
2 7 720
4 7 292
7 10 414

Sample Output 3

8


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
int main(void){
	int c,a,b; cin>>c>>a>>b;
	cout<<(a*c)/2<<endl;

}

Score : 100 points

Problem Statement

There is a right triangle ABC with ∠ABC=90°.

Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC.

It is guaranteed that the area of the triangle ABC is an integer.

Constraints

1 \leq |AB|,|BC|,|CA| \leq 100

All values in input are integers.

The area of the triangle ABC is an integer.

Input

Input is given from Standard Input in the following format:

|AB| |BC| |CA|

Output

Print the area of the triangle ABC.

Sample Input 1

3 4 5

Sample Output 1

6

This triangle has an area of 6.

Sample Input 2

5 12 13

Sample Output 2

30

This triangle has an area of 30.

Sample Input 3

45 28 53

Sample Output 3

630

This triangle has an area of 630.


Score : 200 points

Problem Statement

A sequence a=\{a_1,a_2,a_3,......\} is determined as follows:

The first term s is given as input.

Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd.

a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1.

Find the minimum integer m that satisfies the following condition:

There exists an integer n such that a_m = a_n (m > n).

Constraints

1 \leq s \leq 100

All values in input are integers.

It is guaranteed that all elements in a and the minimum m that satisfies the condition are at most 1000000.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum integer m that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

a=\{8,4,2,1,4,2,1,4,2,1,......\}. As a_5=a_2, the answer is 5.

Sample Input 2

7

Sample Output 2

18

a=\{7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1,4,2,1,......\}.

Sample Input 3

54

Sample Output 3

114


#include <iostream>
#include <string>
#include <algorithm>
#include <set>
#include <cmath>
#include <vector>
#include <numeric>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <queue>

using ll = long long int;
using ul = unsigned long long int;
const ll LL_MAX (1LL<<60);
const ll MOD (1000000007);

#define rep(i,s,e) for(ll i=(s); i<(e); i++)

using namespace std;

ll f(ll n)
{
    if (n%2==0) n/=2;
    else n=3*n+1;

    return n;
}

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

    ll s;
    cin >> s;
    unordered_set<ll> ss;

    ll cnt(0);
    while (true)
    {
        s = f(s);

        cnt++;

        if (ss.find(s)==ss.end())
            ss.insert(s);
        else
            break;
    }

    cout << cnt+1 << endl;

    return 0;
}


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

int main()
{
    int N;
    std::cin >> N;
    std::vector<int> H(N), X(N);
    for (int i = 0; i < N; i++)
    {
        X[i] = 0;
        std::cin >> H[i];
    }

    int cnt = 0;
    while (true)
    {
        bool e = false;
        bool s = false;
        int a = 0;
        for (int i = 0; i < N; i++)
        {
            int x = X[i];
            if (x < H[i])
            {
                s = true;
            }
            else if (x == H[i])
            {
                a++;
                if (s) cnt++;
                s = false;
            }
            if (s)
            {
                X[i]++;
            }
        }
        if (s)cnt++;
        if (a == N)break;
    }

    std::cout << cnt << std::endl;

    return 0;
}

Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221


#include<iostream>
using namespace std;
int main() {
    int n; cin >> n;
    int h[100] = {0};
    int Min = 100;
    for (int i = 0; i < n; ++i) {
        cin >> h[i];
        if (Min > h[i]) {
            Min = h[i];
        }
    }
    for (int i = 0; i < n; ++i) {
        h[i] -= Min;
    }
    int Delete = 0;
    int Sum = Min;
    for (int i = 0; i < n; ++i) {
        if (Delete < h[i]) {
            Delete = h[i];
        }
        if (h[i] != 0 && h[i + 1] == 0) {
            Sum += Delete;
            Delete = 0;
        }
    }
    cout << Sum << endl;
    return 0;
}


#include <iostream>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<int> f;
vector<int> c;
vector<int> c1;
vector<int> c2;
int main()
{
    int n;
    cin>>n;
    int a,b;
    cin>>a>>b;
    for(int i=0;i<n;i++)
    {

        int x;
        cin>>x;
        f.push_back(x);
    }

    for(int i=0;i<n;i++)
    {
        if(f[i]<=a )
        {
           c.push_back(f[i]);
        }
        if(f[i]>=a+1 && f[i]<=b)
        {

            c1.push_back(f[i]);
        }
        if(f[i]>=b+1)
        {

            c2.push_back(f[i]);
        }
    }
    cout<<min(c2.size(),min(c1.size(),c.size()))<<endl;
    return 0;
}

Score : 100 points

Problem Statement

It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board.

The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns.

How many ways are there to choose where to put the notice so that it completely covers exactly HW squares?

Constraints

1 \leq H, W \leq N \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
H
W

Output

Print the answer.

Sample Input 1

3
2
3

Sample Output 1

2

There are two ways to put the notice, as follows:

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

Here, # represents a square covered by the notice, and . represents a square not covered.

Sample Input 2

100
1
1

Sample Output 2

10000

Sample Input 3

5
4
2

Sample Output 3

8


#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>
#include<vector>
#include<map>
using namespace std;
/*
time:
wa:
反省:
考察:
*/
int main() {
    int N;
    cin >> N;
    int a, b;
    cin >> a >> b;
    int p[110];
    int ans;
    int q1 = 0;
    int q2 = 0;
    int q3 = 0;
    for(int i = 0; i < N; i++) {
        cin >> p[i];
    }
    for(int i = 0; i < N; i++){
        if(p[i] <= a) q1++;
        else if(a+1 <= p[i] && p[i] <= b) q2++;
        else q3++;
    }
    ans = min(min(q1, q2),q3);
    cout << ans << endl;
    return 0;
}

Score : 200 points

Problem Statement

You have written N problems to hold programming contests.
The i-th problem will have a score of P_i points if used in a contest.

With these problems, you would like to hold as many contests as possible under the following condition:

A contest has three problems. The first problem has a score not greater than A points, the second has a score between A + 1 and B points (inclusive), and the third has a score not less than B + 1 points.

The same problem should not be used in multiple contests.
At most how many contests can be held?

Constraints

3 \leq N \leq 100

1 \leq P_i \leq 20 (1 \leq i \leq N)

1 \leq A < B < 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A B
P_1 P_2 ... P_N

Output

Print the answer.

Sample Input 1

7
5 15
1 10 16 2 7 20 12

Sample Output 1

2

Two contests can be held by putting the first, second, third problems and the fourth, fifth, sixth problems together.

Sample Input 2

8
3 8
5 5 5 10 10 10 15 20

Sample Output 2

0

No contest can be held, because there is no problem with a score of A = 3 or less.

Sample Input 3

3
5 6
5 6 10

Sample Output 3

1


#include<bits/stdc++.h>
using namespace std;
#define gc getchar_unlocked
#define pb push_back
#define fo(i,n) for(int i=0;i<n;i++)
#define fo1(i,n) for(int i=1;i<n;i++)
#define Fo(i,k,n) for(i=k;k<n?i<n:i>n;k<n?i+=1:i-=1)
#define ll long long
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl
#define all(x) x.begin(), x.end()
#define clr(x) memset(x, 0, sizeof(x))
#define sortall(x) sort(all(x))
#define PI 3.1415926535897932384626
#define setbits(x)      __builtin_popcountll(x)
#define zrobits(x)      __builtin_ctzll(x)
#define mod             1000000007
#define inf             1e18
#define ps(x,y)         fixed<<setprecision(y)<<x
#define mk(type,arr,n)  type *arr=new type[n];
#define w(x)            int x; cin>>x; while(x--)
//=======================
typedef pair<int, int>  pii;
typedef vector<int>     vi;
typedef vector<pii>     vpii;
typedef vector<vi>      vvi;
//=======================
const int MOD = 1000000007;
const int N = 300005, M = N;
//=======================
vi g[N],adj[N];
int n, m, s, w, W, S, k, i, l, j, p, q, pr, fi, md;

void abhinay()
{

    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif

}

int main(){
    abhinay();
    cin>>n>>k;
    int dp[100005][3];
    vi A(n+1),B(n+1),C(n+1);
    fo(i,n) cin>>A[i]>>B[i]>>C[i];
    dp[0][0]=A[0],dp[0][1]=B[0],dp[0][2]=C[0];
    for (int i = 1; i < n; i++)
        for (int j =0;j<3;j++)
            for(int k=0;k<3;k++)
                if (j==k) continue;
                else{
                    if (j==0) dp[i][j]= max(dp[i][j],dp[i-1][k]+A[i]);
                    if (j==1) dp[i][j]= max(dp[i][j],dp[i-1][k]+B[i]);
                    if (j==2) dp[i][j]= max(dp[i][j],dp[i-1][k]+C[i]);
                    }
    int ret = 0;
    ret = max(ret,dp[n-1][0]);
    ret = max(ret,dp[n-1][1]);
    ret = max(ret,dp[n-1][2]);

    cout << ret;
    return 0;
}

Score : 100 points

Problem Statement

Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.

The vacation consists of N days.
For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:

A: Swim in the sea. Gain a_i points of happiness.

B: Catch bugs in the mountains. Gain b_i points of happiness.

C: Do homework at home. Gain c_i points of happiness.

As Taro gets bored easily, he cannot do the same activities for two or more consecutive days.

Find the maximum possible total points of happiness that Taro gains.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq a_i, b_i, c_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the maximum possible total points of happiness that Taro gains.

Sample Input 1

3
10 40 70
20 50 80
30 60 90

Sample Output 1

210

If Taro does activities in the order C, B, C, he will gain 70 + 50 + 90 = 210 points of happiness.

Sample Input 2

1
100 10 1

Sample Output 2

100

Sample Input 3

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

Sample Output 3

46

Taro should do activities in the order C, A, B, A, C, B, A.


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

void input(vector<vector<int> > &arr,int n,int m)
{
	for(int i=0;i<n;i++)
	{
		vector<int> temp;
		for(int j=0;j<m;j++)
		{
			int x;
			cin>>x;
			temp.push_back(x);
		}
		arr.push_back(temp);
		temp.clear();
	}
}
int main()
{
	int n;
	cin>>n;
	vector<vector<int> >arr;
	input(arr,n,3);
	vector<int>dp(n,0);
	int k=0;
	if(arr[0][0]>=arr[0][1] && arr[0][0]>=arr[0][2])
	   dp[0]=arr[0][0];
	else if(arr[0][1]>=arr[0][0] && arr[0][1]>=arr[0][2]){
		dp[0]=arr[0][1];
		k=1;
	}
	else{
	   dp[0]=arr[0][2];
	   k=2;
}
	for(int i=1;i<n;i++)
	{
		int x;
		for(int j=0;j<3;j++)
		{
			if(j!=k){
				if(dp[i]<arr[i][j]+dp[i-1])
				{
					dp[i]=arr[i][j]+dp[i-1];
					x=j;
				}
			}
		}
		k=x;
	}
  cout<<dp[n-1]<<"\n";
}


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

#define ll              long long
#define pb              push_back
#define ppb             pop_back
#define endl            '\n'
#define mii             map<ll,ll>
#define pii             pair<ll,ll>
#define vi              vector<ll>
#define vs              vector<string>
#define all(a)          (a).begin(),(a).end()
#define F               first
#define S               second
#define sz(x)           (ll)x.size()
#define hell            1000000007
#define inf             (ll)1e18 + 5
#define PI              3.14159265358979323844
#define rep(i,a,b)      for (ll i=a;i<b;i++)
#define repr(i,a,b)     for (ll i=a-1;i>=b;i--)
#define lbnd            lower_bound
#define ubnd            upper_bound
#define mp              make_pair
#define ios             ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define ordered_set     tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define trace(...)      __f(#__VA_ARGS__, __VA_ARGS__)

template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
    std::cerr << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
    const char* comma = strchr(names + 1, ',');std::cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}

using namespace std;
using namespace __gnu_pbds;

/*----------------------Graph Moves----------------*/
//const int fx[]={+1,-1,+0,+0};
//const int fy[]={+0,+0,+1,-1};
//const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1};   // Kings Move
//const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1};  // Kings Move
//const int fx[]={-2, -2, -1, -1,  1,  1,  2,  2};  // Knights Move
//const int fy[]={-1,  1, -2,  2, -2,  2, -1,  1}; // Knights Move
/*------------------------------------------------*/

//primes for hashing 937,991,1013,1409,1741

ll n;
vi a,b,c;
ll dp[100005][3];

ll find(ll n,ll i){
	if (n<=0)return 0;
	if (dp[n][i]!=-1)return dp[n][i];
	if (i==0){
		dp[n][i]=a[n-1];
		ll meow=max(find(n-1,1),find(n-1,2));
		dp[n][i]+=max(meow,find(n-2,0));
	}
	else if (i==1){
		dp[n][i]=b[n-1];
		ll meow=max(find(n-1,0),find(n-1,2));
		dp[n][i]+=max(meow,find(n-2,1));
	}
	else {
		dp[n][i]=c[n-1];
		ll meow=max(find(n-1,1),find(n-1,0));
		dp[n][i]+=max(meow,find(n-2,2));
	}
	return dp[n][i];
}

void solve() {
    cin>>n;
    memset(dp,-1,sizeof dp);
    rep(i,0,n){
    	ll x,y,z;
    	cin>>x>>y>>z;
    	a.pb(x),b.pb(y),c.pb(z);
    }
    find(n,0);
    find(n,1);
    find(n,2);
    cout<<max(dp[n][0],max(dp[n][1],dp[n][2]))<<endl;
}

signed main() {
    ios
    ll test=1;
    //cin>>test;
    while (test--) solve();
    return 0;
}


//template by I_Love_Totoro, inspired by chamow
//Doing VC Everyday #SpecialistByMarch
//refer cook_book and AC  of/Ubuntu folder _FunWithCP_ dated:16/03/2020- for POC and more insights respectively
//interactive comments ahead! : for the love of CP <3
//note to self:for the love of everything good, uncomment fastread whenever applicable :)

/* footnotes/ obs
*
*/

/*main idea:
*
*/

/*similar to:
*
*/

/*re-learnt/ got better clarity
*
*/

/*corollary
*
*/

#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define rep(i,a,n) for(i=a;i<n;i++)
#define repe(i,a,n) for(i=a;i<=n;i++)
#define repn(i,a,n) for(i=n;i>=a;i--)
#define all(x) (x).begin(),(x).end()
#define PI (atan(1)*4)
#define INF (int)1e9

#define fastread ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
//typedef vec vector<ll>
typedef long long ll;
typedef long double ld;
typedef long int li;

using namespace std;

ll lcm(ll val1,ll val2)
{
	if(val1==0||val2==0)
		return 0;
	else
		return (val1*val2)/__gcd(val1,val2);
}

ll pw(ll base,ll p)
{
	if(base==1||p==0)
		return 1;
	if(p%2==0){
		ll interm=pw(base,p/2);
		return interm*interm;

	}
	else
		return base*pw(base,p-1);

}

int main()
{

	//fastread;
	/*
	freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    */

	ll n, a, b, c, ansa = 0, ansb = 0, ansc = 0;
	cin>>n;

	vector<vector<ll>>dp(n,vector<ll>(3,0));

	for (ll i = 0; i < n; i ++) {
		cin>>a>>b>>c;

		if (i == 0)
			ansa += a,ansb += b,ansc += c;//dp[i][0] = a, dp[i][1] = b, dp[i][2] = c;
		else {
			/*dp[i][0]*/ansa += max(b,c);
			ansb += max(a,c);
			ansc += max(a,b);
		}
	}
	cout<<max(ansa,max(ansb,ansc))<<"\n";//max(dp[n-1][0],max(dp[n-1][1],dp[n-1][2]))<<"\n";
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
const double eps=1e-6,pi=acos(-1);
const int N=1e3+5,M=1e9+7,SEGM=4*N,OO=0x3f3f3f3f;
int t,n,W;
int p[N],w[N];
map<pair<int,int>,int>mp;

int solve(int i,int remW){
    if(i==n) return 0;
    if(mp.find({i,remW})!=mp.end()) return mp[{i,remW}];
    return mp[{i,remW}]=max(solve(i+1,remW),remW-w[i]>=0?solve(i+1,remW-w[i])+p[i]:(int)-1e9);
}

int main(){
    //freopen("myfile.txt","w",stdout);
    scanf("%d%d",&n,&W);
    for(int i=0;i<n;++i)
        scanf("%d%d",w+i,p+i);
    printf("%d",solve(0,W));
    return 0;
}

Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^9

1 \leq w_i \leq W

1 \leq v_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

1 1000000000
1000000000 10

Sample Output 2

10

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.


#include <bits/stdc++.h>

using namespace std;
using ll = long long;
const ll inf = 1e18 + 5;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n, W, V = 0;
  cin >> n >> W;
  vector<int> w(n), v(n);
  for(int i = 0; i < n; i++) cin >> w[i] >> v[i];
  for(int i = 0; i < n; i++) V += v[i];
  vector<vector<ll>> dp(n + 1, vector<ll> (V + 1, inf));
  for(int i = 0; i <= n; i++) dp[i][0] = 0LL;
  for(int i = 1; i <= n; i++) {
    for(int j = 1; j <= V; j++) {
      if(j >= v[i - 1] && dp[i - 1][j - v[i - 1]] < inf) {
        dp[i][j] = min(dp[i - 1][j], (ll)w[i - 1] + dp[i - 1][j - v[i - 1]]);
      } else {
        dp[i][j] = dp[i - 1][j];
      }
    }
  }
  ll ans = 0;
  for(int j = 1; j <= V; j++) {
    if(dp[n][j] <= W) ans = j;
  }
  cout << ans << '\n';
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll inf=1e18;
int main()
{
	int n,W;
	cin>>n>>W;
	int w[n],v[n];
	for(int  i=0;i<n;i++)cin>>w[i]>>v[i];
	ll dp[1010*n];
	for(int i=0;i< 1010*n;i++)dp[i]=inf;
	for(int i=0;i<n;i++)
	{
		for(int x= 1000*n;x>=0;x--)
		{
			dp[x]=min(dp[x-v[i]]+w[i], dp[x]);
		}
	}
	ll a=-1;
	for(int i=(1000*n);i>=0;i--)
	{
		if(dp[i]<=W){cout<<i+1;break;}
	}

}


#include <iostream>
#include <vector>
#include <limits>

using namespace std;

vector <int> c(101), g(101);

int main()
{
    int n, w;
    long long sumMax = 0;
    cin >> n >> w;

    for (int i = 1; i <= n; i++)
    {
        cin >> g[i] >> c[i];
        sumMax += c[i];
    }

    vector<vector<long long>> dp(105, vector<long long>(100005, sumMax + 1));

    dp[0][0] = 0;
    int ans = 0;

    for (int i = 1; i <= n; i++)
        for (int j = 0; j <= sumMax; j++)
        {
            long long localBest = dp[i - 1][j];

            if (j >= c[i] && dp[i - 1][j - c[i]] != sumMax + 1)
            {
                localBest = dp[i - 1][j - c[i]] + g[i];
                localBest = min(localBest, dp[i - 1][j]);
            }
            dp[i][j] = localBest;

            if(dp[i][j] <= w)
                ans = max(ans, j);
        }

    cout << ans;

    return 0;
}


#include <bits/stdc++.h>
#define debug(a) cout <<  #a << " = " << a << endl;
using ll = long long;
using namespace std;

const ll inf = 100000000000000;
const int N = 100;
int w[N],v[N];
ll dp[200000];

// here dp[i] = minimum weight to make value exactly i

int main(int argc, char const *argv[])
{
    int cap = 0,n;
    for(int i =0 ;i < 200000;i++)dp[i] = inf;
    // here dp[i] = minimum weight to make value exactly i
    scanf("%d%d",&n,&cap);
    dp[0] = 0;
    for(int i = 0; i < n;i++){
        scanf("%d %d",&w[i],&v[i]);
        for(int x = 100000;x>=0;x--){
            if(x-v[i]>=0){
                dp[x] = min(dp[x],dp[x-v[i]]+w[i]);
            }
        }
    }
    ll ans = 0;
    //for(int i = 0; i <= 200;i++){
       // printf("%d = %lld\n",i,dp[i]);
    //}
    for(int i = 100004 ; i >=0 ; i--){
        if(dp[i] <= cap){ans = i;break;}
    }
    printf("%lld\n",ans);
    return 0;
}


#include<bits/stdc++.h>
#define forn(i,a,b) for(long long i=a;i<=b;i++)
#define fork(i,a,b,k) for(long long i=a;i<=b;i+=k)
using namespace std;
typedef long long ll;
vector<int>child[100005],parent[100005];
queue<int>q;
int used[100005],dist[100005];
int n,m,x[100005],y[100005],mx;
void bfs(int s){
	dist[s]=0;
	q.push(s);
	used[s]=1;
	while(!q.empty()){
		int v=q.front();
		q.pop();
		for(int u : parent[v]){
			dist[u]=dist[v]+1;
			mx=max(mx,dist[u]);
			q.push(u);
		}
	}
}
int main(){
	ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cin>>n>>m;
	for(ll i=1;i<=m;i++){
		cin>>x[i]>>y[i];
		parent[y[i]].push_back(x[i]);
		child[x[i]].push_back(y[i]);
	}
	for(int i=1;i<=n;i++){
		if(child[y[i]].empty()){
			bfs(y[i]);
		}
	}
	cout<<mx;
}

Score : 100 points

Problem Statement

There is a directed graph G with N vertices and M edges.
The vertices are numbered 1, 2, \ldots, N, and for each i (1 \leq i \leq M), the i-th directed edge goes from Vertex x_i to y_i.
G does not contain directed cycles.

Find the length of the longest directed path in G.
Here, the length of a directed path is the number of edges in it.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq x_i, y_i \leq N

All pairs (x_i, y_i) are distinct.

G does not contain directed cycles.

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the length of the longest directed path in G.

Sample Input 1

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

Sample Output 1

3

The red directed path in the following figure is the longest:

Sample Input 2

6 3
2 3
4 5
5 6

Sample Output 2

2

The red directed path in the following figure is the longest:

Sample Input 3

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

Sample Output 3

3

The red directed path in the following figure is one of the longest:


#include<bits/stdc++.h>
#define ll          long long
#define pb          push_back
#define endl        '\n'
#define pii         pair<ll int,ll int>
#define vi          vector<ll int>
#define all(a)      (a).begin(),(a).end()
#define F           first
#define S           second
#define sz(x)       (ll int)x.size()
#define hell        1000000001
#define r(i,a,b)    for(i=a;i<b;i++)
#define ra(i,a,b)   for(i=a;i<=b;i++)
#define lbnd        lower_bound
#define ubnd        upper_bound
#define bs          binary_search
#define mp          make_pair
#define ss          set<ll int>
using namespace std;

#define N 1000000
#define M 100000000

struct unit {
  ll int a[N];
};

ll fact (ll int x)
{if(x==1 || x==0)return 1;
else return x*fact(x-1);}

ll power(ll int x,ll int n)
{if(n==0)return 1;
else if(n%2 == 0)return power(x*x,n/2);
else return x*power(x*x,(n-1)/2);}

bool cmp (const pii&a,const pii&b)
{ return((a.F-a.S) > (b.F-b.S));
/*if(a.S<=b.S){if(a.S==b.S)return a.F<b.F;else return a.S<b.S;}
else return a.S<b.S;*/}

int main()
{
    cin.tie(0), cin.sync_with_stdio(0), cout.tie(0), cout.sync_with_stdio(0);
    ll i,j,k,l,m,n,a=0,b=0;
    cin>>n>>m;
    vector<pii> v;
    r(i,0,m)
    {
        cin>>k>>l;
        v.pb(mp(k,l));
    }
    ll dp[n+1];
    memset(dp,0,sizeof(dp));
    r(j,0,m)
    dp[v[j].S]=1;
    r(j,0,m)
    dp[v[j].S]=max(dp[v[j].S],dp[v[j].F]+1);
    cout<<*max_element(dp,dp+n+1);
}


#include <bits/stdc++.h>

using namespace std;

using ll = long long;

const int INF = 1e9 + 5;

template<typename T>
void min_self(T& a, T b)
{
    a = min(a,b);
}

template<typename T>
void max_self(T& a, T b)
{
    a = max(a,b);
}

const int Nax=1e5 + 5;

vector<int> edges[Nax];
bool visited[Nax];
int dist[Nax];
int in[Nax];

void dfs(int a)
{
    //visited[a] = true;

    for(int b: edges[a])
    {
        dist[b] = max(dist[b],1+dist[a]);

        if(--in[b] == 0)
        {
            dfs(b);
        }
    }
}

int main() {

    ios::sync_with_stdio(0);
    cin.tie(0);

    int N, M;
    cin >> N >> M;

    int a, b;

    while(M--)
    {
        cin >> a >> b;
        edges[a].push_back(b);

        ++in[b];
    }

    for(int i=1; i<=N; ++i)
    {
        if(/*!visited[i] && */in[i] == 0)
        {
            dfs(i);
        }
    }

    cout << *max_element(dist+1,dist+N+1);

}


Score : 100 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns.
Let (i, j) denote the square at the i-th row from the top and the j-th column from the left.

For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is described by a character a_{i, j}.
If a_{i, j} is ., Square (i, j) is an empty square; if a_{i, j} is #, Square (i, j) is a wall square.
It is guaranteed that Squares (1, 1) and (H, W) are empty squares.

Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right or down to an adjacent empty square.

Find the number of Taro's paths from Square (1, 1) to (H, W).
As the answer can be extremely large, find the count modulo 10^9 + 7.

Constraints

H and W are integers.

2 \leq H, W \leq 1000

a_{i, j} is . or #.

Squares (1, 1) and (H, W) are empty squares.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W}

Output

Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 + 7.

Sample Input 1

3 4
...#
.#..
....

Sample Output 1

3

There are three paths as follows:

Sample Input 2

5 2
..
#.
..
.#
..

Sample Output 2

0

There may be no paths.

Sample Input 3

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

Sample Output 3

24

Sample Input 4

20 20
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................

Sample Output 4

345263555

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


#include <bits/stdc++.h>
#define lli long long int
#define ld long double
#define rep(i,n) for(int i = 0; i < n; i++)
#define reps(i,a,n) for(int i = a; i < n; i++)
#define s(n) cin >> n
#define csl ios_base::sync_with_stdio(false); cin.tie(NULL)
#define rsz(x,n) x.clear(); x.resize(n)
#define rrsz(x,a,n) x.clear(); x.resize(n,a)
#define wt while(true)
#define all(x) x.begin(),x.end()
#define pb push_back
#define ls(x) ((2*(x)) + 1)
#define rs(x) ((ls(x)) + 1)
#define md(a,b) (((a) + (b))/2)
#define INF (1e9 + 7)

using namespace std;

int main()
{
    lli n;s(n);
    vector<ld>a(n+1);
    rep(i,n)
    {
        ld b;s(b);
        a[i+1]=b;
    }
    vector<vector<ld>>vec(n+1,vector<ld>(n+1,0));
    vec[0][0]=1;
    reps(i,1,n+1)
    vec[i][0]=vec[i-1][0]*(1-a[i]);
    vec[1][1]=a[1];
    reps(i,2,n+1)
    {
        reps(j,1,i+1)
        {
            vec[i][j]+=((vec[i-1][j-1])*(a[i])+(vec[i-1][j])*(1-a[i]));
        }
    }
     /*reps(i,1,n+1)
    cout<<vec[n][i]<<" ";*/

    ld sum=0;
    reps(i,(n/2)+1,n+1)
    sum+=vec[n][i];
    cout<<fixed<<setprecision(10)<<sum;
    return 0;
}

Score : 100 points

Problem Statement

Let N be a positive odd number.

There are N coins, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), when Coin i is tossed, it comes up heads with probability p_i and tails with probability 1 - p_i.

Taro has tossed all the N coins.
Find the probability of having more heads than tails.

Constraints

N is an odd number.

1 \leq N \leq 2999

p_i is a real number and has two decimal places.

0 < p_i < 1

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 \ldots p_N

Output

Print the probability of having more heads than tails.
The output is considered correct when the absolute error is not greater than 10^{-9}.

Sample Input 1

3
0.30 0.60 0.80

Sample Output 1

0.612

The probability of each case where we have more heads than tails is as follows:

The probability of having (Coin 1, Coin 2, Coin 3) = (Head, Head, Head) is 0.3 × 0.6 × 0.8 = 0.144;

The probability of having (Coin 1, Coin 2, Coin 3) = (Tail, Head, Head) is 0.7 × 0.6 × 0.8 = 0.336;

The probability of having (Coin 1, Coin 2, Coin 3) = (Head, Tail, Head) is 0.3 × 0.4 × 0.8 = 0.096;

The probability of having (Coin 1, Coin 2, Coin 3) = (Head, Head, Tail) is 0.3 × 0.6 × 0.2 = 0.036.

Thus, the probability of having more heads than tails is 0.144 + 0.336 + 0.096 + 0.036 = 0.612.

Sample Input 2

1
0.50

Sample Output 2

0.5

Outputs such as 0.500, 0.500000001 and 0.499999999 are also considered correct.

Sample Input 3

5
0.42 0.01 0.42 0.99 0.42

Sample Output 3

0.3821815872


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

int n;
double p[maxn];
double dp[maxn][maxn];

int main() {
	scanf("%d",&n);
	for( int i = 1 ; i <= n ; i++ )
		scanf("%lf",&p[i]);
	dp[0][0] = 1;
	for( int i = 1 ; i <= n ; i++ )
		for( int j = 0 ; j <= i ; j++ ) {
			if(j)
				dp[i][j] = dp[i-1][j-1] * p[i];
			dp[i][j] += dp[i-1][j] * (1-p[i]);
		}
	double ans = 0;
	for( int i = n/2+1 ; i <= n ; i++ )
		ans += dp[n][i];
	printf("%.10lf\n",ans);
	return 0;
}


// Author - Saikat_7
#include <bits/stdc++.h>
using namespace std;
#define fl(i,a,b) for(int i=a;i<b;i++)
#define trav(i,cont) for(const auto& i:cont)
#define cs(x) cout<<x<<" "
#define cn(x) cout<<x<<" "<<endl
#define ll long long int
#define endl '\n'
#define pb push_back
#define ff first
#define ss second
#define mod 1000000007 //998244353
#define inf 1e17
const int mx = 2999; // 2* (10 to power 5);
double dp[3000][3000];
double coins(double arr[],int n, int h)
{	if(dp[n][h]==-1)
	{
	if(h==0|| n==0)
		dp[n][h]= 1;
	else if(h<n)
		dp[n][h]=arr[n-1]*coins(arr,n-1,h-1) + (1-arr[n-1])*coins(arr,n-1,h);
	else if(h==n)
		dp[n][h]=arr[n-1]*coins(arr,n-1,h-1);
	else
		dp[n][h]=0;
		return dp[n][h];;
	}
	else
		return dp[n][h];

}
int main()
{
    ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
    int tc=1;
    // cin>>tc;
    while(tc-- > 0)
    {
   		int n;
   		cin>>n;
   		double arr[n];
   		int h=n/2+1;
   		for(int i=0;i<=n;i++)
   		{
   			for (int j=0;j<=h;j++)
   				dp[i][j]=-1;
   		}
   		for(int i=0;i<n;i++)
   		{
   			cin>>arr[i];
   		}
   		double ans=coins(arr,n,(n/2)+1);
   		cout<<ans;
    }
    return 0;
}


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

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

// DON'T USE THESE MACROS DURING ICPC PRACTICE
#define For(i,n) for (int i=0; i<n; i++)
#define FOR(i,a,b) for (int i=a; i<=b; i++)
#define Down(i,n) for (int i=n-1; i>=0; i--)
#define DOWN(i,a,b) for (int i=b; i>=a; i--)

typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef pair<ld,ld> pdd;
typedef complex<ld> pt;
typedef vector<pt> pol;
typedef vector<int> vi;

const char nl = '\n';
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3f;
const ll MOD = 1e9+7;
const ld EPS = 1e-10;
mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cout << fixed << setprecision(17);

	int n;
	cin >> n;

	ld p[n+1];
	FOR(i,1,n) {
		cin >> p[i];
	}

	ld dp[n+1][n/2+1];
	fill(dp[0], dp[0]+n/2+1, 0);
	dp[0][0] = 1;
	FOR(i,1,n) {
		For(j,n/2+1) {
			dp[i][j] = dp[i-1][j] * p[i];
			if (j>0) dp[i][j] += dp[i-1][j-1] * (1-p[i]);
		}
	}

	ld ans = 0;
	For(j,n/2+1) {
		ans += dp[n][j];
	}
	cout << ans << nl;

	return 0;
}


//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//#pragma GCC optimize("unroll-loops")

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

using namespace std;

typedef pair <int, int> pii;
typedef pair <long long, long long> pll;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;

#define endl "\n"
#define mt make_tuple
#define mp make_pair

template <typename T1, typename T2>
bool umax(T1 &a, const T2&b) { return a < b ? a = b, 1 : 0;}
template <typename T1, typename T2>
bool umin(T1 &a, const T2 &b) {return a > b ? a = b, 1 : 0;}
template <typename T>
T sqr(T a) {return a * a;}

mt19937 rng(20010709);
const int mod = 1000000007;
const int INF = 1000000001;

int n;
ld dp[3000][6005], p[3000];
ld result;

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

    cin >> n;

    for (int i = 1; i <= n; i++)
        cin >> p[i];

    dp[0][0 + n] = 1;

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n * 2; j++) {
            dp[i][j + 1] += dp[i - 1][j] * p[i];
            dp[i][j - 1] += dp[i - 1][j] * (1.0 - p[i]);
        }
    }

    for (int i = 1; i <= n; i++)
        result += dp[n][i + n];

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

    return 0;
}


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

#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define rep1(i, n) for (ll i = 1; i <= (ll)(n); i++)
#define INF 10000000000
#define MOD 1000000007
using ll = long long;
using Graph = vector<vector<ll>>;

ll dp[100100][2];//dp[v][color]
Graph G;

ll rec(int v, int color, int parent){
    if(dp[v][color]!=-1) return dp[v][color];
    ll res = 1;
    for(auto nv : G[v]){
        ll tmp = 0;
        if(nv != parent){
            if(!color) (tmp += rec(nv,1,v)) %= MOD;
            (tmp += rec(nv,0,v)) %= MOD;
            tmp %= MOD;
            if(tmp!=0) (res *= tmp) %= MOD;
        }
    }
    res %= MOD;
    return dp[v][color] = res;
}

int main(){
    int N; cin>>N;
    G.resize(N);
    rep(i,N-1){
        int x,y; cin>>x>>y;
        x--;y--;
        G[x].push_back(y); G[y].push_back(x);
    }
    rep(i,100100)rep(j,2)dp[i][j] = -1;
    ll res = rec(0,0,-1);
    res += rec(0,1,-1);
    res %= MOD;
    cout<<res<<endl;
}

Score : 100 points

Problem Statement

There is a tree with N vertices, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.

Taro has decided to paint each vertex in white or black.
Here, it is not allowed to paint two adjacent vertices both in black.

Find the number of ways in which the vertices can be painted, modulo 10^9 + 7.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq x_i, y_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of ways in which the vertices can be painted, modulo 10^9 + 7.

Sample Input 1

3
1 2
2 3

Sample Output 1

5

There are five ways to paint the vertices, as follows:

Sample Input 2

4
1 2
1 3
1 4

Sample Output 2

9

There are nine ways to paint the vertices, as follows:

Sample Input 3

1

Sample Output 3

2

Sample Input 4

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

Sample Output 4

157


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define fr(i,j,k) for(int i=j;i<k;i++)
#define f(n) fr(i,0,n)
#define f1(n) fr(i,1,n+1)
#define pb push_back
#define F first
#define S second
#define all(x) x.begin(), x.end()
const int mod = 1e9 + 7;
const int maxn = 100005;
struct mat {
    ll a[100][100];
    int n;
    mat() {
        memset(a, 0, sizeof(a));
    }
    mat operator * ( const mat &b ) const {
        mat ret;
        ret.n =b.n;
        for( int i = 0; i < n; ++i )
            for( int j = 0; j < n; ++j )
                for( int k = 0; k < n; ++k )
                    ret.a[i][j] = ( ret.a[i][j] + a[i][k] * b.a[k][j] ) % mod;
        return ret;
    }
};
ll solve(ll n, ll k) {
	mat now;
	now.n = n;
	f(n) {
		fr(j,0,n) {
			cin >> now.a[i][j];
		}
	}
	mat ans;
	ans.n = n;
	f(n) {
		ans.a[i][0] = 1;
	}
	while (k) {
		if (k & 1) {
			ans = now * ans;
		}
		now = now * now;
		k >>= 1;
	}
	ll sum = 0;
	f(n) {
		sum += ans.a[i][0];
		sum %= mod;
	}
	return sum;
}
void go() {
	ll n, m, k;
	cin >> n >> k;
	cout << solve(n, k) << '\n';

}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int c = 0;
    int t;
    if (!c) {
        t = 1;
    }
    else {
        cin >> t;
    }
    while (t--) {
        go();
    }

}

Score : 100 points

Problem Statement

There is a simple directed graph G with N vertices, numbered 1, 2, \ldots, N.

For each i and j (1 \leq i, j \leq N), you are given an integer a_{i, j} that represents whether there is a directed edge from Vertex i to j.
If a_{i, j} = 1, there is a directed edge from Vertex i to j; if a_{i, j} = 0, there is not.

Find the number of different directed paths of length K in G, modulo 10^9 + 7.
We will also count a path that traverses the same edge multiple times.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 10^{18}

a_{i, j} is 0 or 1.

a_{i, i} = 0

Input

Input is given from Standard Input in the following format:

N K
a_{1, 1} \ldots a_{1, N}
:
a_{N, 1} \ldots a_{N, N}

Output

Print the number of different directed paths of length K in G, modulo 10^9 + 7.

Sample Input 1

4 2
0 1 0 0
0 0 1 1
0 0 0 1
1 0 0 0

Sample Output 1

6

G is drawn in the figure below:

There are six directed paths of length 2:

1 → 2 → 3

1 → 2 → 4

2 → 3 → 4

2 → 4 → 1

3 → 4 → 1

4 → 1 → 2

Sample Input 2

3 3
0 1 0
1 0 1
0 0 0

Sample Output 2

3

G is drawn in the figure below:

There are three directed paths of length 3:

1 → 2 → 1 → 2

2 → 1 → 2 → 1

2 → 1 → 2 → 3

Sample Input 3

6 2
0 0 0 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0
0 0 0 0 1 0
0 0 0 0 0 1
0 0 0 0 0 0

Sample Output 3

1

G is drawn in the figure below:

There is one directed path of length 2:

4 → 5 → 6

Sample Input 4

1 1
0

Sample Output 4

0

Sample Input 5

10 1000000000000000000
0 0 1 1 0 0 0 1 1 0
0 0 0 0 0 1 1 1 0 0
0 1 0 0 0 1 0 1 0 1
1 1 1 0 1 1 0 1 1 0
0 1 1 1 0 1 0 1 1 1
0 0 0 1 0 0 1 0 1 0
0 0 0 1 1 0 0 1 0 1
1 0 0 0 1 0 1 0 0 0
0 0 0 0 0 1 0 0 0 0
1 0 1 1 1 0 1 1 1 0

Sample Output 5

957538352

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


#include <bits/stdc++.h>
#define int long long
#define maxn 10005
#define maxc 105
using namespace std;

const int mod = 1e9 + 7;

//     len   sum  last
int dp[maxn][maxc][10] = {};
string s;
int n, k;

int32_t main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> s >> k;
    reverse(begin(s), end(s));
    n = s.size(); s = "@" + s;
    for(int i = 0; i < 10; i++) {
        dp[1][i % k][i] = 1;
    }
    for(int len = 2; len <= n; len++) {
        for(int sum = 0; sum < k; sum++) {
            for(int last = 0; last < 10; last++) {
                int prev = (sum - last + k) % k;
                for(int i = 0; i < 10; i++)
                dp[len][sum][last] += dp[len - 1][prev][i];
                dp[len][sum][last] %= mod;
            }
        }
    }
    int ans = 0, cnt = 0;
    for(int i = n; i > 0; i--) {
        for(int j = 0; j < (s[i] - '0'); j++) {
            int prev = (k - cnt + k) % k;
            ans += dp[i][prev][j];
        }
        ans %= mod;
        cnt += s[i] - '0';
    }
    if(cnt % k == 0) ans++;
    ans = (ans - 1 + mod) % mod;
    cout << ans << '\n';
    return 0;
}

Score : 100 points

Problem Statement

Find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo 10^9 + 7:

The sum of the digits in base ten is a multiple of D.

Constraints

All values in input are integers.

1 \leq K < 10^{10000}

1 \leq D \leq 100

Input

Input is given from Standard Input in the following format:

K
D

Output

Print the number of integers satisfying the condition, modulo 10^9 + 7.

Sample Input 1

30
4

Sample Output 1

6

Those six integers are: 4, 8, 13, 17, 22 and 26.

Sample Input 2

1000000009
1

Sample Output 2

2

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

Sample Input 3

98765432109876543210
58

Sample Output 3

635270834


#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<math.h>
#include<queue>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
typedef long double db;
typedef pair<int,int> pii;
const int N=10000;
const db pi=acos(-1.0);
#define lowbit(x) (x)&(-x)
#define sqr(x) (x)*(x)
#define rep(i,a,b) for (register int i=a;i<=b;i++)
#define per(i,a,b) for (register int i=a;i>=b;i--)
#define fir first
#define sec second
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
#define maxd 1000000007
#define eps 1e-8
int n,d,a[100100],dp[10010][110][2];
char s[100100];

int read()
{
    int x=0,f=1;char ch=getchar();
    while ((ch<'0') || (ch>'9')) {if (ch=='-') f=-1;ch=getchar();}
    while ((ch>='0') && (ch<='9')) {x=x*10+(ch-'0');ch=getchar();}
    return x*f;
}

int dfs(int pos,int mod,int lim)
{
	if (pos>n) dp[pos][mod][lim]=(mod==0);
	if (dp[pos][mod][lim]>-1) return dp[pos][mod][lim];
	int sum=0,up=9;
	if (lim) up=a[pos];
	rep(i,0,up)
	{
		int tmp=dfs(pos+1,(mod+i)%d,lim&&(i==up));
		sum=(sum+tmp)%maxd;
	}
	dp[pos][mod][lim]=sum;
	return sum;
}

int main()
{
	scanf("%s",s+1);d=read();n=strlen(s+1);
	rep(i,1,n) a[i]=s[i]-'0';
	memset(dp,-1,sizeof(dp));
	printf("%d",(dfs(1,0,1)+maxd-1)%maxd);
	return 0;
}


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

typedef long long lint;
typedef long double louble;

template<typename T1,typename T2> inline T1 max(T1 a,T2 b){return a<b?b:a;}
template<typename T1,typename T2> inline T1 min(T1 a,T2 b){return a<b?a:b;}

namespace ae86
{
	const int bufl = 1<<15;

	char buf[bufl],*s=buf,*t=buf;

	inline int fetch()
	{
		if(s==t){t=(s=buf)+fread(buf,1,bufl,stdin);if(s==t)return EOF;}
		return *s++;
	}

	inline int ty()
	{
		int a=0,b=1,c=fetch();
		while(!isdigit(c))b^=c=='-',c=fetch();
		while(isdigit(c))a=a*10+c-48,c=fetch();
		return b?a:-a;
	}
}
using ae86::ty;

const int _ = 200007;

int n,dis[_],rdis[_],len;
lint s[_]={0},sr[_]={0};

inline lint sum(lint f[],int l,int r){return f[r]-f[l-1];}

inline lint finder()
{
	lint ans=0;
	for(int i=1;i<=n;i++)
	{
		int rx=(n-i)>>1,x=n-i-rx;
		ans=max(ans,(sum(s,i,i+x-1)+sum(sr,n-rx+1,n))*2+(((n-i)&1)?rdis[n-rx]:dis[n-x]));
	}
	return ans;
}

int main()
{
	len=ty(),n=ty();
	for(int i=1;i<=n;i++)dis[i]=ty(),rdis[i]=len-dis[i],s[i]=s[i-1]+dis[i],sr[i]=sr[i-1]+rdis[i];
	lint ans=finder();
	for(int i=1;i<=n;i++)dis[i]=len-dis[i];
	reverse(dis+1,dis+n+1);
	for(int i=1;i<=n;i++)rdis[i]=len-dis[i],s[i]=s[i-1]+dis[i],sr[i]=sr[i-1]+rdis[i];
	ans=max(ans,finder());
	printf("%lld\n",ans);
	return 0;
}

Score : 800 points

Problem Statement

Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi.
Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distance from the Takahashi's residence, measured counter-clockwise.

There are N trees around the lake; the coordinate of the i-th tree is X_i. There is no tree at coordinate 0, the location of Takahashi's residence.

Starting at his residence, Takahashi will repeat the following action:

If all trees are burnt, terminate the process.

Specify a direction: clockwise or counter-clockwise.

Walk around the lake in the specified direction, until the coordinate of a tree that is not yet burnt is reached for the first time.

When the coordinate with the tree is reached, burn that tree, stay at the position and go back to the first step.

Find the longest possible total distance Takahashi walks during the process.

Partial Score

A partial score can be obtained in this problem:

300 points will be awarded for passing the input satisfying N \leq 2000.

Constraints

2 \leq L \leq 10^9

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

1 \leq X_1 < ... < X_N \leq L-1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

L N
X_1
:
X_N

Output

Print the longest possible total distance Takahashi walks during the process.

Sample Input 1

10 3
2
7
9

Sample Output 1

15

Takahashi walks the distance of 15 if the process goes as follows:

Walk a distance of 2 counter-clockwise, burn the tree at the coordinate 2 and stay there.

Walk a distance of 5 counter-clockwise, burn the tree at the coordinate 7 and stay there.

Walk a distance of 8 clockwise, burn the tree at the coordinate 9 and stay there.

Sample Input 2

10 6
1
2
3
6
7
9

Sample Output 2

27

Sample Input 3

314159265 7
21662711
77271666
89022761
156626166
160332356
166902656
298992265

Sample Output 3

1204124749


#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <utility>
#include <cstring>
#include <iomanip>
#include <numeric>
#include <cmath>
#include <queue>
#include <map>
using namespace std;
typedef long long ll;
const int INF = 1<<30;
const int MOD = 1e9 + 7;
const int dy[] = {1, 0, -1, 0};
const int dx[] = {0, 1, 0, -1};
map<ll, ll> mp;
void prime_factor(ll n)
{
    for(int i = 2; i * i <= n; i++)
    {
        while (n % i == 0)
        {
            mp[i]++;
            n /= i;
        }
    }
    if (n != 1) mp[n] = 1;
}
int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    ll n, p;
    cin >> n >> p;
    prime_factor(p);
    ll ans = 1LL;
    if(n == 1) cout << p << endl;
    else
    {
        for(auto x : mp)
        {
            if(x.second >= n)
            {
                ans *= x.first * (x.second / n);
            }
        }
        cout << ans << endl;
    }
    return 0;
}

Score : 300 points

Problem Statement

There are N integers a_1, a_2, ..., a_N not less than 1.
The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P.

Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N.

Constraints

1 \leq N \leq 10^{12}

1 \leq P \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N P

Output

Print the answer.

Sample Input 1

3 24

Sample Output 1

2

The greatest common divisor would be 2 when, for example, a_1=2, a_2=6 and a_3=2.

Sample Input 2

5 1

Sample Output 2

1

As a_i are positive integers, the only possible case is a_1 = a_2 = a_3 = a_4 = a_5 = 1.

Sample Input 3

1 111

Sample Output 3

111

Sample Input 4

4 972439611840

Sample Output 4

206


#include <bits/stdc++.h>
#define fr(i, n, m) for(int i = (n); i < (m); i ++)
#define pb push_back
#define pq priority_queue
#define st first
#define nd second

using namespace std;
typedef long long ll;
ll const inf = 1e9;
ll const mod = 998244353  ;

int main()
{
    ll n, p;
    cin >> n >> p;
    ll prime = 2;
    ll c = 0;
    ll gcd = 1;
    while(p > 1){
        if(p % prime == 0){
            c ++;
            p /= prime;
        }
        else{
            gcd = gcd * max(1LL, (c / n) * prime);
            c = 0;
            prime ++;
        }

    }
    if(c > 0) gcd = gcd * max(1LL, c / n * prime);
    cout << gcd << endl;

    return 0;

}


#include <cstdio>
#include <iostream>
#include <vector>
#include <set>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <bitset>
#include <queue>
#include <sstream>
using namespace std;
#define mp make_pair
#define pb push_back
#define re return
#define fi first
#define se second
typedef vector<int> vi;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef vector<pii> vpii;
typedef vector<string> vs;
typedef vector<vi> vvi;
long long n,p,sum=1;
int mx=1;
long long cnt[1000100];
int main() {
    //freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	cin>>n>>p;
	if(n==1){
		cout<<p<<endl;
		return 0;
	}
	for(int i=2;i*i<=p;i++){
		while(p%i==0){
			p/=i;
			cnt[i]++;
			mx=i;
		}
	}
	for(int i=2;i<=mx;i++){
		if(cnt[i]>=n){
			int t=cnt[i]/n;
			for(int j=0;j<t;j++){
				sum*=i;
			}
		}
	}
	cout<<sum<<endl;
    return 0;
}


#include <cstdio>
#include <map>

using namespace std;

int main() {
  long long n, m;
  scanf("%lld %lld", &n, &m);
  map<long long, int> cnt;
  for (long long i = 2; i * i <= m; ++i) {
    while (m % i == 0) {
      ++cnt[i];
      m /= i;
    }
  }
  if (m > 1) {
    ++cnt[m];
  }
  long long ans = 1;
  for (auto &e : cnt) {
    for (int i = 0; i < e.second / n; ++i) {
      ans *= e.first;
    }
  }
  printf("%lld\n", ans);
}


#include <iostream>
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <cassert>
#include <fstream>
#include <iomanip>

using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;

const ll mod = 1e9 + 7;

vector<ll> dx = {1, -1, 0, 0};
vector<ll> dy = {0, 0, 1, -1};

vector<vector<ll>> g;

int main() {

    cin.tie(0);
    ios_base::sync_with_stdio(0);

    ll n;
    cin >> n;
    bool f = 0;
    for (int i = 0; i < n; ++i)
    {
        ll tmp;
        cin >> tmp;
        tmp %= 2ll;
        if (tmp)
        {
            f = 1;
        }
    }
    if (f)
    {
        cout << "first" <<endl;
    }
    else
    {
        cout << "second" << endl;
    }
    return 0;
}

Score : 500 points

Problem Statement

There is an apple tree that bears apples of N colors. The N colors of these apples are numbered 1 to N, and there are a_i apples of Color i.

You and Lunlun the dachshund alternately perform the following operation (starting from you):

Choose one or more apples from the tree and eat them. Here, the apples chosen at the same time must all have different colors.

The one who eats the last apple from the tree will be declared winner. If both you and Lunlun play optimally, which will win?

Constraints

1 \leq N \leq 10^5

1 \leq a_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

If you will win, print first; if Lunlun will win, print second.

Sample Input 1

2
1
2

Sample Output 1

first

Let Color 1 be red, and Color 2 be blue. In this case, the tree bears one red apple and two blue apples.

You should eat the red apple in your first turn. Lunlun is then forced to eat one of the blue apples, and you can win by eating the other in your next turn.

Note that you are also allowed to eat two apples in your first turn, one red and one blue (not a winning move, though).

Sample Input 2

3
100000
30000
20000

Sample Output 2

second


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

int main() {
  string S;
  cin>>S;
  long long w=0LL,sum=0LL;
  for(int i=0;i<S.size();i++){
    if(S.at(i)=='W'){
      w++;
      sum+=i;
    }
  }
  if(w==S.size()||w==0LL)
    cout<<"0"<<endl;
  else
    cout<<sum-w*(w-1LL)/2LL<<endl;
}

Score : 300 points

Problem Statement

There are N Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.)
The state of each piece is represented by a string S of length N.
If S_i=B, the i-th piece from the left is showing black;
If S_i=W, the i-th piece from the left is showing white.

Consider performing the following operation:

Choose i (1 \leq i < N) such that the i-th piece from the left is showing black and the (i+1)-th piece from the left is showing white, then flip both of those pieces. That is, the i-th piece from the left is now showing white and the (i+1)-th piece from the left is now showing black.

Find the maximum possible number of times this operation can be performed.

Constraints

1 \leq |S| \leq 2\times 10^5

S_i=B or W

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum possible number of times the operation can be performed.

Sample Input 1

BBW

Sample Output 1

2

The operation can be performed twice, as follows:

Flip the second and third pieces from the left.

Flip the first and second pieces from the left.

Sample Input 2

BWBWBW

Sample Output 2

6


#include <bits/stdc++.h>
#include <numeric>
using namespace std;
#define ll long long
#define mod107 1000000007
#define rep(i, n) for (int i = 0; i < n; ++i)
using Graph = vector<vector<int>>;
#define grepq priority_queue<double, std::vector<double>, std::greater<double>>
#define all(v) v.begin(), v.end()
#define PI acos(-1)

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 ll INF = 10010001010;
const int inf = 1000034000;

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

int main() {
  string S;
  cin >> S;
  int N = S.size();
  int black = 0;
  int ans = 0;
  for(int i = 0;i < N;i++){
    if(S[i] == 'B'){
      black++;
    }
    else{
      ans += black;
    }
  }
  cout << ans << endl;

}


#include <cstddef>
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <vector>
#include <array>
#include <unordered_map>
#include <algorithm>
#include <numeric>
#include <limits>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <bitset>
#include <valarray>
#include <utility>
#include <tuple>
#include <cmath>
#include <memory>
#include <random>
#include <fstream>
#include <locale>

using ll = long long;
using ull = unsigned long long;

//vector
template <class T>
using vec = std::vector<T>;

template <class T>
using vvec = vec<vec<T>>;

constexpr std::size_t operator""_sz(ull n) { return std::size_t(n); }

int main()
{
    using namespace std;

    int n;
    cin >> n;
    vec<int> v(n);
    vec<bool> used(n);
    set<ll> se;

    vec<ll> pow2(32);
    pow2[0] = 1;
    for (int i = 1; i < 32; ++i)
    {
        pow2[i] = pow2[i - 1] * 2;
    }

    for (auto &e : v)
    {
        cin >> e;
        se.emplace(e);
    }

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

    int ans{};

    for (int i = n - 1; i >= 0; --i)
    {
        if (used[i])
            continue;

        auto target = *upper_bound(pow2.cbegin(), pow2.cend(), v[i]);

        auto find = se.find(target - v[i]);

        if (find != se.end() && target != v[i])
        {
            auto val = *find;
            se.erase(val);

            auto index = distance(v.begin(), upper_bound(v.begin(), v.end(), val));
            used[index] = true;
            used[i] = true;
            ++ans;
        }
    }

    cout << ans << endl;

    return 0;
}

Score : 600 points

Problem Statement

Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i.
He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2.
Note that a ball cannot belong to multiple pairs.
Find the maximum possible number of pairs that can be formed.

Here, a positive integer is said to be a power of 2 when it can be written as 2^t using some non-negative integer t.

Constraints

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

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of pairs such that the sum of the integers written on each pair of balls is a power of 2.

Sample Input 1

3
1 2 3

Sample Output 1

1

We can form one pair whose sum of the written numbers is 4 by pairing the first and third balls.
Note that we cannot pair the second ball with itself.

Sample Input 2

5
3 11 14 5 13

Sample Output 2

2


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>
#include <iostream>
#include <sstream>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <utility>
#include <numeric>
#include <algorithm>
#include <bitset>
#include <complex>
#include <array>
#include <list>
#include <stack>
#include <valarray>

using namespace std;

typedef unsigned uint;
typedef long long Int;
typedef unsigned long long UInt;

const int INF = 1001001001;
const Int INFLL = 1001001001001001001LL;

template<typename T> void pv(T a, T b) { for (T i = a; i != b; ++i) cout << *i << " "; cout << endl; }
template<typename T> void chmin(T& a, T b) { if (a > b) a = b; }
template<typename T> void chmax(T& a, T b) { if (a < b) a = b; }
int in() { int x; scanf("%d", &x); return x; }
double fin() { double x; scanf("%lf", &x); return x; }
Int lin() { Int x; scanf("%lld", &x); return x; }

int main() {
  int H = in();
  int W = in();
  int N = in();
  set<pair<int, int>> X;
  for (int i = 0; i < N; ++i) {
    int r = in() - 1;
    int c = in() - 1;
    X.insert(make_pair(r, c));
  }

  vector<int> top(W, INF);
  int ar = 0, ac = 0;
  while (true) {
    chmin(top[ac], ar);
    ++ar;
    if (ar >= H) {
      break;
    }
    if (X.count(make_pair(ar, ac + 1)) == 0) {
      ++ac;
    }
  }

  int res = H;
  for (const auto& p : X) {
    if (top[p.second] < p.first) {
      chmin(res, p.first);
    }
  }
  printf("%d\n", res);
  return 0;
}

Score : 800 points

Problem Statement

Takahashi and Aoki will play a game using a grid with H rows and W columns of square cells.
There are N obstacles on this grid; the i-th obstacle is at (X_i,Y_i).
Here, we represent the cell at the i-th row and j-th column (1 \leq i \leq H, 1 \leq j \leq W) by (i,j).
There is no obstacle at (1,1), and there is a piece placed there at (1,1).

Starting from Takahashi, he and Aoki alternately perform one of the following actions:

Move the piece to an adjacent cell.
Here, let the position of the piece be (x,y). Then Takahashi can only move the piece to (x+1,y), and Aoki can only move the piece to (x,y+1).
If the destination cell does not exist or it is occupied by an obstacle, this action cannot be taken.

Do not move the piece, and end his turn without affecting the grid.

The game ends when the piece does not move twice in a row.

Takahashi would like to perform as many actions (including not moving the piece) as possible before the game ends, while Aoki would like to perform as few actions as possible before the game ends.
How many actions will Takahashi end up performing?

Constraints

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

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

1 \leq X_i \leq H

1 \leq Y_i \leq W

If i \neq j, (X_i,Y_i) \neq (X_j,Y_j)

(X_i,Y_i) \neq (1,1)

X_i and Y_i are integers.

Input

Input is given from Standard Input in the following format:

H W N
X_1 Y_1
:
X_N Y_N

Output

Print the number of actions Takahashi will end up performing.

Sample Input 1

3 3 1
3 2

Sample Output 1

2

For example, the game proceeds as follows:

Takahashi moves the piece to (2,1).

Aoki does not move the piece.

Takahashi moves the piece to (3,1).

Aoki does not move the piece.

Takahashi does not move the piece.

Takahashi performs three actions in this case, but if both players play optimally, Takahashi will perform only two actions before the game ends.

Sample Input 2

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

Sample Output 2

6

Sample Input 3

100000 100000 0

Sample Output 3

100000


#include<bits/stdc++.h>
using namespace std;
int main(){
  int age;
  cin >> age;
  if(age == 3 || age==5 || age==7) cout << "YES" << endl;
  else  cout << "NO" <<endl;
  return 0;
}

Score : 100 points

Problem Statement

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

1 ≤ X ≤ 9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If Takahashi's growth will be celebrated, print YES; if it will not, print NO.

Sample Input 1

5

Sample Output 1

YES

The growth of a five-year-old child will be celebrated.

Sample Input 2

6

Sample Output 2

NO

See you next year.


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

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

  int n =S.size();
  int x = 999;
  for(int i=0;i<n-2;i++){
    int w = (S[i] - '0') * 100 + (S[i+1] - '0') * 10 + (S[i+2] - '0');
    x = min(x, abs(w-753));
  }

  cout << x;

  return 0;
}

Score : 200 points

Problem Statement

There is a string S consisting of digits 1, 2, ..., 9.
Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)

The master's favorite number is 753. The closer to this number, the better.
What is the minimum possible (absolute) difference between X and 753?

Constraints

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

Each character in S is 1, 2, ..., or 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum possible difference between X and 753.

Sample Input 1

1234567876

Sample Output 1

34

Taking out the seventh to ninth characters results in X = 787, and the difference between this and 753 is 787 - 753 = 34. The difference cannot be made smaller, no matter where X is taken from.

Note that the digits cannot be rearranged. For example, taking out 567 and rearranging it to 765 is not allowed.

We cannot take out three digits that are not consecutive from S, either. For example, taking out the seventh digit 7, the ninth digit 7 and the tenth digit 6 to obtain 776 is not allowed.

Sample Input 2

35753

Sample Output 2

0

If 753 itself can be taken out, the answer is 0.

Sample Input 3

1111111111

Sample Output 3

642

No matter where X is taken from, X = 111, with the difference 753 - 111 = 642.


#include <bits/stdc++.h>
using namespace std;
int main(){
	string s,x;
	int mi;
	cin>>s;
	mi=1000;
	for(int i=0;i<s.size()-2;i++){
		x=s.substr(i,3);
		mi=min(mi,abs(753-((x[0]-'0')*100+(x[1]-'0')*10+(x[2]-'0'))));
	}
	cout<<mi<<endl;
}


Score : 300 points

Problem Statement

You are given an integer N. Among the integers between 1 and N (inclusive), how many Shichi-Go-San numbers (literally "Seven-Five-Three numbers") are there?

Here, a Shichi-Go-San number is a positive integer that satisfies the following condition:

When the number is written in base ten, each of the digits 7, 5 and 3 appears at least once, and the other digits never appear.

Constraints

1 \leq N < 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of the Shichi-Go-San numbers between 1 and N (inclusive).

Sample Input 1

575

Sample Output 1

4

There are four Shichi-Go-San numbers not greater than 575: 357, 375, 537 and 573.

Sample Input 2

3600

Sample Output 2

13

There are 13 Shichi-Go-San numbers not greater than 3600: the above four numbers, 735, 753, 3357, 3375, 3537, 3557, 3573, 3575 and 3577.

Sample Input 3

999999999

Sample Output 3

26484


//author:luckYrat(twitter:@luckYrat_)
//#include <bits/stdc++.h>

//def
#include <iostream>

#include <cmath>
#include <algorithm>
#include <iomanip>

//array
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <map>
#include <utility>
#include <climits>

using namespace std;

using ll = long long;
using P = pair<ll,ll>;

#define anyfill(n,s) setw(n) << setfill(s)
#define loop(s) for(int i = 0; s > i; i++)
#define rep(i,q) for(int i = 0; (q) > i; i++)
#define repp(i,n,q) for(int i = n; (q) > i; i++)
#define dep(i,q) for(int i = (q); 0 < i; i--)

#define MAX 1000000000
const int mod = 1000000007;
#define EPS (1e-10)

#define pb push_back
#define fir first
#define scn second
#define ednl endl

#define YesNo(a) (a?"Yes":"No")
#define YESNO(a) (a?"YES":"NO")
#define yesno(a) (a?"yes":"no")

P ar4[4] = {{0,1},{0,-1},{1,0},{-1,0}};
P ar8[8] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
/*
確認ポイント
cout << fixed << setprecision(n) << 小数計算//n桁の小数表記になる
vector.unique()は隣接した同じ要素を削除するので先にソートをする

計算量は変わらないが楽できるシリーズ
C++11以降でmin({a,b,c...})で複数個のmic,maxを処理できる
min(max)_element(iter,iter)で一番小さい(大きい)値のポインタが帰ってくる
count(iter,iter,int)でintがiterからiterの間にいくつあったかを取得できる

*/
__attribute__((constructor))
void initial() {
 cin.tie(0);
 ios::sync_with_stdio(false);
}

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

Score: 100 points

Problem Statement

There is a train going from Station A to Station B that costs X yen (the currency of Japan).

Also, there is a bus going from Station B to Station C that costs Y yen.

Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.

How much does it cost to travel from Station A to Station C if she uses this ticket?

Constraints

1 \leq X,Y \leq 100

Y is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If it costs x yen to travel from Station A to Station C, print x.

Sample Input 1

81 58

Sample Output 1

110

The train fare is 81 yen.

The train fare is 58 ⁄ 2=29 yen with the 50% discount.

Thus, it costs 110 yen to travel from Station A to Station C.

Sample Input 2

4 54

Sample Output 2

31


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define repr(i, n) for (int i = (n); i >= 0; --i)
#define FOR(i, m, n) for (int i = (m); i < (n); ++i)
#define FORR(i, m, n) for (int i = (m); i >= (n); --i)
using namespace std;
typedef long long ll;
const ll mod = 1000000007;
const ll mod2 = 998244353;

int main() {
  int x, y;
  cin >> x >> y;
  cout << x+y/2 << endl;
}


#pragma GCC optimize "-O3"
#pragma GCC target ("avx")
#define _USE_MATH_DEFINES
#include<bits/stdc++.h>
#define int long long
#define rep(i,n) for(int i=0;i<n;++i)
#define vi vector<int>
#define vvi vector<vi>
#define pb push_back
#define pi pair<int,int>
#define vp vector<pair<int,int>>
#define mp make_pair
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
#define inf (1ll<<60)
#define SORT(v) sort(all(v))
#define RSORT(v) sort(all(v),greater<int>())
signed gcd(int a, int b){return b?gcd(b,a%b):a;}
signed lcm(int a,int b){return a*b/gcd(a,b);}

using namespace std;

const int mod=1e9+7;

void run();

void init() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout<<fixed<<setprecision(12);
}

signed main(){
    init();
    run();
    return 0;
}

void run(){
    int x, y;
    cin >> x >> y;
    cout << x+y/2 << endl;
}


#include <iostream>
#include <utility>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <map>
#include <fstream>
#include <bitset>
#include <stack>
using namespace std;

typedef long long ll;
typedef pair<ll,ll> pii;
typedef vector<ll> vec;

int main()
{
#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	int x, y; cin >> x >> y;
	cout << x + y / 2;

	return 0;

}


#include<bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < n; ++i)
#define rep2(i,s,n) for (int i = s; i < n; ++i)
#define all(a) a.begin(),a.end()
using namespace std;
using ll = long long;
using P = pair<int,int>;

int main() {
    int n,t,a;
    cin >> n >> t >> a;
    int ans;
    double now = 1001001001;
    rep(i,n) {
        int h;
        cin >> h;
        double nt = t-nt*0.006;
        double dif = abs(nt-a);
        if(dif < now) {
            now = dif;
            ans = i+1;
        }
    }
    cout << ans << endl;
}

Score: 200 points

Problem Statement

A country decides to build a palace.

In this country, the average temperature of a point at an elevation of x meters is T-x \times 0.006 degrees Celsius.

There are N places proposed for the place. The elevation of Place i is H_i meters.

Among them, Princess Joisino orders you to select the place whose average temperature is the closest to A degrees Celsius, and build the palace there.

Print the index of the place where the palace should be built.

It is guaranteed that the solution is unique.

Constraints

1 \leq N \leq 1000

0 \leq T \leq 50

-60 \leq A \leq T

0 \leq H_i \leq 10^5

All values in input are integers.

The solution is unique.

Input

Input is given from Standard Input in the following format:

N
T A
H_1 H_2 ... H_N

Output

Print the index of the place where the palace should be built.

Sample Input 1

2
12 5
1000 2000

Sample Output 1

1

The average temperature of Place 1 is 12-1000 \times 0.006=6 degrees Celsius.

The average temperature of Place 2 is 12-2000 \times 0.006=0 degrees Celsius.

Thus, the palace should be built at Place 1.

Sample Input 2

3
21 -11
81234 94124 52141

Sample Output 2

3


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

// define list

namespace  math{
    const double PI = 3.14;
    const int INF = 1000000007;
    int GCM(int a,int b); //最大公約数
    int LCM(int a,int b); //最小公倍数
    int Pemu(int n,int r); //順列
    int Comb(int n,int m); //組み合わせ
    int Digit(int N); //桁和

    int GCM(int a,int b){
        if(a<b){
            swap(a,b);
        }
        int r = a%b;
        while (r!=0)
        {
            a=b;
            b=r;
            r=a%b;
        }
        return b;
    }

    int LCM(int a,int b){
        return a*(b/GCM(a,b));
    }

    int Pemu(int n,int r){
        int ans = n;
        for(int i=1;i<r;i++){
            ans*=(ans-i);
        }
        return ans;
    }

    int Comb(int n,int m){
        int a=n,b=m;
        for(int i=1;i<m;i++){
            a *= (a-i);
        }
        for(int i=1;i<m;i++){
            b *= (b-i);
        }

        return a/b;
    }

    int Digit(int N){
        if(N<10){
            return N;
        }
        int r = 0;
        while (N>=10)
        {
            r += (N%10);
            N /= 10;
        }
        r += N;
        return r;
    }
}

namespace SubLib{
    #define int long long
    #define double long double
    #define incin(n) int (n); cin >> (n);
    #define incin2(a,b) int a,b; cin >> a >> b;
    #define rap(n,i) for(int (i) = 0;i<(n);(i)++)
    #define input(n,v) (v) = SubLib::Input((n),(v))
    #define all(v) (v).begin(),(v).end()
    using intv = vector<int>;
    using strv = vector<string>;
    using charv = vector<char>;
    template <class T1>
    using pvec = vector<pair<T1,T1>>;
    template <typename T> vector<T> Input(int n,vector<T> v){
        for(int i=0;i<n;i++){
            cin >> v.at(i);
        }
        return v;
    }
}

using namespace math;
using namespace SubLib;
double Kion(int X,int T){
    return T -X * 0.006;
}

signed main(){
    incin(n);
    incin2(t,a);
    intv h(n);
    input(n,h);
    int log_dif = 1000000000;
    int point;
    rap(n,i){
        if(abs(Kion(h[i],t)-a)<log_dif){
            log_dif = abs(Kion(h[i],t)-a);
            point = i+1;
        }
    }
    cout << point << endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using product = pair<ll,ll>;
using vvll = vector<vector<ll>>;
using vll = vector<ll>;

int main()
{
    ll N,M;
    cin>>N>>M;
    vll P(M);
    vll Y(M);
    for(ll i=0;i<M;i++)
    {
        cin>>P[i]>>Y[i];
        --P[i];
    }
    vvll vals(N);
    for(ll i=0;i<M;i++)vals[P[i]].emplace_back(Y[i]);
    for(ll i=0;i<N;i++)sort(vals[i].begin(),vals[i].end());

    for(ll i=0;i<M;i++)
    {
        ll v=P[i];
        printf("%06d",v+1);

        ll id=lower_bound(vals[v].begin(),vals[v].end(),Y[i])-vals[v].begin();
        printf("%06d\n",id+1);
    }
}

Score: 300 points

Problem Statement

In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures.

City i is established in year Y_i and belongs to Prefecture P_i.

You can assume that there are no multiple cities that are established in the same year.

It is decided to allocate a 12-digit ID number to each city.

If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x.

Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits.

Find the ID numbers for all the cities.

Note that there can be a prefecture with no cities.

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq P_i \leq N

1 \leq Y_i \leq 10^9

Y_i are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
P_1 Y_1
:
P_M Y_M

Output

Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...).

Sample Input 1

2 3
1 32
2 63
1 12

Sample Output 1

000001000002
000002000001
000001000001

As City 1 is the second established city among the cities that belong to Prefecture 1, its ID number is 000001000002.

As City 2 is the first established city among the cities that belong to Prefecture 2, its ID number is 000002000001.

As City 3 is the first established city among the cities that belong to Prefecture 1, its ID number is 000001000001.

Sample Input 2

2 3
2 55
2 77
2 99

Sample Output 2

000002000001
000002000002
000002000003