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

#define rep(var,n)  for(int var=0;var<(n);++var)

const ll MOD=1000000007LL;

ll SUB(ll x, ll y) { return (x-y+MOD) % MOD; }
ll MUL(ll x, ll y) { return x*y % MOD; }

//xのe丈の高速計算
ll POW(ll x, ll e) {
  //最初1
  ll v=1;
  //後処理は、xの二乗を取って、e/2する。
  //for (;something;)はwhile(something)に同じ
  for(; e; x=MUL(x,x), e>>=1) {
    //もしeが奇数なら、vにxをかける。
    if (e&1) v = MUL(v,x);
  }
  return v;
}

//a,b,c,d  1<->A, 2<->G, 3<->C, 4<->Tに対応?で、admissible出ない組み合わせがbad==true
inline bool bad(int a,int b,int c,int d){
    if (        b==1 && c==2 && d==3) return true;
    if (a==1         && c==2 && d==3) return true;
    if (        b==2 && c==1 && d==3) return true;
    if (        b==1 && c==3 && d==2) return true;
    if (a==1 && b==2         && d==3) return true;
    return false;
}

ll solve(int N) {
  //n のとき、a,b,c,dそれぞれ5通り試すの。
    ll dp[101][256][2];
    memset(dp, 0, sizeof(dp));
    dp[0][0][0] = 1;
    for (int i=0;i<N;i++){
        for (int a=0;a<4;a++) for (int b=0;b<4;b++) for (int c=0;c<4;c++) for (int d=0;d<4;d++) {
            //何か5進法で表記しておるな？
            int abcd = ((a*4+b)*4+c)*4+d;
            for (int e=0; e<4; ++e) {
              //
                int bcde = ((b*4+c)*4+d)*4+e;
                //直前n-1でbadになるかどうかと、nでbadになるかどうかで4通りあるが、それぞれ
                //
                bool _bad = bad(b,c,d,e);
                for (int j=0;j<2;j++){
                    (dp[i+1][bcde][j || _bad] += dp[i][abcd][j]) %= MOD;
                }
            }
        }
    }
    ll ans = 0;
    for (int i=0;i<256;i++) {
        (ans += dp[N][i][1]) %= MOD;
    }
    return SUB(POW(4,N), ans);
}

int main() {
    int N; cin >> N;
    cout << solve(N) << endl;
    return 0;
}

Score : 400 points

Problem Statement

You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:

The string does not contain characters other than A, C, G and T.

The string does not contain AGC as a substring.

The condition above cannot be violated by swapping two adjacent characters once.

Notes

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

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

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

61

There are 4^3 = 64 strings of length 3 that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is 64 - 3 = 61.

Sample Input 2

4

Sample Output 2

230

Sample Input 3

100

Sample Output 3

388130742

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


#include <iostream>
#include <vector>
#include <stack>

using namespace std;
using vi = vector<int>;

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define ITER(it,v) for(auto it=v.begin();it!=v.end();++it)
#define IN(v) if (scanf("%d", &v)<1);
// #define OUT(v) printf("%d\n", v)
#define OUT(v) cout << v << "\n"

int N;
int B[100];
vi ans;
bool dfs(string& s) {
  // s: 抜いた状況
  // 1なら抜いた
  // 深さ優先で抜いてみる
  // OUT(s);
  if (s.find('0') == string::npos)
    return true;
  int index = 1;
  stack<int> st;
  REP(i, N) {
    if (s[i] == '1')
      continue;
    if (B[i] == index) {
      st.push(i);
    }
    ++index;
  }
  while (!st.empty()) {
    int i = st.top(); st.pop();
    s[i] = '1';
    if (dfs(s)) {
      ans.push_back(B[i]);
      return true;
    }
    s[i] = '0';
  }
  return false;
}
int main() {
  IN(N);

  string s;
  REP(i, N) {
    IN(B[i]);
    s += "0";
  }
  if (dfs(s)) {
    ITER(it, ans) {
      OUT(*it);
    }
  } else
    OUT(-1);

  return 0;
}

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

Score : 400 points

Problem Statement

Snuke has an empty sequence a.

He will perform N operations on this sequence.

In the i-th operation, he chooses an integer j satisfying 1 \leq j \leq i, and insert j at position j in a (the beginning is position 1).

You are given a sequence b of length N. Determine if it is possible that a is equal to b after N operations. If it is, show one possible sequence of operations that achieves it.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq b_i \leq N

Input

Input is given from Standard Input in the following format:

N
b_1 \dots b_N

Output

If there is no sequence of N operations after which a would be equal to b, print -1.
If there is, print N lines. In the i-th line, the integer chosen in the i-th operation should be printed. If there are multiple solutions, any of them is accepted.

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

In this sequence of operations, the sequence a changes as follows:

After the first operation: (1)

After the second operation: (1,1)

After the third operation: (1,2,1)

Sample Input 2

2
2 2

Sample Output 2

-1

2 cannot be inserted at the beginning of the sequence, so this is impossible.

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1

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.


#line 2 "/Users/kaage/Desktop/ProgrammingWorkspace/library/other/template.hpp"
#define _CRT_SECURE_NO_WARNINGS
#pragma target("avx2")
#pragma optimize("O3")
#pragma optimize("unroll-loops")
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <string.h>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#define rep(i,n) for(int i=0;i<(n);i++)
#define REP(i,n) for(int i=1;i<=(n);i++)
#define all(V) V.begin(),V.end()
typedef unsigned int uint;
typedef long long lint;
typedef unsigned long long ulint;
typedef std::pair<int, int> P;
typedef std::pair<lint, lint> LP;
constexpr int INF = INT_MAX/2;
constexpr lint LINF = LLONG_MAX/2;
constexpr double eps = DBL_EPSILON;
constexpr double PI=3.141592653589793238462643383279;
template<class T>
class prique :public std::priority_queue<T, std::vector<T>, std::greater<T>> {};
template <class T, class U>
inline bool chmax(T& lhs, const U& rhs) {
	if (lhs < rhs) {
		lhs = rhs;
		return 1;
	}
	return 0;
}
template <class T, class U>
inline bool chmin(T& lhs, const U& rhs) {
	if (lhs > rhs) {
		lhs = rhs;
		return 1;
	}
	return 0;
}
inline lint gcd(lint a, lint b) {
	while (b) {
		lint c = a;
		a = b; b = c % b;
	}
	return a;
}
inline lint lcm(lint a, lint b) {
	return a / gcd(a, b) * b;
}
bool isprime(lint n) {
	if (n == 1)return false;
	for (int i = 2; i * i <= n; i++) {
		if (n % i == 0)return false;
	}
	return true;
}
template<typename T>
T mypow(T a, lint b) {
	T res(1);
	while(b){
		if(b&1)res*=a;
		a*=a;
		b>>=1;
	}
	return res;
}
lint modpow(lint a, lint b, lint m) {
	lint res(1);
	while(b){
		if(b&1){
			res*=a;res%=m;
		}
		a*=a;a%=m;
		b>>=1;
	}
	return res;
}
template<typename T>
void printArray(std::vector<T>& vec) {
	rep(i, vec.size()){
		std::cout << vec[i];
		std::cout<<(i==(int)vec.size()-1?"\n":" ");
	}
}
template<typename T>
void printArray(T l, T r) {
	T rprev = std::prev(r);
	for (T i = l; i != rprev; i++) {
		std::cout << *i << " ";
	}
	std::cout << *rprev << std::endl;
}
LP extGcd(lint a,lint b) {
	if(b==0)return {1,0};
	LP s=extGcd(b,a%b);
	std::swap(s.first,s.second);
	s.second-=a/b*s.first;
	return s;
}
LP ChineseRem(const lint& b1,const lint& m1,const lint& b2,const lint& m2) {
	lint p=extGcd(m1,m2).first;
	lint tmp=(b2-b1)*p%m2;
	lint r=(b1+m1*tmp+m1*m2)%(m1*m2);
	return std::make_pair(r,m1*m2);
}
template<typename F>
inline constexpr decltype(auto) lambda_fix(F&& f){
	return [f=std::forward<F>(f)](auto&&... args){
		return f(f,std::forward<decltype(args)>(args)...);
	};
}
#line 2 "main.cpp"
int N,M,count[100010];
int main(){
	std::cin>>N>>M;
	rep(i,M){
		int a,b;
		std::cin>>a>>b;
		count[a]++;count[b]++;
	}
	REP(i,N){
		if(count[i]&1){
			puts("No");
			return 0;
		}
	}
	std::sort(count+1,count+N+1);
	if(count[N]>=4&&N-1>0&&count[N-1]<=count[N])puts("Yes");
	else puts("No");
	return 0;
}

Score : 800 points

Problem Statement

You are given a simple connected undirected graph consisting of N vertices and M edges.
The vertices are numbered 1 to N, and the edges are numbered 1 to M.

Edge i connects Vertex a_i and b_i bidirectionally.

Determine if three circuits (see Notes) can be formed using each of the edges exactly once.

Notes

A circuit is a cycle allowing repetitions of vertices but not edges.

Constraints

All values in input are integers.

1 \leq N,M \leq 10^{5}

1 \leq a_i, b_i \leq N

The given graph is simple and connected.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

If three circuits can be formed using each of the edges exactly once, print Yes; if they cannot, print No.

Sample Input 1

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

Sample Output 1

Yes

Three circuits can be formed using each of the edges exactly once, as follows:

Sample Input 2

3 3
1 2
2 3
3 1

Sample Output 2

No

Three circuits are needed.

Sample Input 3

18 27
17 7
12 15
18 17
13 18
13 6
5 7
7 1
14 5
15 11
7 6
1 9
5 4
18 16
4 6
7 2
7 11
6 3
12 14
5 2
10 5
7 8
10 15
3 15
9 8
7 15
5 16
18 15

Sample Output 3

Yes


//#pragma GCC optimize("Ofast,unroll-loops")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,tune=native")
#include<bits/stdc++.h>

using namespace std;

#define all(x) (x).begin(),(x).end()
#define I(x, a) for(auto x : (a))
#define ins insert
#define F(i, l, r) for(auto i = (l); i < (r); i++)
#define DF(i, l, r) for(auto i = (l); i >= (r); i--)
#define E(i, l, r) for(auto i = (l); i <= (r); i++)
#define pb push_back
#define X first
#define Y second
#define mp make_pair
#define ret return
#define brk break
#define cont continue
#define move fjgjgjgjghd

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

const int N = (int)1e5 + 55;
multiset<int> gr[N];
int n, m;
bool was[N];

void fail(){
    cout << "No";
    exit(0);
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int returned = 0;
    cin >> n >> m;
    F(i, 0, m){
        int v, u;
        cin >> v >> u;
        --v; --u;
        gr[v].insert(u);
        gr[u].insert(v);
    }
    F(i, 0, n)if(gr[i].size()&1)fail();
    stack<int> st;
    st.push(0);
    was[0] = 1;
    while(!st.empty()){
        int v = st.top();
        while(!gr[v].empty()){
            int u = *gr[v].begin();
            gr[v].erase(gr[v].begin());
            gr[u].erase(gr[u].find(v));
            st.push(u);
            if(was[u])++returned;
            was[u] = 1;
            brk;
        }
        if(v == st.top())st.pop();
    }
    if(returned < 3)fail();
    else cout << "Yes";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int, int>;
const ll MOD = 1000000007;

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

    vector<int> cnt(26);
    for(int i=0;i<N;i++){
        cnt[S[i] - 'a']++;
    }

    ll ans = 1;
    for(int i=0;i<26;i++){
        ans = (ans * (cnt[i] + 1)) % MOD;
    }
    cout << ans - 1 << endl;
    return 0;
}

Score : 200 points

Problem Statement

You are given a string S of length N.
Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of the subsequences such that all characters are different, modulo 10^9+7.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in S itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17


/*
オーダー
10**6	余裕を持って間に合う
10**7	おそらく間に合う	余裕を持って間に合う
10**8	非常にシンプルな処理でない限り厳しい	おそらく間に合う
10**9		非常にシンプルな処理でない限り厳しい
logn	:OK
n		:10^7
nlogn	:10^6
n**2	:10^4
n**3	:300
2**n	:20
n!		:10

// 各桁の和を計算する関数
int findSumOfDigits(int n) {
  int sum = 0;
  while (n > 0) { // n が 0 になるまで
    sum += n % 10;
    n /= 10;
  }
  return sum;
}

sort(a, a + N, greater<int>());  // a[0:N] を大きい順にソート

int num[110] = {0};  // バケット
for (int i = 0; i < N; ++i) {
    num[d[i]]++;  // d[i] が 1 個増える
}

map<string, int> mp; // 連想配列 map<キー型, 値型> オブジェクト名
for (int i = 0; i < N; ++i) {
    auto itr = mp.find(s[i]);        // s[i] が設定されているか？
    if(itr != mp.end() ) {
         mp[s[i]] += 1;
    }
    else {
         mp[s[i]] += 1 ;
    }
}
stack<int> s;	//intをデータとするスタックを用意
s.push(1);		//{} -> {1}
printf("%d\n", s.top());	// 3
s.pop();

queue<int> que;	//intをデータとするキューを用意
que.push(1);		//{} -> {1}
printf("%d\n", que.front());	// 1
que.pop();
*/

#include <iostream>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <bitset>
#include <string.h>

using namespace std;

// #define for(i,a,b) for (int i=(a);i<(b);++i)
typedef long long ll;
typedef pair<ll,ll> P;
#define REP(i,n) for(long long i = 0; i < (long long)(n); i++)
#define pb push_back // vectorに要素追加
#define INF (ll)1e18
// int
// // 各桁の和を計算する関数
// int findSumOfDigits(int n) {
//   int amari = 0;
//   int keta = 0;
//   while (n > 0) { // n が 0 になるまで
//     amari += n % 2;
//     if (keta%2==0)
//     n /= 10;
//   }
//   return sum;
// }

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

vector<P> C_pair;
const ll n_div = 1e9+7;
const ll MAX_N = 2*1e5;
ll N;
ll num_pair;
ll C[MAX_N];
ll dp[MAX_N+1]; // dp[i ~ num_pairまでのC_pairを使った組み合わせ]

// i番目以降の品物から重さの総和がj以下になるように選ぶ
ll dfs(ll i){
	if (dp[i]!=-1){
		return dp[i];
	}
	else if (i==num_pair-1){
		dp[i] = 2;
		return dp[i];
	}
	else{
		ll idx_no_overlap = -1;
		for (ll j = i+1; j < num_pair; ++j){
			if (C_pair[i].second<=C_pair[j].first){
				// printf("!!!\n");
				idx_no_overlap = j;
			}
		}
		if (idx_no_overlap==-1){
			printf("i: %lld all overlap\n", i);
			dp[i] = dfs(i+1) + 1;
			dp[i] %= n_div;
		}
		else{
			// printf("i: %lld no overlap to %lld\n", i, idx_no_overlap);
			dp[i] = dfs(i+1) + dfs(idx_no_overlap);
			dp[i] %= n_div;
		}
		return dp[i];
	}
}

int main() {
	// 入力
	cin >> N;
	for (ll i = 0; i < N; ++i) cin >> C[i];

	// 解法
	// ペアのベクトルを作ってソート
	ll last[MAX_N];
	REP(i,MAX_N)last[i]=-1;

	REP(i, N){
		if (last[C[i]]!=-1 & last[C[i]]!=i-1){
			C_pair.pb(make_pair(last[C[i]],i));
		}
		last[C[i]] = i;
	}
	sort(C_pair.begin(), C_pair.end());
	num_pair = C_pair.size();

	// REP(i, C_pair.size()){
	// 	printf("i: %lld, %lld -> %lld\n", i, C_pair[i].first, C_pair[i].second);
	// }

	// DFS
	memset(dp, -1, sizeof(dp));

	// REP(i,num_pair){
	// 	printf("i: %lld, dp: %lld\n", i, dp[i]);
	// }
	if (num_pair==0) dp[0] = 1;
	for (ll i = num_pair-1; i>=0; --i){
		dfs(0);
	}
	// REP(i,num_pair){
	// 	printf("i: %lld, dp: %lld\n", i, dp[i]);
	// }

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

Score : 700 points

Problem Statement

There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i.

Snuke will perform the following operation zero or more times:

Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones.

Find the number of possible final sequences of colors of the stones, modulo 10^9+7.

Constraints

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

1 \leq C_i \leq 2\times 10^5(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
C_1
:
C_N

Output

Print the number of possible final sequences of colors of the stones, modulo 10^9+7.

Sample Input 1

5
1
2
1
2
2

Sample Output 1

3

We can make three sequences of colors of stones, as follows:

(1,2,1,2,2), by doing nothing.

(1,1,1,2,2), by choosing the first and third stones to perform the operation.

(1,2,2,2,2), by choosing the second and fourth stones to perform the operation.

Sample Input 2

6
4
2
5
4
2
4

Sample Output 2

5

Sample Input 3

7
1
3
1
2
3
3
2

Sample Output 3

5


#include <bits/stdc++.h>
#define SZ(x) ((int)(x).size())
typedef long long ll;
typedef long double ld;
using namespace std;

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cout.setf(ios::fixed); cout.precision(20);
    int H, W, h, w; cin >> H >> W >> h >> w;
    cout << H * W - h * W - w * (H - h) << "\n";
}

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


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

#define ll long long
#define all(x) (x).begin(), (x).end()
const long long INF = 1LL << 60;

#define rep(i, n) for (int i = 0; i < (int)(n); i++)  //(i, 10) i=0～i=9まで
#define repr(i, n) for (int i = n; i >= 0; i--)   // (i, 10) i=10～i=0まで
#define FOR(i, m, n) for (int i = m; i < n; i++)  // (i, 3, 10) i=3～i=9まで

// 総数を1000000007で割った余り
const long long mod = 1e9 + 7;

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

    // 入力
    int H, W;
    cin >> H >> W;
    int h, w;
    cin >> h >> w;
    int ans = 0;

    // 処理
    // ans = W * H - (H * w + W * h - w * h);
    ans = (W - w) * (H - h);
    cout << ans << endl;

    // 出力

    return 0;
}


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

int main(){
    //個数の指定
    int N,M,C;
    int count;
    cin >> N >> M >> C;
    vector<int> dots(N);
    vector<int> A(M);
    vector<int> B(M);
    for(int i = 0;i < M;i++){
        cin >> B.at(i);
    }
    //vectorを作りカウント
    for(int k = 0;k < N;k++){
        for(int i = 0;i < M;i++){
        cin >> A.at(i);
        dots.at(k) += A.at(i) * B.at(i); //AとBの内積を取りdotsベクトルの要素とする
    }
    if(dots.at(k) + C > 0){
        count++;
    }
}
}

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


#include<iostream>
#define p 20
using namespace std;

int main(){
	int N,M,C;
	int A[p];
	int B[p];
	int i,j;
	int sum;
	int x=0;

	cin >> N >> M >> C;

	for(i=0;i<M;i++)
		cin >> A[i];

	for(j=0;j<N;j++){
		for(i=0;i<M;i++){
			cin >> B[i];
			sum+=(A[i]*B[i]);
		}
		if(sum+C>0)
			x++;
	}

	cout << x << endl;

	return 0;
}


/*author: hyperion_1724
  date:
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	// chrono::steady_clock sc;
 //  	auto start = sc.now();
 //  	ifstream cin;
 //  	cin.open("INPUT.txt");

	int N,M,C;
	cin>>N>>M>>C;
	int B[M];
	for (int i = 0; i < M; ++i)
	{
		cin>>B[i];
	}
	int ans=0;
	for (int i = 0; i < N; ++i)
	{
		int x=C;
		for (int i = 0; i < M; ++i)
		{
			int y;
			cin>>y;
			x+=y*B[i];
		}
		if(x>0)
		{
			ans++;
		}
	}
	cout<<ans<<endl;

	// cin.close();
	// auto end = sc.now();
 //   	auto time_span = static_cast<chrono::duration<double>>(end - start);
 //   	cout<<"Operation took: "<<time_span.count()<<" seconds";

	return 0;
}


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

int main(){
    ll n,m;
    cin >> n >> m;
    vector<P> ab(n);
    rp(i,n){
        ll a,b;
        cin >> a >> b;
        ab.at(i)=make_pair(a,b);
    }
    sort(ab.begin(),ab.end());
    int ctr=0;
    ll money=0ll;
    while(m>0){
        if(m<ab.at(ctr).second){
            money += ab.at(ctr).first*m;
            m=0;
        }
        else{
            money += ab.at(ctr).first*ab.at(ctr).second;
            m-=ab.at(ctr).second;
            ctr++;
        }
    }
    cout << money << endl;
    return 0;
}

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

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


#define MOD_TYPE 1

#pragma region Macros
#include <bits/stdc++.h>
using namespace std;
/*
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using multiInt = boost::multiprecision::cpp_int;
using lld = boost::multiprecision::cpp_dec_float_100;
*/
/*
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
*/
using ll = long long int;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using pld = pair<ld, ld>;
template <typename Q_type>
using smaller_queue = priority_queue<Q_type, vector<Q_type>, greater<Q_type>>;

constexpr ll MOD = (MOD_TYPE == 1 ? (ll)(1e9 + 7) : 998244353);
constexpr int INF = (int)1e9;
constexpr ll LINF = (ll)4e18;
constexpr ld PI = acos(-1.0);
constexpr ld EPS = 1e-11;
constexpr int Dx[] = {0, 0, -1, 1, -1, 1, -1, 1, 0};
constexpr int Dy[] = {1, -1, 0, 0, -1, -1, 1, 1, 0};

#define REP(i, m, n) for (ll i = m; i < (ll)(n); ++i)
#define rep(i, n) REP(i, 0, n)
#define REPI(i, m, n) for (int i = m; i < (int)(n); ++i)
#define repi(i, n) REPI(i, 0, n)
#define MP make_pair
#define MT make_tuple
#define YES(n) cout << ((n) ? "YES" : "NO") << "\n"
#define Yes(n) cout << ((n) ? "Yes" : "No") << "\n"
#define possible(n) cout << ((n) ? "possible" : "impossible") << "\n"
#define Possible(n) cout << ((n) ? "Possible" : "Impossible") << "\n"
#define Yay(n) cout << ((n) ? "Yay!" : ":(") << "\n"
#define all(v) v.begin(), v.end()
#define NP(v) next_permutation(all(v))
#define dbg(x) cerr << #x << ":" << x << "\n";

inline void init_main()
{
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << setprecision(30) << setiosflags(ios::fixed);
}
template <typename T>
inline bool chmin(T &a, T b)
{
  if (a > b)
  {
    a = b;
    return true;
  }
  return false;
}
template <typename T>
inline bool chmax(T &a, T b)
{
  if (a < b)
  {
    a = b;
    return true;
  }
  return false;
}
inline ll CEIL(ll a, ll b)
{
  return (a + b - 1) / b;
}
#pragma endregion

template <int MOD>
struct Fp
{
  long long val;

  constexpr Fp(long long v = 0) noexcept : val(v % MOD)
  {
    if (val < 0)
      v += MOD;
  }

  constexpr int getmod()
  {
    return MOD;
  }

  constexpr Fp operator-() const noexcept
  {
    return val ? MOD - val : 0;
  }

  constexpr Fp operator+(const Fp &r) const noexcept
  {
    return Fp(*this) += r;
  }

  constexpr Fp operator-(const Fp &r) const noexcept
  {
    return Fp(*this) -= r;
  }

  constexpr Fp operator*(const Fp &r) const noexcept
  {
    return Fp(*this) *= r;
  }

  constexpr Fp operator/(const Fp &r) const noexcept
  {
    return Fp(*this) /= r;
  }

  constexpr Fp &operator+=(const Fp &r) noexcept
  {
    val += r.val;
    if (val >= MOD)
      val -= MOD;
    return *this;
  }

  constexpr Fp &operator-=(const Fp &r) noexcept
  {
    val -= r.val;
    if (val < 0)
      val += MOD;
    return *this;
  }

  constexpr Fp &operator*=(const Fp &r) noexcept
  {
    val = val * r.val % MOD;
    if (val < 0)
      val += MOD;
    return *this;
  }

  constexpr Fp &operator/=(const Fp &r) noexcept
  {
    long long a = r.val, b = MOD, u = 1, v = 0;
    while (b)
    {
      long long t = a / b;
      a -= t * b;
      swap(a, b);
      u -= t * v;
      swap(u, v);
    }
    val = val * u % MOD;
    if (val < 0)
      val += MOD;
    return *this;
  }

  constexpr bool operator==(const Fp &r) const noexcept
  {
    return this->val == r.val;
  }

  constexpr bool operator!=(const Fp &r) const noexcept
  {
    return this->val != r.val;
  }

  friend constexpr ostream &operator<<(ostream &os, const Fp<MOD> &x) noexcept
  {
    return os << x.val;
  }

  friend constexpr istream &operator>>(istream &is, Fp<MOD> &x) noexcept
  {
    return is >> x.val;
  }
};

Fp<MOD> modpow(const Fp<MOD> &a, long long n) noexcept
{
  if (n == 0)
    return 1;
  auto t = modpow(a, n / 2);
  t = t * t;
  if (n & 1)
    t = t * a;
  return t;
}

using mint = Fp<MOD>;

inline ll gcd(ll a, ll b)
{
  if (a < b)
    swap(a, b);
  return b == 0 ? a : gcd(b, a % b);
}

inline ll lcm(ll a, ll b)
{
  return a / gcd(a, b) * b;
}

int main()
{
  init_main();

  ll a, b, k;
  cin >> a >> b >> k;
  k--;
  for (ll i = a * b;; i--)
  {
    if (a % i == 0 && b % i == 0)
    {
      if (k == 0)
      {
        cout << i << endl;
        return 0;
      }
      else
      {
        k--;
      }
    }
  }

  return 0;
}

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


#include <iostream>
using namespace std;
int main(int argc, char** argv) {
	int a,b,k;
	cin >> a >> b >> k;
	for(int i=100;i>=1;i--)
	{
		if(a%i==0&&b%i==0)
		{
			--k;
		}
		if(k==0)
		{
			cout << i;
			return 0;
		}
	}
	return 0;
}


#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <math.h>
#include <algorithm>
using namespace std;
#define ll long long
const double EPS = 1e-10;

int main (){
  ll a,b,k;
  cin>>a>>b>>k;
  ll ans=min(a,b);
  for(ll i=0;i<k;i++){
    while(a%ans!=0||b%ans!=0)ans--;
    ans--;
  }
  ans++;
  cout<<ans<<endl;
}


#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <unordered_set>

typedef long long ll;

using namespace std;

vector<unordered_set<int>> cc;

int findVertex(int v) {
    for(int i = 0; i < cc.size(); ++i) {
        if(cc[i].count(v) > 0) {
            return i;
        }
    }
    return -1;
}

int main() {
    ll n = 0, m = 0;
    cin >> n >> m;

    vector<int> vs;
    vector<int> ve;
    for(int i = 0; i < m; ++i) {
        int s = 0, e = 0;
        cin >> s >> e;
        vs.push_back(s);
        ve.push_back(e);
    }

    ll total = n * (n - 1) / 2;
    vector<ll> answers;

    for(int i = 1; i <= n; ++i) {
        unordered_set<int> iset;
        iset.insert(i);

        cc.push_back(iset);
    }

    answers.push_back(total);

    ll curTotal = 0;
    for(ll i = m - 1; i >= 0; --i) {
        int posSi = findVertex(vs[i]);
        int posEi = findVertex(ve[i]);

        // if current two vertexs are already in one set
        if(posSi == posEi) {
            answers.push_back(total - curTotal);
            continue;
        }

        ll cs = (cc[posSi].size() * (cc[posSi].size() - 1)) / 2;
        ll ce = (cc[posEi].size() * (cc[posEi].size() - 1)) / 2;

        curTotal -= cs + ce;

        // merge the two sets
        for(unordered_set<int>::iterator it = cc[posEi].begin(); it != cc[posEi].end(); ++it) {
            cc[posSi].insert(*it);
        }

        // remove the original two sets
        cc[posEi].clear();

        // re-calculate total
        curTotal += (cc[posSi].size() * (cc[posSi].size() - 1)) / 2;
        answers.push_back(total - curTotal);
    }

    for(int i = int(answers.size()) - 2; i >= 0; --i) {
        cout << answers[i] << endl;
    }

    return 0;
}

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.

You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

All four cubes can be removed, by performing the operation as follows:

Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


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

int main(){
    string s;
    cin >> s;
    int originalSize = s.size();
    bool trimmed = false;

    while(true){
        trimmed = false;
        for(int i = 0; i < s.size(); i++){
            if (s[i] != s[i+1]) {
                s.erase(i, 2);
                trimmed = true;
                break;
            }
        }
        if (!trimmed) {
            break;
        }

    }

    int finalSize = s.size();
    cout << originalSize - finalSize << "\n";
}


//#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <queue>
#include <algorithm>
#include <sstream>
#include <vector>
#include <math.h>
#include <set>
#include <map>
#include <numeric>
#include <bitset>
#include <iomanip>
#include <cctype>
#include <cstdlib>      // srand,rand

using namespace std;
#define ll long long

#define modd 1000000007
#define INF 1000000000000000000ll

typedef pair<long long, long long> pl;

typedef string::const_iterator State;
class ParseError {};

/*

class UnionFind {
public:
	vector <ll> par;
	vector <ll> siz;

	// Constructor
	UnionFind(ll sz_) : par(sz_), siz(sz_, 1LL) {
		for (ll i = 0; i < sz_; ++i) par[i] = i;
	}
	void init(ll sz_) {
		par.resize(sz_);
		siz.assign(sz_, 1LL);  // resize だとなぜか初期化されなかった
		for (ll i = 0; i < sz_; ++i) par[i] = i; // 初期では親は自分自身
	}

	// Member Function
	// Find
	ll root(ll x) { // 根の検索
		while (par[x] != x) {
			x = par[x] = par[par[x]]; // x の親の親を x の親とする
		}
		return x;
	}

	// Union(Unite, Merge)
	bool merge(ll x, ll y) {
		x = root(x);
		y = root(y);
		if (x == y) return false;

		// merge technique（データ構造をマージするテク．小を大にくっつける）
		if (siz[x] < siz[y]) swap(x, y);
		siz[x] += siz[y];
		par[y] = x;
		return true;
	}

	bool issame(ll x, ll y) { // 連結判定
		return root(x) == root(y);
	}

	ll size(ll x) { // 素集合のサイズ
		return siz[root(x)];
	}

};*/

/*
struct SegmentTree {
private:
	ll n;
	vector<ll> node;

public:
	// 元配列 v をセグメント木で表現する
	SegmentTree(vector<ll> v) {
		// 最下段のノード数は元配列のサイズ以上になる最小の 2 冪 -> これを n とおく
		// セグメント木全体で必要なノード数は 2n-1 個である
		ll sz = v.size();
		n = 1; while (n < sz) n *= 2;
		node.resize(2 * n - 1, INF);

		// 最下段に値を入れたあとに、下の段から順番に値を入れる
		// 値を入れるには、自分の子の 2 値を参照すれば良い
		for (ll i = 0; i < sz; i++) node[i + n - 1] = v[i];
		for (ll i = n - 2; i >= 0; i--) node[i] = min(node[2 * i + 1], node[2 * i + 2]);
	}

	void update(ll x, ll val) {
		// 最下段のノードにアクセスする
		x += (n - 1);

		// 最下段のノードを更新したら、あとは親に上って更新していく
		node[x] = val;
		while (x > 0) {
			x = (x - 1) / 2;
			node[x] = min(node[2 * x + 1], node[2 * x + 2]);
		}
	}

};
*/

ll N, M, K, a, b, c, d, e, H, W, L, T;
ll x, y;
ll A[2000004] = {};
ll B[2000004] = {};
ll C[2000004] = {};
ll D[1000006] = {};
ll E[1000006] = {};
bool f, ff;
string S[200000];
string SS;
set <long long>sll;
pl bufpl;
vector <long long>vl[300005];
vector <long long>vll;
vector <pl>vpl;
vector <string> vs;
set<ll> llset;
multiset<ll> llmset;
queue<ll> ql;
multiset<pl> plmset;

struct ST
{
	ll first;
	ll second;
	ll kaisuu;

	/*bool operator<(const ST& another) const
	{
		return first < another.first;//比較
	};*/

};
queue<ST> qpl;

/*vector <ST> vst;
ST st[200005];
ST bufst;
bitset<5000> bits;*/

/*
long long modinv(long long aa, long long mm) {
	long long bb = mm, uu = 1, vv = 0;
	while (bb) {
		long long tt = aa / bb;
		aa -= tt * bb; swap(aa, bb);
		uu -= tt * vv; swap(uu, vv);
	}
	uu %= mm;
	if (uu < 0) uu += mm;
	return uu;
}

*/

ll zettai(ll aa) {

	if (aa < 0) {
		aa *= -1;
	}
	return aa;

}

class UnionFind
{

public:
	vector <ll>pairent;
	vector <ll>depth;
	vector <ll>size;

	UnionFind(ll Amount) : pairent(Amount, 1), depth(Amount, 1), size(Amount, 1) {

		for (ll i = 0; i < Amount; i++) {
			pairent[i] = i;
		}

	}

	ll FindPairent(ll x) {
		if (pairent[x] == x)return x;
		else return pairent[x] = FindPairent(pairent[x]);

	}

	ll Merge(ll x, ll y) {
		x = FindPairent(x);
		y = FindPairent(y);

		if (x != y) {
			if (depth[x] > depth[y]) {
				pairent[y] = pairent[x];
				return size[x] += size[y];
			}
			else {
				pairent[x] = pairent[y];
				if (depth[x] == depth[y]) {
					depth[y] ++;
				}

				return size[y] += size[x];
			}

		}
		else {
			return -1;
		}

	}

	bool IsSame(ll x, ll y) {
		if (FindPairent(x) == FindPairent(y))return true;
		else return false;
	}

	ll GetSize(ll x) {
		x = FindPairent(x);
		return size[x];
	}

};

int main() {

	cin >> N >>M;

	UnionFind uf(N);

	for (int i = 0; i < M; i++) {
		cin >> A[i] >> B[i];
		A[i]--;
		B[i]--;
	}
	C[M] = 0;

	for (int i = M - 1; i >= 0; i--) {
		int as = uf.GetSize(A[i]) * (uf.GetSize(A[i]) - 1) / 2 + uf.GetSize(B[i]) * (uf.GetSize(B[i]) - 1) / 2;

		if (uf.Merge(A[i], B[i]) != -1) {

			int bbb = uf.GetSize(uf.FindPairent(A[i]));
			C[i] = C[i + 1] + (bbb * (bbb - 1) / 2 - as);
		}
		else {
			C[i] = C[i + 1];
		}

	}

	for (int i = 1; i <= M; i++) {
		cout << N*(N-1)/2 - C[i] << endl;
	}
	//cout << fixed << setprecision(10) << ansa << endl;
	return 0;

}

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


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

int main(){
    ll a, b, q;
    cin >> a >> b >> q;
    vector<ll> s(a), t(b), x(q);
    rep(i, 0, a) cin >> s[i];
    rep(i, 0, b) cin >> t[i];
    rep(i, 0, q) cin >> x[i];
    rep(i, 0, q){
        auto pos = x[i];
        auto sitr = lower_bound(s.begin(), s.end(), pos);
        auto titr = lower_bound(t.begin(), t.end(), pos);
        ll s_l, s_r, t_l, t_r;
        if(sitr == s.begin()) {
            s_r = *sitr - pos;
            s_l = 1e18;
        }else if(sitr == s.end()){
            s_r = 1e18;
            s_l = pos - (*(sitr-1));
        }else{
            s_r = *sitr - pos;
            s_l = pos - *(sitr - 1);
        }
        if(titr == t.begin()) {
            t_r = *titr - pos;
            t_l = 1e18;
        }else if(titr == t.end()){
            t_r = 1e18;
            t_l = pos - (*(titr-1));
        }else{
            t_r = *titr - pos;
            t_l = pos - *(titr-1);
        }
        ll c1 = max(s_l, t_l);
        ll c2 = max(s_r, t_r);
        ll c3 = 2 * min(s_l, t_r) + max(s_l, t_r);
        ll c4 = 2 * min(s_r, t_l) + max(s_r, t_l);
        cout << min({c1, c2, c3, c4}) << endl;
    }
    return 0;
}

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

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

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


#include <bits/stdc++.h>
using namespace std;
long long dis(long long a, long b){
	return abs(a - b);
}
long long solve(long long p, vector<long long>&a){
	auto mayor = upper_bound(a.begin(), a.end(), p);
	auto menor = lower_bound(a.begin(), a.end(), p);
	long long ans = LLONG_MAX;
	if(mayor != a.end()) ans = min(ans, dis(p, *mayor));
	if(menor != a.begin()){
		menor--;
		ans = min(ans, dis(p, *menor));
	}
	return ans;
}
int main(){
	int n, m, q;
	long long x;
	cin >> n >> m >> q;
	vector<long long> a(n), b(m);
	for(int i = 0; i < n; ++i) cin >> a[i];
	for(int i = 0; i < m; ++i) cin >> b[i];
	sort(a.begin(), a.end());
	sort(b.begin(), b.end());
	while(q--){
		cin >> x;
		auto ya = upper_bound(a.begin(), a.end(), x);
		auto yb = upper_bound(b.begin(), b.end(), x);
		if(ya == a.end()) ya--;
		if(yb == b.end()) yb--;

		auto ma = lower_bound(a.begin(), a.end(), x);
		auto mb = lower_bound(b.begin(), b.end(), x);

		if(ma == a.end() or *ma > x and ma != a.begin() ) ma--;
		if(mb == b.end() or *mb > x and mb != b.begin()) mb--;

		long long menor_a = *ma;
		long long menor_b = *mb;
		long long mayor_a = *ya;
		long long mayor_b = *yb;
		long long ans = LLONG_MAX, aux;

		if(mayor_b >= x){
			aux =  solve(mayor_b, a);
			if(aux != LLONG_MAX)
			ans = min(ans, dis(mayor_b, x) + aux);
		}
		if(mayor_a >= x){
			aux =  solve(mayor_a, b);
			if(aux != LLONG_MAX)
			ans = min(ans, dis(mayor_a, x) + aux);
		}
		if(menor_b <= x){
			aux =  solve(menor_b, a);
			if(aux != LLONG_MAX)
			ans = min(ans, dis(menor_b, x) + aux);
		}
		if(menor_a <= x){
			aux =  solve(menor_a, b);
			if(aux != LLONG_MAX)
			ans = min(ans, dis(menor_a, x) + aux);
		}
		cout << ans << endl;
	}
	return 0;
}


#include<stdio.h>
int main(){
	int A,B;
	1 <=A && A<=B && B<=20;
	scanf("%d%d",&A,&B);
	if(B%A==0){
		printf("\n%d",A+B);}else{
		printf("\n%d",B-A);
	}
	return 0;
}

Score : 100 points

Problem Statement

You are given positive integers A and B.

If A is a divisor of B, print A + B; otherwise, print B - A.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

If A is a divisor of B, print A + B; otherwise, print B - A.

Sample Input 1

4 12

Sample Output 1

16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


#include<iostream>

using namespace std;

int main(){
    int a,b;
    cin >> a >> b;
    if (b%a==0){
        cout << a+b << endl;
    }else{
        cout << b-a << endl;
    }
    return 0;
}


#include <bits/stdc++.h>

#define INT_INF (2 * 1e9)
#define LL_INF  (2LL * 1e18)
#ifdef __LOCAL
#define DBG(X) cout << #X << "=" << (X) << endl;
#else
#define DBG(X)
#endif

using namespace std;

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

const ll mod = 1e9 + 7;
static mt19937 _g(time(nullptr));

inline ll randint(ll a, ll b) { ll w = (_g() << 31LL) ^ _g(); return a + w % (b - a + 1); }
inline void fast_io() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); };
template<typename T> inline T sign(T x) { return T(x > 0) - T(x < 0); }

void solve()
{
	int n, m;
	bool good[200];

	cin >> n >> m;

	for(int i = 1; i <= m; ++i)
		good[i] = true;

	for(int i = 0; i < n; ++i)
	{
		bool appeared[200];

		for(int j = 1; j <= m; ++j)
			appeared[j] = false;

		int k;
		cin >> k;

		for(int j = 0; j < k; ++j)
		{
			int val;
			cin >> val;

			appeared[val] = true;
		}

		for(int j = 1; j <= m; ++j)
			good[j] &= appeared[j];
	}

	int ans = 0;

	for(int j = 1; j <= m; ++j)
		ans += good[j];

	cout << ans << endl;
}

int main(int argc, char** argv)
{
	fast_io();
	solve();

	return 0;
}

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.

The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.

Find the number of the foods liked by all the N people.

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

Constraints

Input is given from Standard Input in the following format:

N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

Output

Print the number of the foods liked by all the N people.

Sample Input 1

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

Sample Output 1

1

As only the third food is liked by all the three people, 1 should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3


#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int n;

    cin >> n;

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

    cout << "test:";
    for (int i = 0; i < a.size(); i++)
    {
        cout << a[i] << " " ;
    }
    cout << endl;

    while (true)
    {
        int aa = rand() % a.size();     // 攻撃するもんすたー
        int ab = rand() % a.size() - 1; // 攻撃されるモンスター
        if (aa >= ab)
        {
            ab++;
        }

        a[ab] -= a[aa];
        if (a[ab] <= 0){
            a.erase(a.begin() + ab);
        }

        if (a.size() <= 1)
            break;
    }

    cout << a[0];
    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 <bits/stdc++.h>
using namespace std;
#define REP(i,a) for(int i = 0; i < (a); i++)
#define ALL(a) (a).begin(),(a).end()
typedef long long ll;
typedef pair<int, int> P;
const int INF = 1e9;
const long long LINF = 1e18;
const long long MOD = 1e9 + 7;

int d[] = {0, 2, 5, 5, 4, 5, 6, 3, 7, 6};

signed main(){
    int n,m;
    cin >> n >> m;
    bool use[10];
    REP(i,m){
        int a;
        cin >> a;
        use[a] = true;
    }
    vector<int> dp(n + 1, -INF);
    int prev[n + 1];
    dp[0] = 0;
    for(int i = 0; i <= n; i++){
        for(int j = 9; j >= 1; j--){
            if(!use[j]) continue;
            if(i - d[j] < 0) continue;
            if(dp[i - d[j]] + 1 > dp[i]){
                dp[i] = dp[i - d[j]] + 1;
                prev[i] = j;
            }
        }
    }
    string ans;
    int i = n;
    while(i != 0){
        ans.push_back('0' + prev[i]);
        i -= d[prev[i]];
    }
    cout << ans << endl;
    return 0;
}

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


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

int main()
{
  vector<int> data;
  for (int i=0; i < 3; i++) {
    int ai, bi;
	cin >> ai >> bi;
    data.push_back(ai);
    data.push_back(bi);
  }

  int c1, c2, c3, c4;
  c1 = c2 = c3 = c4 = 0;
  for (int i=0; i < data.size(); i++) {
    if (data[i] == 1) {
      c1++;
    } else if (data[i] == 2) {
      c2++;
    } else if (data[i] == 3) {
      c3++;
    } else {
      c4++;
    }
  }
  if (c1 > 2 || c2 > 2 || c3 > 2 || c4 > 2) {
    cout << "NO" << endl;
  } else {
    cout << "YES" << 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 <iostream>
#include <vector>
#include <string>
#include <algorithm>
#define FOR(i, n) for(int i = 0; i < (n); i ++)
#define CIN(type, val) type val; cin >> val;
#define COUT(val) cout << (val) << "\n";
#define Range(c) c.begin(), c.end()
using namespace std;

int main(void){
    CIN(int, n);
    CIN(int, m);

    vector<int> x(m);
    FOR(i, m) cin >> x[i];
    sort(Range(x));

    vector<int> dx(m-1);
    FOR(i, m-1) dx[i] = x[i+1] - x[i];
    sort(Range(dx));

    int ans = 0;
    int nn = m - n;
    FOR(i, nn) ans += dx[i];
    COUT(ans);
}

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>

#define rep(i, n) for(int i = 0; i<(n); i++)
#define chmax(x, y) x = max(x, y)
#define chmin(x, y) x = min(x, y)
using namespace std;
using ll = long long;

int main() {
    int N;
    cin >> N;
    vector<ll> A(N), B(N);
    rep(i, N) cin >> A[i] >> B[i];

    vector<ll> C(N);
    rep(i, N) C[i] = A[i] + B[i];
    sort(C.rbegin(), C.rend());

    ll ans = 0;
    rep(i, N) ans -= B[i];
    for (int i = 0; i < N; i += 2) ans += C[i];

    cout << ans << endl;
}

Score : 400 points

Problem Statement

There are N dishes of cuisine placed in front of Takahashi and Aoki.
For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.

When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.

Starting from Takahashi, they alternately choose one dish and eat it, until there is no more dish to eat.
Here, both of them choose dishes so that the following value is maximized: "the sum of the happiness he/she will earn in the end" minus "the sum of the happiness the other person will earn in the end".

Find the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Sample Input 1

3
10 10
20 20
30 30

Sample Output 1

20

In this sample, both of them earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since Takahashi and Aoki have the same "taste", each time they will choose the dish with which they can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (30 + 10) - 20 = 20.

Sample Input 2

3
20 10
20 20
20 30

Sample Output 2

20

In this sample, Takahashi earns 20 points of happiness by eating any one of the dishes 1, 2 and 3, but Aoki earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since only Aoki has likes and dislikes, each time they will choose the dish with which Aoki can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (20 + 20) - 20 = 20.

Sample Input 3

6
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 3

-2999999997

Note that the answer may not fit into a 32-bit integer.


#include <iostream>

using namespace std;

int main() {
    ios::sync_with_stdio(false);

    int a, b, c;
    cin >> a >> b >> c;

    cout << (a*b) / 2 << endl;

    return 0;
}

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.


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

int main() {
  int AB, BC, CA;
  cin >> AB >> BC >> CA;

  cout << AB * BC * 0.5 << endl;
}


#include <bits/stdc++.h>
#define sz(x) (int)(x).size()
#define For(i, a, b) for (int i = int(a); i < int(b); i++)
#define Dor(i, a, b) for (int i = int(b) - 1; i >= int(a); i--)
#define Foz(i, a) For(i, 0, a)
#define Doz(i, a) Dor(i, 0, a)
#define Trav(e, v) for (auto& e : v)
#define pb push_back
#define mp make_pair
#define all(x) begin(x), end(x)
using namespace std;
using ll = long long;
using ii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vii = vector<ii>;
template <typename T> bool ckmin (T& a, T b) { return (b < a) ? a = b, 1 : 0; }
template <typename T> bool ckmax (T& a, T b) { return (b > a) ? a = b, 1 : 0; }
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#ifdef XVENOM
	#define errp(...) fprintf(stderr, __VA_ARGS__)
	#define dbg(...) errp("[%s]: ", #__VA_ARGS__), dbg_str(__VA_ARGS__)
#else
	#define errp(...)
	#define dbg(...)
#endif
template <typename U, typename V> string to_string (pair<U, V>);
string to_string (string& e) { return "\"" + e + "\""; }
string to_string (char e) { return "\'" + string(1, e) + "\'"; }
string to_string (bool e) { return e ? "true" : "false"; }
template <typename T> string to_string (T e) {
	string s = "[ ";
	for (auto& x : e) s += to_string(x) + " ";
	return s + "]";
}
template <typename U, typename V> string to_string (pair<U, V> e) {
	return "(" + to_string(e.first) + ", " + to_string(e.second) + ")";
}
void dbg_str () { errp(" \n"); }
template <typename U, typename... V> void dbg_str (U u, V... v) {
 	errp(" %s", to_string(u).c_str()); dbg_str(v...);
}
/* --- */
int main() {
	ios_base::sync_with_stdio(0); cin.tie(0);
	/* --- */
	int n;
	cin >> n;
	vi a(n), f(n);
	Foz(i, n) cin >> a[i];
	f[0] = a[0];
	For(i, 1, n) f[i] = f[i - 1] + max(0, a[i] - a[i - 1]);
	cout << f[n - 1] << '\n';
}

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 <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstring>
#include <chrono>
#include <complex>
#define endl "\n"
#define ll long long int
#define vi vector<int>
#define vll vector<ll>
#define vvi vector < vi >
#define pii pair<int,int>
#define pll pair<long long, long long>
#define mod 1000000007
#define inf 1000000000000000001;
#define all(c) c.begin(),c.end()
#define mp(x,y) make_pair(x,y)
#define mem(a,val) memset(a,val,sizeof(a))
#define pb push_back
#define f first
#define s second
#define pi 3.141592653589793238
using namespace std;

ll gcd( ll a, ll b )
{
	if(b==0)
	{
		return a;
	}
	else
	{
		return gcd( b, a%b );
	}
}
ll lcm (ll a, ll b)
{
	return (a*b)/gcd(a,b);
}

ll power(ll a, ll b)	//a is base, b is exponent
{
	if(b==0)
		return 1;
	if(b==1)
		return a;
	if(b%2 == 1)
		return (power(a,b-1)*a)%mod;
	ll q = power(a,b/2);
	return (q*q)%mod;
}

bool cmp(pair<pll,ll> a,pair<pll,ll> b)
{
	pll p = a.f;
	pll q = b.f;

	if(a.s-p.s < b.s-q.s) return false;
	return true;
}

int main()
{
	std::ios::sync_with_stdio(false);
	ll n;
	cin >> n;
	ll a[n+2],b[n+2],c[n+2];
	ll suma =0,sumb=0;
	for(int i =0;i<n;i++) cin>>a[i], suma+=a[i];
	for(int i = 0;i<n;i++) cin >> b[i], sumb+=b[i];
//	cout << sum << endl;
	if(sumb>suma) return cout << -1 << endl,0;
	if(sumb==suma) return cout << "0\n",0;
	ll co=0;
	for(int i =0;i<n;i++)
	{
		if(a[i]<b[i])
		{
			// need to increase this
			c[i]  = b[i];
			co++;
		}
		else c[i] = a[i];
	}
	ll sumc = 0;
	for(int i =0;i<n;i++) sumc+=c[i];
	if(sumc==suma) return cout << co << endl,0;

	vector<pair<pll,ll>> vec;
	for(int i =0;i<n;i++)
	{
		pll p;
		p.f = a[i];
		p.s = b[i];
		vec.pb(mp(p,c[i]));
	}
	stable_sort(all(vec),cmp);
	if(sumc>suma)
	{
		ll k = sumc-suma;
		for(int i =0;i<n&&k>0;i++)
		{
			if(c[i]>b[i])
			{
				ll dif = c[i]-b[i];
				if(dif>=k)
				{
					c[i]-=k;
					k = 0;
					co++;
					break;
				}
				else
				{
					c[i]-=dif;
					k-=dif;
					co++;
				}
			}
		}
		cout << co << endl;
		return 0;
	}
	cout << co+1 << endl;

	return 0;
}

//Hello, this is a snippet.

Score : 400 points

Problem Statement

A university student, Takahashi, has to take N examinations and pass all of them.
Currently, his readiness for the i-th examination is A_{i}, and according to his investigation, it is known that he needs readiness of at least B_{i} in order to pass the i-th examination.

Takahashi thinks that he may not be able to pass all the examinations, and he has decided to ask a magician, Aoki, to change the readiness for as few examinations as possible so that he can pass all of them, while not changing the total readiness.

For Takahashi, find the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the following conditions:

The sum of the sequence A_1, A_2, ..., A_{N} and the sum of the sequence C_1, C_2, ..., C_{N} are equal.

For every i, B_i \leq C_i holds.

If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

A_i and B_i are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N}
B_1 B_2 ... B_{N}

Output

Print the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the conditions.
If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.

Sample Input 1

3
2 3 5
3 4 1

Sample Output 1

3

(A_1, A_2, A_3) = (2, 3, 5) and (B_1, B_2, B_3) = (3, 4, 1). If nothing is done, he cannot pass the first and second exams.
The minimum possible number of indices i such that A_i and C_i are different, 3, is achieved when:

(C_1, C_2, C_3) = (3, 5, 2)

Sample Input 2

3
2 3 3
2 2 1

Sample Output 2

0

In this case, he has to do nothing in order to pass all the exams.

Sample Input 3

3
17 7 1
25 6 14

Sample Output 3

-1

In this case, no matter what is done, he cannot pass all the exams.

Sample Input 4

12
757232153 372327760 440075441 195848680 354974235 458054863 463477172 740174259 615762794 632963102 529866931 64991604
74164189 98239366 465611891 362739947 147060907 118867039 63189252 78303147 501410831 110823640 122948912 572905212

Sample Output 4

5


#include <bits/stdc++.h>
using namespace std;
const int M=1e9+7;
bool cmp(int a,int b){
	return a>b;}
int main(){
int n,m;
long long c=1;
cin>>n>>m;
set <int> at,bt;
int a[n],b[m];
for(int i=0;i<n;i++){
cin>>a[i];
at.insert(a[i]);}
for(int i=0;i<m;i++){
cin>>b[i];
bt.insert(b[i]);}
if(at.size()!=n||bt.size()!=m){
cout<<0;
return 0;}
int al=0,bl=0;
sort(a,a+n,cmp);
sort(b,b+m,cmp);
for(int i=n*m;i>0;i--){
	if((al<n&&bl<m)&&(i==a[al]&&i==b[bl])){
		al++;
		bl++;}
	else if(al<n&&i==a[al]){
		c*=bl;
		al++;}
	else if(bl<m&&i==b[bl]){
		c*=al;
		bl++;}
	else
	c*=(al*bl-(n*m-i));
	c%=M;}
cout<<c;}

Score : 500 points

Problem Statement

Consider writing each of the integers from 1 to N \times M in a grid with N rows and M columns, without duplicates.
Takahashi thinks it is not fun enough, and he will write the numbers under the following conditions:

The largest among the values in the i-th row (1 \leq i \leq N) is A_i.

The largest among the values in the j-th column (1 \leq j \leq M) is B_j.

For him, find the number of ways to write the numbers under these conditions, modulo 10^9 + 7.

Constraints

1 \leq N \leq 1000

1 \leq M \leq 1000

1 \leq A_i \leq N \times M

1 \leq B_j \leq N \times M

A_i and B_j are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_{N}
B_1 B_2 ... B_{M}

Output

Print the number of ways to write the numbers under the conditions, modulo 10^9 + 7.

Sample Input 1

2 2
4 3
3 4

Sample Output 1

2

(A_1, A_2) = (4, 3) and (B_1, B_2) = (3, 4). In this case, there are two ways to write the numbers, as follows:

1 in (1, 1), 4 in (1, 2), 3 in (2, 1) and 2 in (2, 2).

2 in (1, 1), 4 in (1, 2), 3 in (2, 1) and 1 in (2, 2).

Here, (i, j) denotes the square at the i-th row and the j-th column.

Sample Input 2

3 3
5 9 7
3 6 9

Sample Output 2

0

Since there is no way to write the numbers under the condition, 0 should be printed.

Sample Input 3

2 2
4 4
4 4

Sample Output 3

0

Sample Input 4

14 13
158 167 181 147 178 151 179 182 176 169 180 129 175 168
181 150 178 179 167 180 176 169 182 177 175 159 173

Sample Output 4

343772227


#include<iostream>
#include<string>
#include<cmath>
#include<queue>
#include<map>
#include<set>
#include<list>
#include<iomanip>
#include<vector>
#include<random>
#include<functional>
#include<algorithm>
#include<stack>
#include<cstdio>
#include<bitset>
#include<unordered_map>
#include <climits>
#include<fstream>
using namespace std;
//---------------------------------------------------
//library zone!!!!!
typedef long long ll;
typedef long double ld;
#define rep(i,j) for(ll i=0;i<(long long)(j);i++)
#define all(a) (a).begin(),(a).end()
const ll Mod = 1000000007;
struct P {
	ll pos, cost;
};
bool operator<(P a, P b) { return a.cost < b.cost; }
bool operator>(P a, P b) { return a.cost > b.cost; }
struct B {
	ll to, cost;
};
struct E {
	ll from, to, cost;
};
bool operator<(E a, E b) {
	return a.cost < b.cost;
}
struct H {
	ll x, y;
};
bool operator<(H a, H b) {
	if (a.x != b.x) return a.x < b.x;
	return a.y < b.y;
}
bool operator>(H a, H b) {
	if (a.x != b.x) return a.x > b.x;
	return a.y > b.y;
}
bool operator==(H a, H b) {
	return a.x == b.x&&a.y == b.y;
}
bool operator!=(H a, H b) {
	return a.x != b.x || a.y != b.y;
}
ll gcd(ll i, ll j) {
	if (i > j) swap(i, j);
	if (i == 0) return j;
	return gcd(j%i, i);
}
ld mod_pow(ld x, ll n, ll p) {
	ld res = 1;
	while (n > 0) {
		if (n & 1) res = res * x;
		x = x * x;
		n >>= 1;
	}
	return res;
}//x^n%p
const ll Inf = 3023372036854775807;
const int inf = 1500000000;
#define int long long
//----------------------------------------------------
int a[2000], b[2000];
bool e[4000000];
int n, m;
int c[4000000];
int f[4000000];
bool d[4000000];
signed main() {
	cin >> n >> m;
	for (int i = 0; i < n; i++) {
		cin >> a[i];
		if (e[a[i]]) {
			cout << 0 << endl;
			return 0;
		}
		e[a[i]] = 1;
	}
	for (int i = 0; i <= n * m; i++) {
		e[i] = 0;
	}
	for (int j = 0; j < m; j++) {
		cin >> b[j];
		if (e[b[j]]) {
			cout << 0 << endl;
			return 0;
		}
		e[b[j]] = 1;
	}
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			c[min(a[i], b[j])]++;
			if (a[i] == b[j]) d[a[i]] = 1;
		}
	}
	for (int i = n * m; i >= 0; i--) {
		f[i] = f[i + 1] + c[i];
	}
	int ans = 1;
	for (int i = n * m; i >= 1; i--) {
		if (d[i]) continue;
		if (c[i] == 0) {
			ans *= (f[i] - (n*m - i));
		}
		else {
			ans *= c[i];
		}
		ans %= Mod;
	}
	cout << ans << endl;
}


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

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

	long long ans = -1;
	for(int i = 1; i < n; i++){
		long long cost = i * d + a[0] + a[i];
		for(int j = 1; j < n; j++){
			if(j != i){
				int costAdd = abs(i - j) * d + a[i] + a[j];
				for(int k = 0; k < j; k++){
					costAdd = min(costAdd, abs(k - j) * d + a[k] + a[j]);
				}
				cost += costAdd;
			}
		}
		if(ans == -1 || ans > cost)
			ans = cost;
	}

	cout << ans << "\n";

	return 0;
}

Score : 600 points

Problem Statement

There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}.
Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.

Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}.
For Takahashi, find the minimum possible total cost to achieve the objective.

Constraints

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

1 \leq D \leq 10^9

1 \leq A_{i} \leq 10^9

A_{i} and D are integers.

Input

Input is given from Standard Input in the following format:

N D
A_1 A_2 ... A_N

Output

Print the minimum possible total cost.

Sample Input 1

3 1
1 100 1

Sample Output 1

106

This cost can be achieved by, for example, building roads connecting City 1, 2 and City 1, 3.

Sample Input 2

3 1000
1 100 1

Sample Output 2

2202

Sample Input 3

6 14
25 171 7 1 17 162

Sample Output 3

497

Sample Input 4

12 5
43 94 27 3 69 99 56 25 8 15 46 8

Sample Output 4

658


#include <bits/stdc++.h>

using namespace std;

typedef unsigned long long ull;
typedef long long ll;
typedef long double ld;
#define int ll
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector< vi > vvi;
typedef vector< vvi > vvvi;
typedef vector<short> vs;
typedef vector<vs> vvs;
typedef vector<vvs> vvvs;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<vvl> vvvl;
typedef vector<ld> vld;
typedef vector<vld> vvld;
typedef vector<vvld> vvvld;
typedef vector<string> vst;
typedef vector<vst> vvst;
typedef pair<ld, ld> pld;
typedef complex<double> base;
typedef complex<int> point;

#define inmin(a, b) a = min(a, (b))
#define inmax(a, b) a = max(a, (b))
#define ALL(a) a.begin(),a.end()
#define RALL(a) a.rbegin(),a.rend()
#define sqr(x) ((x) * (x))
#define fori(i, n) for(int i = 0; i < int(n); ++i)
#define SZ(a) ((int)((a).size()))
#define triple(T) tuple<T, T, T>
#define quad(T) tuple<T, T, T, T>

#ifdef MAX_HOME
#define cerr cout
#else
#define cerr if (false) cerr
#endif

#define watch(x) cerr << (#x) << " = " << (x)    << endl;

const double PI = 2 * acos(0.0);

const string DIGITS = "0123456789";
const string ALPH = "abcdefghijklmnopqrstuvwxyz";

template <class T0, class T1>
inline ostream & operator << (ostream &out, pair<T0, T1> &a) {
    return out << "{" << a.first << ", " << a.second << "}";
}

template <class T0, class T1, class T2>
inline ostream & operator << (ostream &out, tuple<T0, T1, T2> &a) {
    return out << "{" << get<0>(a) << ", " << get<1>(a) << ", " << get<2>(a) << "}";
}

template <class T0, class T1, class T2, class T3>
inline ostream & operator << (ostream &out, tuple<T0, T1, T2, T3> &a) {
    return out << "{" << get<0>(a) << ", " << get<1>(a) << ", " << get<2>(a) << ", " <<  get<3>(a) << "}";
}

template<class T>
inline ostream & operator << (ostream &out, vector<T> &a) {
    out << "[";
    fori (i, a.size())
        out << a[i] << vector<string>{", ", "]  "}[i + 1 == a.size()];
    return out;
}

void smain();

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

#ifdef MAX_HOME
    freopen("input.txt", "r", stdin);
    clock_t start = clock();
#endif
    cout << setprecision(12) << fixed;
    smain();
#ifdef MAX_HOME
    cout << "\n\n\n\nTOTAL EXECUTION TIME: " << float( clock () - start ) /  CLOCKS_PER_SEC << endl;
#endif
}

const int N = 2e5 + 9;
const ll oo = 1e18 + 1000;

ll a[N];
ll n;
ll d;
ll lf[N], rf[N];

void smain() {

    cin >> n >> d;
    fori (i, n) cin >> a[i];

    ll ans = d * (n - 1);

    fori (i, n) {
        ans += a[i];
        if (i != 0 && i != n - 1) ans += a[i];
    }

    ll mn = oo;
    ll msk = 0;
    for (int i = 0; i < n; ++i) {
        if (i) msk += d;

        lf[i] = mn + msk;

        ll msked = a[i] - msk;
        if (msked < mn) {
            mn = msked;
        }
    }

    mn = oo;
    msk = 0;

    for (int i = n - 1; i >= 0; --i) {
        if (i + 1 != n) msk += d;

        rf[i] = mn + msk;

        ll msked = a[i] - msk;
        if (msked < mn) {
            mn = msked;
        }
    }

    for (int i = 1; i + 1 < n; ++i) {
        ll plus = min(lf[i], rf[i]);
        ll minus = a[i];
        if (minus > plus) ans += plus - minus;
    }
    cout << ans;
}


#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
typedef long long ll;
typedef long double ld;
const int inf=1e9+7;
const ll longinf=1LL<<60;
#define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i )
#define rep(i,n) REP(i,0,n)
#define F first
#define S second

const int mx=200010;
const ll mod=1e9+7;

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

int h,w;
vector<vector<char>> d(410, vector<char>(410,'?'));

int bfs(int x, int y){
  int cnt=0;
  queue<P> q;
  vector<vector<bool>> used(410, vector<bool>(410,false));
  q.push({x,y});
  used[x][y];

  while(!q.empty()){
    P p = q.front(); q.pop();
    rep(i,4){
      int nx = p.F+dx[i], ny = p.S+dy[i];
      if(nx<0 || h<=nx || ny<0 || w<=ny) continue;
      if(used[nx][ny]) continue;
      if(d[p.F][p.S]==d[nx][ny]) continue;
      q.push({nx,ny});
      used[nx][ny] = true;
      if(d[nx][ny]=='.') cnt++;
    }
  }
  return cnt;
}

int main() {
  cin >> h >> w;
  rep(i,h)rep(j,w) cin >> d[i][j];

  ll ans = 0;
  rep(i,h)rep(j,w)if(d[i][j]=='#'){
    ans += bfs(i,j);
  }

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

Score : 300 points

Problem Statement

There is a grid with H rows and W columns, where each square is painted black or white.

You are given H strings S_1, S_2, ..., S_H, each of length W.
If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is #; if that square is painted white, the j-th character in the string S_i is ..

Find the number of pairs of a black square c_1 and a white square c_2 that satisfy the following condition:

There is a path from the square c_1 to the square c_2 where we repeatedly move to a vertically or horizontally adjacent square through an alternating sequence of black and white squares: black, white, black, white...

Constraints

1 \leq H, W \leq 400

|S_i| = W (1 \leq i \leq H)

For each i (1 \leq i \leq H), the string S_i consists of characters # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
S_2
:
S_H

Output

Print the answer.

Sample Input 1

3 3
.#.
..#
#..

Sample Output 1

10

Some of the pairs satisfying the condition are ((1, 2), (3, 3)) and ((3, 1), (3, 2)), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

Sample Input 2

2 4
....
....

Sample Output 2

0

Sample Input 3

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

Sample Output 3

6


#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }

// 入力
int N;
long long a[100010][3]; // a[i], b[i], c[i] をそれぞれまとめて a[i][0], a[i][1], a[i][2] にしてしまう

// DP テーブル
long long dp[100010][3];

int main() {
    int N; cin >> N;
    for (int i = 0; i < N; ++i) for (int j = 0; j < 3; ++j) cin >> a[i][j];

    // 初期化は既に 0 に初期化される
    // 初期条件も既に 0 で OK

    // ループ
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 3; ++k) {
                if (j == k) continue;
                chmax(dp[i + 1][k], dp[i][j] + a[i][k]);
            }
        }
    }

    // 答え
    long long res = 0;
    for (int j = 0; j < 3; ++j) chmax(res, dp[N][j]);
    cout << res << endl;
}

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>
#define fin freopen("input", "r", stdin);
#define fout freopen("output", "w", stdout);
#define wt(x) cerr << #x << ": " << x << " ";
#define whatis(x) {cerr << #x << ": " << x << endl;}
#define whatis2(x, y) {wt(x); wt(y); cerr << endl;}
#define whatis3(x, y, z) {wt(x); wt(y); wt(z); cerr << endl;}
#define whatis4(x, y, z, a) {wt(x); wt(y); wt(z); wt(a); cerr << endl;}
using namespace std;

typedef long long ll; typedef unsigned long long ull; typedef long double ld;
const ll MOD = 1000000007; const ld PI = acos(-1.0);

const int N = (int) 1e2 + 10; // Max number of items
const int W = (int) 1e9 + 10; // Max weight my knapsack can hold
const int V = (int) 1e3 + 10; // Max value
ll dp[N][V * N];
struct ITEM { ll value; ll weight; };
ll n, mx_weight;
ll solve() {
    // dp[i][j] -> i: number of current elements
    // j: max current value
    // dp[i][j] returns the min weight with i elements and j value
    cin >> n >> mx_weight;
    vector<ITEM> items(n + 1);
    ll mx_value = 0;
    for (int i = 1; i <= n; ++i) {
        cin >> items[i].weight >> items[i].value;
        mx_value += items[i].value;
    }
    const int INF = 1e6;
    for (int i = 0; i <= n; ++i) {
        for (int cur_value = 0; cur_value <= mx_value; ++cur_value) {
            dp[i][cur_value] = INF;
        }
    }
    for (int i = 0; i <= n; ++i) dp[i][0] = 0;
    /* for (int cur_value = 0; cur_value <= mx_value; ++cur_value) dp[0][cur_value] = 0; */
    ll ans = 0;
    ll wt = 0;
    for (int i = 1; i <= n; ++i) {
        for (int cur_value = 1; cur_value <= mx_value; ++cur_value) {
            dp[i][cur_value] = dp[i-1][cur_value];
            if (items[i].value <= cur_value) {
                dp[i][cur_value] = min (dp[i-1][cur_value - items[i].value] + items[i].weight,
                        dp[i-1][cur_value]);
            }
            if (dp[i][cur_value] <= mx_weight) ans = max (ans, (ll) cur_value);
        }
    }
    /* whatis(wt); */
    return ans;
}

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

    cout << solve() << endl;

    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 <iostream>
#include <set>
#include <map>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <climits>
#include <numeric>
#include <cmath>
#include <queue>
#include <sstream>
#include <string.h>
#include <bitset>

using namespace std;
typedef long long ll;

const ll INF = 1LL<<62;
int dp[100100];
int N, M;
vector<vector<int>> G;

int rec(int v) {
  if (dp[v] != -1) {
    return dp[v];
  }
  int res = 0;
  for (int nv : G[v]) {
    res = max(res, rec(nv) + 1);
  }
  return dp[v] = res;
}

int main() {
  cin >> N >> M;
  G.assign(N, vector<int>());
  for (int i = 0; i < M; i++) {
    int x, y;
    cin >> x >> y;
    x--; y--;
    G[x].push_back(y);
  }

  for (int i = 0; i < N; i++) {
    dp[i] = -1;
  }

  int res = 0;
  for (int v = 0; v < N; ++v) {
    res = max(res, rec(v));
  }
  cout << res << endl;
  return 0;
}

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:


//		HYSO SERIOUS? WHY SO SERIOUS                            RIOUS? WHY SO SERIOUS? WHYSO SERIO
//		 ERIOUS? WHY SO SERIOUS ? WHY                          WHY SO SERIOUS? WHY SOSERIOUSWHYS
//		       OSERIOUS? WHY SO SERIOU         SERIOUS        ERIOUS? WHY SO SERIOUS? WHYS
//		          WHY SO SERIOUS? WHY SOSERIOUS? WHYSOSERIOUS? WHY SO SERIOUS?WHY SO SE
//		           ERIOUS? WHY SO SERIOUS? WHY SO SERIOUS? WHY SO SERIOUS? WHY SOSERIO
//		           WHY SO SERIOUS? WHY SO SERIOUS? WHY SO SERIOUS? WHY SO SERIOUS? WH
//		            SERIOUS?WHYSO SERIOUS? WHY SO SERIOUS? WHY SO SERIOUS? WHYSO SE
//		              ?WHYSOSERIOUS?WHY SO SERIOUS? WHY SO SERIOUS?WHYSO SERIOUS?
//		                           OSERIOUS? WHY SO SERIOUS?WHYSOSER
//		                                 HYSOSERIOUS?WHYSOSERI
//		                                     SOSERIOUS?W
//		                                         SER
//		                                          W

#include 	<ext/pb_ds/assoc_container.hpp>
#include 	<ext/pb_ds/tree_policy.hpp>
#include 	<iostream>
#include 	<queue>
#include 	<tuple>
#include 	<vector>
#include	<bits/stdc++.h>
#include	<algorithm>
#include 	<cmath>
#include 	<map>
#include 	<string>
#include 	<iomanip>
using 		namespace __gnu_pbds;
using 		namespace std;
#define 	ll  long long int
#define		read(a) long long int a; cin>>a;
#define 	readstr(s) string s; cin>>s;
#define 	readarr(a,l) long long int a[l]={0}; for(ll i=0;i<l;i++) cin>>a[i];
#define 	readc(c) char c; cin>>c;
#define 	loop(i,a,b) for(ll i=a;i<b;i++)
#define 	rloop(i,a,b) for(ll i=a;i>b;i--)
#define 	loopitr(vec) for(auto it=vec.begin();it!=vec.end();it++)
#define 	ff first
#define 	ss second
#define 	readmtrx(i,j,a,b) ll arr[a][b]={0};for(ll i=0;i<a;i++)for(ll j=0;j<b;j++) cin>>arr[i][j];
#define 	v(pi) vector<ll>pi
#define 	all(a) a.begin(), a.end()
#define 	yes cout <<"YES"<<endl;
#define 	no cout <<"NO"<<endl;
#define 	sc(x) cout << (#x) << " is " << (x) << endl;
#define 	vp(pi) vector<pair<ll,ll>>pi
#define 	fast ios_base::sync_with_stdio(false);cin.tie(0);
#define 	pb(p) push_back(p)
#define 	mp make_pair
#define 	mi(lol) map<ll,ll>lol
#define 	fsort(vec) sort(vec.begin(),vec.end())
#define 	rsort(vec) sort(vec.begin(),vec.end(),compare)
#define 	Endl endl
#define 	ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define 	roundoff std::cout << std::setprecision(15)
#define 	inf 9223372036854775807
#define 	infn -9223372036854775807
#define 	pi 3.14159265358979323846
const 		int mod = 1e9+7;
#define 	REVERSE(vec) reverse(vec.begin(),vec.end())

ll gcd (ll a, ll b) { return b ? gcd (b, a % b) : a; }
ll lcm (ll a, ll b) { return a / gcd(a, b) * b; }

//code start from here
char ch[1001][1001];
ll sum=0;
ll dp[1001][1001];
ll path(ll i, ll j, ll a,ll b){
	if(dp[i][j]!=-1) return (dp[i][j])%mod;
	if(i==a-1 && j==b-1) return dp[i][j]=1%mod;
	if(i==a-1 && ch[i][j+1]=='#') return dp[i][j]=0;
	if(j==b-1 && ch[i+1][j]=='.' && i+1<=a-1) return dp[i][j]=(path(i+1,j,a,b))%mod;
	if(j==b-1 && ch[i+1][j]=='#') return dp[i][j]=0;
	if(ch[i+1][j]!='#' && ch[i][j+1]!='#' && j+1<=b-1 && i+1<=a-1) return dp[i][j]=(path(i+1,j,a,b)+path(i,j+1,a,b))%mod;
	if(ch[i][j+1]!='#' && ch[i+1][j]!='.' && j+1<=b-1) return dp[i][j]=path(i,j+1,a,b)%mod;
	if(ch[i][j+1]=='#' && ch[i+1][j]=='.' && i+1<=a-1) return dp[i][j]=path(i+1,j,a,b)%mod;

}

int main() {
	fast;
	#ifndef ONLINE_JUDGE
 	 	freopen("input.txt","r",stdin);
	  	freopen("output.txt","w",stdout);
	#endif
	memset(dp,-1,sizeof(dp));
	read(a)
	read(b)
	loop(j,0,a){
		loop(i,0,b){
			readc(c)
			ch[j][i]=c;
		}
	}
	ll i=0;ll j=0;
	cout<<path(i,j,a,b)<<endl;
	return 0;
}

//ends here

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>
using namespace std;
const int N = 1001;

int m,n,f[N][N];
char c[N][N];

int main()
{
  scanf ("%d%d", &m,&n);
  for (int i=1; i<=m; i++)
  {
    scanf (" %s", c[i] + 1);
  }
  for (int i=1; i<=m; i++)
  for (int j=1; j<=n; j++)
    if (c[i][j] == '.')
      f[i][j] = (f[i][j-1] + f[i-1][j]) % 1000000007;
  cout << f[m][n];
  return 0;
}


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

#define int long long
#define pii pair<int,int>
#define pqi priority_queue<int>
#define pb push_back()
#define INF 1000000000000000000

#define pi acos(-1)

const int modu= (1e9)+7;

void testCase(int ti){
    cout<<"Case "<<ti<<": ";
}

int bigmod(int n,int p){
    if(p==0) return 1;
    int x=bigmod(n,p/2)%modu;
    x=(x*x)%modu;
    if(p%2) return (x*n)%modu;
    return x;
}

int modInverse(int a){
    return bigmod(a,modu-2)%modu;
}

void debug(string pr,vector<int> var,bool out=true){
    #ifdef OFFLINE
        ofstream fl;
        fl.open("debug.txt");
        fl<<pr;
        for(int i=0;i<var.size();i++) fl<<" "<<var[i];
        fl<<endl;
        fl.close();
    if(out){
        cout<<pr;
        for(int i=0;i<var.size();i++) cout<<" "<<var[i];
        cout<<endl;
    }
    #endif
}

void faster(){
    ios_base::sync_with_stdio(false);
    cin.tie();
    cout.tie();
}

void defInit(){
    //faster();
    #ifdef OFFLINE
      freopen("in.txt", "r", stdin);
      freopen("out.txt", "w", stdout);
    #endif
}

int add(int x,int y){
    int z =(x%modu + y%modu)%modu;
    while(z<0) z=(z+modu)%modu;
    return z;
}

int mul(int x,int y){
    int z = (x%modu * y%modu)%modu;
    while(z<0) z=(z+modu)%modu;
    return z;
}
// starts here
#define float long double
const int MAXN = 3000;
int n;
float ara[MAXN];
vector<vector<float>> dp(MAXN,vector<float>(MAXN,-1));

float calc(int idx,int rem){
    float &now=dp[idx][rem];
    if(now!=-1) return now;
    if(idx==n) return now=1;
    float ans1=0,ans2=0;
    if(rem) ans1=(1-ara[idx])*calc(idx+1,rem-1);
    ans2=ara[idx]*calc(idx+1,rem);
    return now=ans1+ans2;
}

int32_t main(){
    defInit();
    //Now I will start writing codes and start preparation to get errors
    cin>>n;
    for(int i=0;i<n;i++) cin>>ara[i];
    int rem=(n-1)/2;
    cout<<fixed<<setprecision(10);
    cout<<calc(0,rem);
    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


#pragma GCC optimize ("O3")
#include <bits/stdc++.h>
using namespace std;

#define MAXN ((int)1e3+5)
#define MOD ((int)1e9 + 7)
#define ll long long
#define _ << " " <<
#define TRACE(x) cout << #x << " = " << x << endl;
#define pb push_back
#define MP make_pair
#define pi pair<int,int>
#define vi vector<int>
#define vii vector<pi>
#define all(x) x.begin(), x.end()

int n,m,t,k;
double p[MAXN];
double dp[MAXN][MAXN];

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

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

	// for (int i = 0; i < n; ++i)
	// {
	// 	cout << 1-p[i] << endl;
	// }

	dp[0][0] = 1.0f-p[0];
	dp[0][1] = p[0];

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

	double ans = 0;
	for (int i = n/2+1; i <= n; ++i)
	{
		// cout << i _ dp[n-1][i] << endl;
		ans += dp[n-1][i];
	}

	cout << std::setprecision(12) << ans;
	// for (int i = 0; i < n; ++i)
	// {
	// 	cout << i << " : ";
	// 	for (int j = 0; j <= i+1; ++j)
	// 	{
	// 		cout << dp[i][j] << " ";
	// 	}
	// 	cout << endl;
	// }
	return 0;
}


#include<bits/stdc++.h>
#define endl '\n'
#define ll long long int
#define loop(i,a,b)           for(ll i=a;i<=b;++i)
#define pb                    push_back
#define F                     first
#define S                     second
#define mp                    make_pair
#define clr(x)                x.clear()
#define MOD                   1000000007
#define itoc(c)               ((char)(((int)'0')+c))
#define vl                    vector<ll>
#define SZ(x)                 (x).size()
#define all(p)                p.begin(),p.end()
#define mid(s,e)              (s+(e-s)/2)
#define sv()                  ll t,n; scanf("%lld",&t);n=t; while(t--)
#define tcase()               ll t,n; cin>>t;n=t; while(t--)
#define iscn(num)             scanf("%d",&num);
#define scn(num)              scanf("%lld",&num);
#define scn2(num,num2)        scanf("%lld%lld",&num,&num2);
#define dbg(x)                cerr <<"( "<<#x << " = " << x << " )"<<endl
using namespace std;
const ll INF = 2e18 + 99;
typedef pair<ll,ll> Pair;
typedef vector<int> vec;;
void FAST_IO();
void ara_read(vec &v,ll n);
////////////////////////

int main()
{
	int n, k;
	scanf("%d%d",&n,&k);
	vec num;
	ara_read(num,n);
	// taking number of stones k, as dp dimension...
	vector< bool > dp(k+1);

	for(int stone=0; stone<= k; ++stone){
		for(auto x : num){
			if(stone>= x  && !dp[stone-x]){
				dp[stone]=true;
				break ;
			}
		}
	}
	// if dp[k] is true, that means first player is winner
    puts((dp[k] ? "First" : "Second"));
    return 0;
}

void FAST_IO()
{
    // ios_base::sync_with_stdio(0);
    //cin.tie(NULL);
    //cout.tie(NULL);
    //cout.setf(ios::fixed);
    //cout.precision(2);

}
void ara_read(vec &v,ll n){
	v.resize(n);
	for(int & i : v){
		scanf("%d",&i);
	}

}

Score : 100 points

Problem Statement

There is a set A = \{ a_1, a_2, \ldots, a_N \} consisting of N positive integers.
Taro and Jiro will play the following game against each other.

Initially, we have a pile consisting of K stones.
The two players perform the following operation alternately, starting from Taro:

Choose an element x in A, and remove exactly x stones from the pile.

A player loses when he becomes unable to play.
Assuming that both players play optimally, determine the winner.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 10^5

1 \leq a_1 < a_2 < \cdots < a_N \leq K

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 \ldots a_N

Output

If Taro will win, print First; if Jiro will win, print Second.

Sample Input 1

2 4
2 3

Sample Output 1

First

If Taro removes three stones, Jiro cannot make a move.
Thus, Taro wins.

Sample Input 2

2 5
2 3

Sample Output 2

Second

Whatever Taro does in his operation, Jiro wins, as follows:

If Taro removes two stones, Jiro can remove three stones to make Taro unable to make a move.

If Taro removes three stones, Jiro can remove two stones to make Taro unable to make a move.

Sample Input 3

2 7
2 3

Sample Output 3

First

Taro should remove two stones. Then, whatever Jiro does in his operation, Taro wins, as follows:

If Jiro removes two stones, Taro can remove three stones to make Jiro unable to make a move.

If Jiro removes three stones, Taro can remove two stones to make Jiro unable to make a move.

Sample Input 4

3 20
1 2 3

Sample Output 4

Second

Sample Input 5

3 21
1 2 3

Sample Output 5

First

Sample Input 6

1 100000
1

Sample Output 6

Second