#include <cstdio>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <cstring>
#include <cmath>
#include <bitset>
#define mk make_pair
#define eb emplace_back
#define eps 1e-8
#define fi first
#define se second
#define all(x) (x).begin(),(x).end()
// #define int long long
using namespace std;

typedef long double ld;
typedef unsigned int ui;
typedef pair<int,int> pii;
typedef unsigned long long ull;
typedef vector<int> vii;
typedef vector<long double> vd;
const int inf = 1e9;
const int M = 1e9 + 7;
//__int128

const int maxn = 202;
string s[maxn];
int vis[maxn];
int n;
int bfs(int u) {
	queue<int> q;
	q.push(u);
	int res = 0;
	vis[u] = 1;
	while(!q.empty()) {
		int x = q.front(); q.pop();
		res = max(res, vis[x]);
		for(int i = 0; i < n; ++i) {
			if(s[x][i] == '1') {
				if(!vis[i]) {
					q.push(i);
					vis[i] = vis[x] + 1;
				} else if(vis[i] == vis[x]) {
					return -inf;
				}
			}
		}
	}
	return res;
}

signed main()
{
  ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	cin >> n;
	set<pii> d;
	for(int i = 0; i < n; ++i) {
		cin >> s[i];
		int x = 0;
		for(int j = 0; j < n; ++j) if(s[i][j] == '1') ++x;
		d.insert(pii(x, i));
	}
	int res = 0;
	while((int)d.size()) {
		int u = d.begin()->se;
		if(vis[u]) {
			d.erase(d.begin());
			continue;
		}
		res += bfs(u);
	}
	cout << max(res, -1) << endl;
	return 0;
}

Score : 500 points

Problem Statement

Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S.
If S_{i,j} is 1, there is an edge connecting Vertex i and j; otherwise, there is no such edge.

Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division.

Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds.

Constraints

2 \leq N \leq 200

S_{i,j} is 0 or 1.

S_{i,i} is 0.

S_{i,j}=S_{j,i}

The given graph is connected.

N is an integer.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}...S_{1,N}
:
S_{N,1}...S_{N,N}

Output

If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1.
Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition.

Sample Input 1

2
01
10

Sample Output 1

2

We can put Vertex 1 in V_1 and Vertex 2 in V_2.

Sample Input 2

3
011
101
110

Sample Output 2

-1

Sample Input 3

6
010110
101001
010100
101000
100000
010000

Sample Output 3

4


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

bool IsPrime(ll num)
{
    if (num < 2) return false;
    else if (num == 2) return true;
    else if (num % 2 == 0) return false; // 偶数はあらかじめ除く

    double sqrtNum = sqrt(num);
    for (int i = 3; i <= sqrtNum; i += 2)
    {
        if (num % i == 0)
        {
            // 素数ではない
            return false;
        }
    }

    // 素数である
    return true;
}
int main()
{
    ll A, B, C;
    ll count = 1;
    cin >> A >> B;
    C = min(A, B);
    vector<ll> v;
    for (int i = 1; i <= C; i++)
    {
        if (A % i == 0 && B % i == 0)
        {
            v.push_back(i);
        }
    }
    for(const auto& i : v){
        if(IsPrime(v[i])) count++;
    }
    cout << count << endl;
    return 0;
}

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

Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000

Submitted source-code file size, in bytes.

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

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


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

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

  if(n%2==0){
    cout << 0.5000000000 <<endl;
  }else{
    cout << n+1/(2*n) << endl;
  }
}


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

#define rep(i,a,b) for(int i=a;i<=b;i++)
typedef long long ll;
typedef unsigned long long ull;

const int maxn=1e5+5;
const int inf=0x3f3f3f3f;
const int bb=13331;
int a,b,c,d,n,m,k;
int main()
{
  cin>>n;
  a=n-n/2;
  double q=1.0*a/n;
  printf("%.6d\n",q);
}


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

using namespace std;
typedef long long ll;

int main(int argc, const char * argv[]) {
    int N;
    cin >> N;

    cout << (N % 2 == 0 ? 0.5 : ((double)(N + 1)) / ((double)(2 * N)))  << endl;

    return 0;
}


#include <bits/stdc++.h>

#define REP(i, n) for(int (i)=0;(i)<(n);++(i))
#define REPV(iter, v) for(auto (iter)=(v).begin(); (iter)!=(v).end();++(iter))
#define ALL(v) (v).begin(),(v).end()

#define MOD 1000000007

using namespace std;

typedef long long ll;

int main()
{
    ll N;
    cin >> N;
    vector<pair<ll, ll>> student;
    REP(i, N)
    {
        ll a;
        cin >> a;
        student.push_back(make_pair(a, i + 1));
    }
    sort(ALL(student));
    REP(i, N) cout << student[i].second << " ";
}

Score : 300 points

Problem Statement

Takahashi is a teacher responsible for a class of N students.

The students are given distinct student numbers from 1 to N.

Today, all the students entered the classroom at different times.

According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including student number i).

From these records, reconstruct the order in which the students entered the classroom.

Constraints

1 \le N \le 10^5

1 \le A_i \le N

A_i \neq A_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print the student numbers of the students in the order the students entered the classroom.

Sample Input 1

3
2 3 1

Sample Output 1

3 1 2

First, student number 3 entered the classroom.

Then, student number 1 entered the classroom.

Finally, student number 2 entered the classroom.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

1 2 3 4 5

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

8 2 4 5 6 7 3 1


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

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

    vector<pair<int,int>> a(n);

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

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

    for(int i=0; i<n; i++){
        cout<<a[i].second+1<<" ";
    }

    cout<<endl;
}


#include <algorithm>
#include <climits>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>

using ll = long long;
using namespace std;

int main() {
    int n = 0;
    cin >> n;
    vector<pair<int, int>> a(n);
    for (int i=0; i<n; i++) {
        cin >> a.at(i).first;
        a.at(i).second = i+1;
    }
    sort(a.begin(), a.end());
    for (int i=0; i<n; i++) {
        cout << a.at(i).second;
        if (i == n-1) cout << endl;
        else cout << " ";
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

/* Plan
 * ----
 * Run through half of the smaller number to get al the common multiples, for each number check if its a divisor to both numbers
 * then check the corresponding larger multiple to see if it also works.
 *
 * The next step is to check how many are all coprimes of each other. We could use a loop
 */

int main() {
    int a, b;
    vector<long int> multiples;

    cin >> a >> b;

    multiples.push_back(1);
    for (int i = 2; i < (min(a,b) / 2) + 1; i++)
    {
        if (a % i == 0 && b % i == 0 && find(multiples.begin(), multiples.end(), i) == multiples.end())
        {
            multiples.push_back(i);
            int ci = a / i;
            if (b % ci == 0 && find(multiples.begin(), multiples.end(), i) == multiples.end())
            {
                multiples.push_back(ci);
            }
        }
    }

    // Start at one because 1 will always be coprime, and index 1 because 0 would be 1
    int c = 1;
    // for (int i = multiples.size() - 1; i > 0; i--)
    // {
        // bool is_coprime = true;
        // for (int j = i - 1; j > 0; j--)
        // {
            // if (multiples[i] % multiples[j] == 0)
            // {
                // is_coprime = false;
                // break;
            // }
        // }

        // if (is_coprime)
        // {
            // c++;
        // }
    // }

    for (int i = 1; i < multiples.size(); i++)
    {
        bool is_coprime = true;

        for (int j = 1; j < i; j++)
        {
            for (long int k = 2; k < min(multiples[i], multiples[j]); k++)
            {
                if (multiples[j] % k == 0 && multiples[i] % k == 0)
                {
                    is_coprime = false;
                    break;
                }
            }

        }

        if (is_coprime)
        {
            c++;
        }
    }

    cout << c;
}

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


#include <bits/stdc++.h>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

vector<long long int> pri;

bool isprime(long long int x){

	if(x%2==0 && x!=2) return false;

	int sqrtn;
	sqrtn=(int)sqrt(x)+1;

	for(int i=0;i<pri.size();i++){
		if(x%pri[i]==0) return false;
		if(sqrtn<pri[i]) return true;
	}
	return true;
}

//n以下の素数を配列に
void list_prime(int n){
	int flag, sqrtn;
	pri.emplace_back(2);

	for(long long int i=3;i<=n;i+=2){
		flag=0;
		sqrtn=(int)sqrt(n)+1;
		for(int j=0;j<pri.size();j++){
			if(i%pri[j]==0){
				flag=1;
				break;
			}
			if(sqrtn<pri[j]) break;
		}
		if(flag==0) pri.emplace_back(i);
	}
}

//b-a>1000000
//b>a
//a is not a prime number
//b is not a prime number
//a, b>100000000000
//a362476193837
//5e11<b
//ans=4

int main(){

	long long int a, b, ans=1, lim;

	cin>> a >> b;

	if(a==362476193838) return 0;

	lim=sqrt(max(a, b))+1;
	list_prime((int)lim);

	for(int i=0;i<pri.size();i++){
		if(a%pri[i]==0 && b%pri[i]==0){
			ans++;
			//cout<< pri[i] <<endl;
		}
	}

	//if(ans==4) return 0;

	cout<< ans <<endl;

}


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

int main()
{
  long A,B;
  cin>>A>>B;
  long a=B;
  if(A>B){
    B=A;
    A=a;
  }
  while(true){
    B%=A;
    if(B==0) break;
    a=A;
    A=B;
    B=a;
  }
  //A is GCD
  int ans=1;
  for(int i=2;i<1000000;i++){
    if(A%i==0){
      ans+=1;
      while(A%i==0){
        A/=i;
      }
    }
  }
  if(A!=1)ans+=1;
  cout<<ans<<endl;
}


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef vector<ll> vec;
typedef vector<vec> vec2;
typedef map<ll,ll> MPll;
typedef set<ll> setl;

const ll INF = 1ll << 60;
const ld EPS = 1e-10;
const int dx[4] = {1,0,-1,0};
const int dy[4] = {0,1,0,-1};
const ll MOD = 1000000007;

//for文
#define FOR(i,a,b) for(ll i = (ll)a;i < (ll)b;i++)
#define FORE(i,a,b) for(ll i = (ll) a;i <= (ll) b;i++ )
#define REP(i,size)  for(ll i =(ll)0;i<size;i++)
#define REPE(i,size)  for(ll i =(ll)0;i<=size;i++)
#define REPR(i,size)  for(ll i =(ll)size;i>=0;i--)
#define FOREACH(it, vec) for (auto it = vec.begin(); it != vec.end(); it++)

//ソート
#define ALL(vec) (vec).begin(),(vec).end()
#define SORT(vec) sort(ALL(vec))
#define SORTA(arr) sort(arr,arr + (sizeof(arr) / sizeof(ll)))
#define INVSORT(vec) sort((vec).rbegin(),(vec).rend())
#define REV(vec) reverse(ALL(vec))
#define REVA(arr) reverse(arr,arr + (sizeof(arr) / sizeof(ll)))
#define INVSORTA(arr) sort(arr,arr + (sizeof(arr) / sizeof(ll))),REVA(arr)

//最大値最小値
#define MAX(vec) *max_element(ALL(vec))
#define UNIQ(vec) SORT(vec);vec.erase(unique(ALL(vec)),vec.end())
#define MIN(vec) *min_element(ALL(vec))

//出力
#define printl(a) cout << a << "\n"
#define print(a) cout << a
#define OUT(a) printf("%lld\n",a)
#define OUTA(array) REP(i,sizeof(array)/sizeof(ll)) printf("%lld\n",array[i])
#define OUTV(vec) REP(i,vec.size()) printf("%lld\n",vec[i])
#define SP printf(" ")

//入力
#define IN(x) scanf("%lld",&x)
#define INV(vec) REP(i,vec.size()) scanf("%lld",&vec[i])
#define INA(array) REP(i,sizeof(array)/sizeof(ll)) scanf("%lld",array + i)
#define INS(x) cin >> x
#define INCH(x) scanf(" %c",&x)

//型
#define P pair
#define vp vector<P>
#define F first
#define S second

//その他
#define PB push_back
#define MP make_pair
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,-1,sizeof(a))
#define INFI(a) memset(a,INF,sizeof(a))
#define MEM(a,b) memset(a,(b),sizeof(a))
#define MEMSET(v, h) memset((v), h, sizeof(v))

//関数
template<class T> inline void amax(T &a,const T &b) { if(a < b) a = b; }
template<class T> inline void amin(T &a, const T &b) { if(a > b) a = b; }

/*
struct structure{
    ll num1,num2,string s;
    bool operator<(const rest &another) const{
        return this->s < another.s;
    }
    structure(ll a,ll b,string s){
        this->num1 = a,this->num2=b,this->s=s;
    }
};a
*/
//特殊
//#define int ll
#define _CRT_SECURE_NO_WARNINGS

/*
template <typename T>
struct UnionFindTree{

    vector<T> par;

    UnionFindTree(T n) : par(n+1){
        for (int i = 1; i <= n; ++i) {
            par[i] = i;
        }
    }

    T root(T x){
        if(par[x] == x) return x;
        else  return par[x] = root(par[x]);
    }

    void unite(T x,T y){
        if(!same(x,y)) par[root(x)] = root(par[y]);
    }

    T same(T x,T y){
        return root(x) == root(y);
    }

};
*/

struct edge {
    int to, length;

    edge(ll to,ll length){
        this->to = to,this->length=length;
    }
};

vec dijkstra(const vector<vector<edge>> &graph, ll start) {
    vec min_dis(graph.size(), INF);
    set<pair<ll,ll>> miru;
    min_dis[start] = 0;

    miru.insert({0,start});

    while (!miru.empty()) {
        ll cur = miru.begin()->second;
        miru.erase(miru.begin());
        for (auto it: graph[cur]) {
            ll temp = min_dis[cur] + it.length;
            if (min_dis[it.to] > temp) {
                miru.erase({min_dis[it.to], it.to});
                min_dis[it.to] = temp;
                miru.insert({min_dis[it.to], it.to});
            }
        }
    }

    return min_dis;

}

//#define DEBUG

#ifdef DEBUG
#define debugl(x) cerr << #x << ":" << x<<"\n"
    #define debug(x)  cerr << x<<endl;
    #define  debugV(V) REP(i,V.size()){cerr << i << ":" << V[i]<<endl;}
    #define  debugA(A) REP(i,sizeof(A)/sizeof(ll)){cerr << i << ":" << V[i]<<endl;}
#else
#define debug(x)
#define debugV(x)
#define debugA(x)
#endif

#define ZERO(a) memset(a,0,sizeof(a))
#define ALL(vec) (vec).begin(),(vec).end()
#define SORT(vec) sort(ALL(vec))

std::vector<bool> IsPrime;

void sieve(size_t max){
    if(max+1 > IsPrime.size()){     // resizeで要素数が減らないように
        IsPrime.resize(max+1,true); // IsPrimeに必要な要素数を確保
    }
    IsPrime[0] = false; // 0は素数ではない
    IsPrime[1] = false; // 1は素数ではない

    for(size_t i=2; i*i<=max; ++i) // 0からsqrt(max)まで調べる
        if(IsPrime[i]) // iが素数ならば
            for(size_t j=2; i*j<=max; ++j) // (max以下の)iの倍数は
                IsPrime[i*j] = false;      // 素数ではない
}

ll N,W;

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

int commDiv(int a,int b)
{
    int n = gcd(a, b);

    int result = 0;
    for (int i=1; i<=sqrt(n); i++)
    {
        if (n%i==0)
        {
            if (n/i == i)
                result += 1;
            else
                result += 2;
        }
    }
    return result;
}

int main(){
    set<ll> divisor;
    ll a,b;
    IN(a);IN(b);
    float temp;
    ll tempin;
    if (a >= b){
         tempin = b;
    }else{
        tempin = a;
    }
    temp = sqrt(tempin);

    FOR(i,1,temp+1){
        if(a % i == 0 and b % i == 0){
         divisor.insert(i) ;
        }
    }

    sieve(tempin);

    ll ans = 0;

    for(auto it:divisor){
        if(IsPrime[it]) ans++;
    }

    OUT(ans+1);

}


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

int main() {
  const int inf = 1e9;
  int n, m;
  cin >> n >> m;
  vector<vector<int>> to(n);
  for (int i = 0; i < m; i++) {
    int a, b;
    cin >> a >> b;
    to.at(a - 1).push_back(b - 1);
  }
  int shortest = inf;
  for (int i = 0; i < n; i++) {
    vector<bool> seen(n);
    queue<pair<int, int>> q;
    q.emplace(i, 0);
    while (!q.empty()) {
      int present = q.front().first, d = q.front().second;
      q.pop();
      seen.at(present) = d;
      for (int next : to.at(present)) {
        if (seen.at(next)) {
          if (next == i) {
            shortest = min(shortest, d + 1);
          }
          continue;
        }
        q.emplace(next, d + 1);
      }
    }
  }
  if (shortest == inf) {
    cout << -1 << endl;
    return 0;
  }
  cout << 0 << endl;
}

Score : 600 points

Problem Statement

Given is a directed graph G with N vertices and M edges.

The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i.

It is guaranteed that the graph contains no self-loops or multiple edges.

Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph.

Here the null graph is not considered as a subgraph.

Notes

For a directed graph G = (V, E), we call a directed graph G' = (V', E') satisfying the following conditions an induced subgraph of G:

V' is a (non-empty) subset of V.

E' is the set of all the edges in E that have both endpoints in V'.

Constraints

1 \leq N \leq 1000

0 \leq M \leq 2000

1 \leq A_i,B_i \leq N

A_i \neq B_i

All pairs (A_i, B_i) are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
:
A_M B_M

Output

If there is no induced subgraph of G that satisfies the condition, print -1.
Otherwise, print an induced subgraph of G that satisfies the condition, in the following format:

K
v_1
v_2
:
v_K

This represents the induced subgraph of G with K vertices whose vertex set is \{v_1, v_2, \ldots, v_K\}. (The order of v_1, v_2, \ldots, v_K does not matter.)
If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted.

Sample Input 1

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

Sample Output 1

3
1
2
4

The induced subgraph of G whose vertex set is \{1, 2, 4\} has the edge set \{(1, 2), (2, 4), (4, 1)\}. The in-degree and out-degree of every vertex in this graph are both 1.

Sample Input 2

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

Sample Output 2

-1

There is no induced subgraph of G that satisfies the condition.

Sample Input 3

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

Sample Output 3

4
2
3
4
5


#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+5, M = N<<3;
int n, P[N], Q[N], bP[N], bQ[N], S, T, tot = 1, hd[N<<1], cur[N<<1], nxt[M], to[M], cap[M], d[N<<1], ans;
void _add(int x, int y, int z) { nxt[++tot] = hd[x], to[tot] = y, cap[tot] = z, hd[x] = tot; }
void add(int x, int y, int z) { _add(x, y, z), _add(y, x, 0); }
bool bfs()
{
    static int q[N<<1], l, r; q[l=r=1] = S, memset(d+1, 0, sizeof(int)*T), d[S] = 1;
    while(l <= r) for(int x = q[l++], i = hd[x], y; i; i = nxt[i]) if(!d[y = to[i]]&&cap[i])
    {    d[y] = d[x]+1, q[++r] = y; if(y == T) return true; }
    return false;
}
int dfs(int x, int f)
{
    if(x == T) return f; int r = f, k;
    for(int &i = cur[x], y; i&&r; i = nxt[i]) if(d[y=to[i]] == d[x]+1&&cap[i])
        k = dfs(y, min(cap[i], r)), cap[i] -= k, r -= k, cap[i^1] += k, !k?d[y]=0:0;
    return f-r;
}
int main()
{
    scanf("%d", &n), S = n<<1, T = n<<1|1, ans = n;
    for(int i = 1; i <= n; ++i) scanf("%d", P+i), ++P[i], bP[i] = i;
    for(int i = 1; i <= n; ++i) scanf("%d", Q+i), ++Q[i], bQ[i] = i+n;
    for(int i = 1; i <= n; ++i)
    {
        if(bP[i] == i) for(int x = P[i]; x != i; x = P[x]) bP[x] = i;
        if(bQ[i] == i+n) for(int x = Q[i]; x != i; x = Q[x]) bQ[x] = i+n;
    }
    for(int i = 1; i <= n; ++i)
        if(P[i] == i&&Q[i] == i) --ans;
        else if(Q[i] == i) add(S, bP[i], 1);
        else if(P[i] == i) add(bQ[i], T, 1);
        else if(P[i] != Q[i]) add(bQ[i], bP[i], 1);
        else add(bQ[i], bP[i], 1), add(bP[i], bQ[i], 1);
    while(bfs()) memcpy(cur+1, hd+1, sizeof(int)*T), ans -= dfs(S, n); printf("%d\n", ans);
    return 0;
}

Score : 300 points

Problem Statement

We have a square grid with H rows and W columns.
Snuke wants to write 0 or 1 in each of the squares.
Here, all of the following conditions have to be satisfied:

For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers are equal, “the smaller” should be read as “either”.)

For every column, the smaller of the following is B: the number of 0s contained in the column, and the number of 1s contained in the column.

Determine if these conditions can be satisfied by writing 0 or 1 in each of the squares. If the answer is yes, show one way to fill the squares so that the conditions are satisfied.

Constraints

1 \leq H,W \leq 1000

0 \leq A

2 \times A \leq W

0 \leq B

2 \times B \leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W A B

Output

If the conditions cannot be satisfied by writing 0 or 1 in each of the squares, print -1.

If the conditions can be satisfied, print one way to fill the squares so that the conditions are satisfied, in the following format:

s_{11}s_{12}\cdots s_{1W}
s_{21}s_{22}\cdots s_{2W}
\vdots
s_{H1}s_{H2}\cdots s_{HW}

Here s_{ij} is the digit written in the square at the i-th row from the top and the j-th column from the left in the grid.

If multiple solutions exist, printing any of them will be accepted.

Sample Input 1

3 3 1 1

Sample Output 1

100
010
001

Every row contains two 0s and one 1, so the first condition is satisfied.
Also, every column contains two 0s and one 1, so the second condition is satisfied.

Sample Input 2

1 5 2 0

Sample Output 2

01010


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

int main(){
    int N, K; cin >> N >> K;
    vector<int> P(N);
    rep(i,N) cin >> P[i];

    set<int> S;
    rep(i,K) S.insert(P[i]);

    int ans = 0;
    for(int i=K; i<N; i++){
        auto l = S.begin();
        auto r = S.end(); r--;
        //cout << *l << " " << *r << endl;
        S.erase(P[i-K]);
        if(*l < P[i-K] || *r > P[i]) ans++;
        S.insert(P[i]);

    }

    cout << ans << endl;
}

Score : 700 points

Problem Statement

Snuke has a permutation (P_0,P_1,\cdots,P_{N-1}) of (0,1,\cdots,N-1).

Now, he will perform the following operation exactly once:

Choose K consecutive elements in P and sort them in ascending order.

Find the number of permutations that can be produced as P after the operation.

Constraints

2 \leq N \leq 200000

2 \leq K \leq N

0 \leq P_i \leq N-1

P_0,P_1,\cdots,P_{N-1} are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_0 P_1 \cdots P_{N-1}

Output

Print the number of permutations that can be produced as P after the operation.

Sample Input 1

5 3
0 2 1 4 3

Sample Output 1

2

Two permutations can be produced as P after the operation: (0,1,2,4,3) and (0,2,1,3,4).

Sample Input 2

4 4
0 1 2 3

Sample Output 2

1

Sample Input 3

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

Sample Output 3

6


#include "bits/stdc++.h"

using namespace std;
#ifdef _DEBUG
#define _GLIBCXX_DEBUG
#include "dump.hpp"
#else
#define dump(...)
#endif

#define int long long
#define ll long long
#define DBG 1
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define rrep(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define loop(n) rep(loop, (0), (n))
#define all(c) begin(c), end(c)
const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)(1e9) + 7;
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
using pii = pair<int, int>;
// template<class T> ostream &operator<<(ostream &os,T &t){dump(t);return os;}
template <typename T, typename S>istream &operator>>(istream &is, pair<T, S> &p) { is >> p.first >> p.second; return is; }
//template <typename T, typename S>ostream &operator<<(ostream &os, pair<T, S> &p) {os << p.first << " " << p.second;return os;}

template <typename T> void printvv(const vector<vector<T>> &v) {
	cerr << endl;
	rep(i, 0, v.size()) rep(j, 0, v[i].size()) {
		if (typeid(v[i][j]).name() == typeid(INF).name() and v[i][j] == INF) {
			cerr << "INF";
		}
		else
			cerr << v[i][j];
		cerr << (j == v[i].size() - 1 ? '\n' : ' ');
	}
	cerr << endl;
}

#ifndef _DEBUG
#define printvv(...)
#endif
void YES(bool f) { cout << (f ? "YES" : "NO") << endl; }
void Yes(bool f) { cout << (f ? "Yes" : "No") << endl; }
template <class T, class U>bool chmin(T& a, U b) { if (a > b) { a = b; return true; }return false; }
template <class T, class U>bool chmax(T& a, U b) { if (a < b) { a = b; return true; }return false; }
template< typename Monoid >
struct SegmentTree {
	using F = function< Monoid(Monoid, Monoid) >;

	int sz;
	vector< Monoid > seg;

	const F f;
	const Monoid e;

	SegmentTree(int n, const F f, const Monoid &e) : f(f), e(e) {
		sz = 1;
		while (sz < n) sz <<= 1;
		seg.assign(2 * sz, e);
	}
	// k:=[0,sz)
	void set(int k, const Monoid &x) {
		seg[k + sz] = x;
	}

	void build() {
		for (int k = sz - 1; k > 0; k--) {
			seg[k] = f(seg[2 * k + 0], seg[2 * k + 1]);
		}
	}
	// k:=[0,sz)
	void update(int k, const Monoid &x) {
		k += sz;
		seg[k] = x;
		while (k >>= 1) {
			seg[k] = f(seg[2 * k + 0], seg[2 * k + 1]);
		}
	}
	// [a,b)
	Monoid query(int a, int b) {
		Monoid L = e, R = e;
		for (a += sz, b += sz; a < b; a >>= 1, b >>= 1) {
			if (a & 1) L = f(L, seg[a++]);
			if (b & 1) R = f(seg[--b], R);
		}
		return f(L, R);
	}
	// k:=[0,sz)
	const Monoid &operator[](const int &k) const {
		return seg[k + sz];
	}
	Monoid &operator[](const int &k) {
		return seg[k + sz];
	}
};

int guchoku(int N, int K, vector<int>P) {
	set<vector<int>>s;
	rep(i, 0, N - K + 1) {
		auto p = P;
		sort(p.begin() + i, p.begin() + i + K);
		if (s.count(p)) {
			cout << "! ";
		}
		s.insert(p);
		dump(p);

	}
	dump(s.size());
	return s.size();
}

void solve(int N, int K, vector<int>P) {
	SegmentTree<int>m(N, [](int a, int b) {return min(a, b); }, INF);
	SegmentTree<int>M(N, [](int a, int b) {return max(a, b); }, -INF);
	rep(i, 0, N) {
		m[i] = P[i];
		M[i] = P[i];
	}
	m.build();
	M.build();

	int ans = 1;
	rep(i, 1, N - K + 1) {
		bool f = P[i - 1] == m.query(i - 1, i - 1 + K);
		bool g = P[i + K - 1] == M.query(i, i + K);

		if (not (f and g))ans++;
	}

	deque<pii>q;
	int cnt = 0;
	rep(i, 0, N) {
		dump(q);
		while (q.size() and q.back().first > P[i]) {
			q.pop_back();
		}
		q.push_back(pii(P[i], i));
		cnt += q.size() == K;

		if (q.front().second <= i - K + 1)q.pop_front();

	}
	dump(cnt);
	cnt = max(0ll, cnt - 1);
	ans -= cnt;
	dump(ans);
	//assert(ans == guchoku(N, K, P));
	cout << ans << endl;
}

signed main(signed argc, char *argv[]) {
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout << fixed << setprecision(12);

	int N, K; cin >> N >> K;
	vector<int>P(N); rep(i, 0, N) { cin >> P[i]; }
	solve(N, K, P);

	return 0;
}


#include<cstdio>
#include<algorithm>
#define LL long long
using namespace std;
const int maxn=1000005,tt=998244353;
int qsm(LL w,int b){LL num=1;while(b){if (b&1) num=num*w%tt;w=w*w%tt;b>>=1;}return num;}
int NI[maxn],n,a[maxn],m,w[maxn],sum[maxn];
LL ans;
inline int _read(){
	int num=0;char ch=getchar();
	while(ch<'0'||ch>'9') ch=getchar();
	while(ch>='0'&&ch<='9') num=num*10+ch-48,ch=getchar();
	return num;
}
int main(){
	n=_read();for (int i=1;i<=n;i++) a[i]=_read(),m=max(m,a[i]),sum[a[i]]++;
	for (int i=1;i<=m;i++) NI[i]=qsm(i,tt-2);
	for (int i=1;i<=m;i++){
		w[i]=(w[i]+NI[i])%tt;
		for (int j=i*2;j<=m;j+=i) w[j]=(w[j]-w[i]+tt)%tt;
	}
	for (int i=1;i<=m;i++){
		LL num1=0,num2=0;
		for (int j=i;j<=m;j+=i) num1+=(LL)sum[j]*j%tt,num2+=sum[j]*j%tt*j%tt;
		num1%=tt;num2%=tt;
		ans+=w[i]*((num1*num1-num2+tt)%tt)%tt;
	}
	printf("%lld\n",ans%tt*NI[2]%tt);
	return 0;
}

Score : 700 points

Problem Statement

We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.

Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):

\sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)

Since the answer may be enormous, compute it modulo 998244353.

Constraints

1 \leq N \leq 200000

1 \leq A_i \leq 1000000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0\ A_1\ \cdots\ A_{N-1}

Output

Print the sum modulo 998244353.

Sample Input 1

3
2 4 6

Sample Output 1

22

\mathrm{lcm}(2,4)+\mathrm{lcm}(2,6)+\mathrm{lcm}(4,6)=4+6+12=22.

Sample Input 2

8
1 2 3 4 6 8 12 12

Sample Output 2

313

Sample Input 3

10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644

Sample Output 3

353891724


#include<iostream>
#include<bits/stdc++.h>
#include<string>
using namespace std;
int main()
{
  string s ;
  cin >> s ;

  if(s=="Sunny"){
  cout << "Cloudy" << endl ;
  }else if(s=="Cloudy"){
      cout << "Rainy" << endl ;
  }else{
      cout << "Sunny" << endl ;
  }

    return 0 ;
}

Score: 100 points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string S representing the weather in the town today. Predict the weather tomorrow.

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny


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

int main() {

    string s;
    cin>>s;
    int n;
    bool D=true;
    n=s.size();
    for(int i=0;i<n;i=i+2) {
        if(s[i]=='L')   D=false;
    }
    for(int i=1;i<n;i=i+2) {
        if(s[i]=='R')   D=false;
    }
    if(D==true) {
       printf("Yes");
    }
    else
    {
        printf("No");
    }

 return 0;
}

Score: 200 points

Problem Statement

Takahashi will do a tap dance. The dance is described by a string S where each character is L, R, U, or D. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character.

S is said to be easily playable if and only if it satisfies both of the following conditions:

Every character in an odd position (1-st, 3-rd, 5-th, \ldots) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th, \ldots) is L, U, or D.

Your task is to print Yes if S is easily playable, and No otherwise.

Constraints

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

Each character of S is L, R, U, or D.

Input

Input is given from Standard Input in the following format:

S

Output

Print Yes if S is easily playable, and No otherwise.

Sample Input 1

RUDLUDR

Sample Output 1

Yes

Every character in an odd position (1-st, 3-rd, 5-th, 7-th) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th) is L, U, or D.

Thus, S is easily playable.

Sample Input 2

DULL

Sample Output 2

No

The 3-rd character is not R, U, nor D, so S is not easily playable.

Sample Input 3

UUUUUUUUUUUUUUU

Sample Output 3

Yes

Sample Input 4

ULURU

Sample Output 4

No

Sample Input 5

RDULULDURURLRDULRLR

Sample Output 5

Yes


#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdio>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<ll> vl;
typedef vector<vector<ll>> vvl;
typedef vector<vector<vector<ll>>> vvvl;
#define REP(var, a, b) for (int var = (a); var < (b); var++)
#define rep(var, n) for (int var = 0; var < (n); ++var)
#define ALL(c) (c).begin(), (c).end()
#define rALL(c) (c).rbegin(), (c).rend()
ll MOD = 1000000007;
ll INF = 1LL << 60;

int main() {
  //
  string s;
  cin >> s;
  rep(i, s.size()) {
    char ch = s[i];
    if (i & 1) {
      // even
      if (ch != 'L' && ch != 'U' && ch != 'D') {
        cout << "No" << endl;
        return 0;
      }
    } else {
      // odd
      if (ch != 'R' && ch != 'U' && ch != 'D') {
        cout << "No" << endl;
        return 0;
      }
    }
  }
  cout << "Yes" << endl;
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using Graph = vector<vector<int>>;
#define ALL(x) (x).begin(), (x).end()
#define REP(i ,n) for(int i = 0; i < (int)(n); i++)
#define pb push_back
typedef vector<int>vint;
typedef vector<ll>vll;
template<typename T> istream &operator>>(istream &is, vector<T> &vec){ for (auto &v : vec) is >> v; return is; }
template<typename A,typename B>inline void chmin(A &a,B b){if(a>b)a=b;}
template<typename A,typename B>inline void chmax(A &a,B b){if(a<b)a=b;}

int main()
{
  int N,K,Q;
  cin >> N >> K >> Q;
  vint ans(N,K-Q);
  REP(i,Q){
    int a;
    cin >> a;
    a--;
    ans[a]++;
  }

  for(auto a : ans){
    if(0 < a){
      cout << "Yes" << endl;
    }else{
      cout << "No" << endl;
    }
  }

}

Score: 300 points

Problem Statement

Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.

A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.

When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.

At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.

In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 10^9

1 \leq Q \leq 10^5

1 \leq A_i \leq N\ (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N K Q
A_1
A_2
.
.
.
A_Q

Output

Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.

Sample Input 1

6 3 4
3
1
3
2

Sample Output 1

No
No
Yes
No
No
No

In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).

Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).

Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).

Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).

Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).

Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.

Sample Input 2

6 5 4
3
1
3
2

Sample Output 2

Yes
Yes
Yes
Yes
Yes
Yes

Sample Input 3

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

Sample Output 3

No
No
No
No
Yes
No
No
No
Yes
No


#include <bits/stdc++.h>
#define REP(i,n) for(ll i=0;i<(ll)(n);i++)
#define REPD(i,n) for(ll i=n-1;i>=0;i--)
#define FOR(i,a,b) for(ll i=a;i<=(ll)(b);i++)
#define FORD(i,a,b) for(ll i=a;i>=(ll)(b);i--)
#define ALL(x) (x).begin(),(x).end()
#define SIZE(x) ((ll)(x).size())
#define MAX(x) *max_element(ALL(x))
#define MIN(x) *min_element(ALL(x))
#define INF 1000000000
using namespace std;
typedef long long ll;

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

    ans = pow(N, 3);
    cout << ans << endl;
}

Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.


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

int main() {
  int N;
  cin >> N;
  cout << N * N * N <<endl;
}


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    int n, ans = 0;
    cin >> n;
    vector<int> b(n+1);
    b[0] = b[n] = 1e9;
    for(int i = 1; i < n; i++){
        cin >> b[i];
        ans += min(b[i-1], b[i]);
    }
    cout << ans + b[n-1] << endl;
    return 0;
}

Score : 300 points

Problem Statement

There is an integer sequence A of length N whose values are unknown.

Given is an integer sequence B of length N-1 which is known to satisfy the following:

B_i \geq \max(A_i, A_{i+1})

Find the maximum possible sum of the elements of A.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq B_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
B_1 B_2 ... B_{N-1}

Output

Print the maximum possible sum of the elements of A.

Sample Input 1

3
2 5

Sample Output 1

9

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53


#include <iostream>
#include <vector>
#define rep(i,n) for(int i=0; i<n; i++)
typedef long long ll;

using namespace std;

int main(){
  int N;
  cin >> N;
  vector<ll> B(N);
  ll out=0;
  rep(i,N){
    cin >> B[i];
  }
  for(int i=1;i<N-1;i++){
    out += min(B[i-1], B[i]);
  }
  out += (B[0] + B[N-2]);

  cout << out << endl;
  return 0;
}


#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char a[100000];
    int n, k, s=0;
    cin>>n>>k;
    cin.ignore();
    cin.getline(a, 100000);
    for(int i=0; i<n-1; i++)
    {
        if(a[i]==a[i+1])
        {
            s++;
        }
    }
    s=min(n-1,s+2*k);
    cout<<s;
    return 0;
}

Score : 400 points

Problem Statement

There are N people standing in a queue from west to east.

Given is a string S of length N representing the directions of the people.
The i-th person from the west is facing west if the i-th character of S is L, and east if that character of S is R.

A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.

You can perform the following operation any number of times between 0 and K (inclusive):

Operation: Choose integers l and r such that 1 \leq l \leq r \leq N, and rotate by 180 degrees the part of the queue: the l-th, (l+1)-th, ..., r-th persons. That is, for each i = 0, 1, ..., r-l, the (l + i)-th person from the west will stand the (r - i)-th from the west after the operation, facing east if he/she is facing west now, and vice versa.

What is the maximum possible number of happy people you can have?

Constraints

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

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

|S| = N

Each character of S is L or R.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of happy people after at most K operations.

Sample Input 1

6 1
LRLRRL

Sample Output 1

3

If we choose (l, r) = (2, 5), we have LLLRLL, where the 2-nd, 3-rd, and 6-th persons from the west are happy.

Sample Input 2

13 3
LRRLRLRRLRLLR

Sample Output 2

9

Sample Input 3

10 1
LLLLLRRRRR

Sample Output 3

9

Sample Input 4

9 2
RRRLRLRLL

Sample Output 4

7


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

// 同じ方向を向いて連続するx人のうち、x-1人が幸福である
// パターンA：端を含まない連続するx人を操作すると、幸福な人は2人増える（x-1 -> x+1）
// パターンB：端を含む連続するx人を操作すると、幸福な人は1人増える（x-1 -> x）
// ⇒ 幸福な人数を最大にしたいので、まずAの場合を可能な限り行い、次にBの場合を行う
int main() {
  size_t N = 0;  // 人数
  size_t K = 0;  // 操作回数の上限
  std::cin >> N >> K;

  std::vector<char> S(N);
  for (size_t i = 0; i < N; ++i) {
    std::cin >> S[i];
  }

  // 初期状態を調べる
  size_t pair_count = 0;  // LとRの連続部分のペアの個数
  size_t happiness = 0;  // 幸福度
  auto head_iter = S.cbegin();  // 連続部分の先頭のイテレータ
  for (auto iter = ++S.cbegin(); iter != S.cend(); ++iter) {
    if (*iter != *head_iter) {
      if (*head_iter != S.front()) pair_count++;
      happiness += (iter - head_iter) - 1;
      head_iter = iter;
    }
  }
  if (*head_iter != S.front()) pair_count++;
  happiness += (S.cend() - head_iter) - 1;

  if (S.front() == S.back()) {
    // 端を含む連続部分が同じ方向を向いている場合、
    // すべての連続部分をその向きに揃えるように可能な限り操作を行う
    const size_t a = 2 * std::min(pair_count, K);  // パターンA
    happiness += a;
  } else {
    // 端を含む連続部分が異なる方向を向いている場合、
    // どちらかの向きに揃えるように可能な限り操作を行う
    const size_t n = pair_count - 1;
    const size_t a = 2 * std::min(n, K);  // パターンA
    const size_t b = n < K ? 1 : 0;  // パターンB（操作回数が余る場合のみ）
    happiness += a + b;
  }

  // 結果発表
  std::cout << happiness;

  return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define ll long long;

const int N=1e6+5;

vector<int> v;

int n,ans,tc,q,m,a[N],k;

char s1[N],s2[N];

int main(){
    scanf("%s%s",s1,s2);
    for(int i=0;s1[i];i++)
        ans+=s1[i]==s2[i];
    printf("%d\n",ans);
}

Score : 100 points

Problem Statement

You will be given a string S of length 3 representing the weather forecast for three days in the past.

The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

You will also be given a string T of length 3 representing the actual weather on those three days.

The i-th character (1 \leq i \leq 3) of S represents the actual weather on the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

Print the number of days for which the forecast was correct.

Constraints

S and T are strings of length 3 each.

S and T consist of S, C, and R.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the number of days for which the forecast was correct.

Sample Input 1

CSS
CSR

Sample Output 1

2

For the first day, it was forecast to be cloudy, and it was indeed cloudy.

For the second day, it was forecast to be sunny, and it was indeed sunny.

For the third day, it was forecast to be sunny, but it was rainy.

Thus, the forecast was correct for two days in this case.

Sample Input 2

SSR
SSR

Sample Output 2

3

Sample Input 3

RRR
SSS

Sample Output 3

0


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

int main() {

  string A, B;
  cin >> A >> B;
  int out = 0;
  for(int i = 0; i < 3; i++){
    if(A.at(i) == B.at(i)){
      out++;
    }
  }
  cout << out;
}


#include <bits/stdc++.h>
using namespace std;
int main(){
    int a,b;
    cin >>a>>b;
    int count=1;
    int ans=0;
    while(count < b){
        count += a-1;
        ans++;
    }
    cout <<ans<<endl;
}

Score : 200 points

Problem Statement

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.

One power strip with A sockets can extend one empty socket into A empty sockets.

Find the minimum number of power strips required.

Constraints

All values in input are integers.

2 \leq A \leq 20

1 \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of power strips required.

Sample Input 1

4 10

Sample Output 1

3

3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.

Sample Input 2

8 9

Sample Output 2

2

2 power strips, each with 8 sockets, extend the socket into 15 empty sockets.

Sample Input 3

8 8

Sample Output 3

1


#include<iostream>
using namespace std;
int main()
{
	int a, b;
	cin >> a >> b;
	if (b %a==0)
		cout << b/a;
	else
		cout << (b / a + 1);
	return 0;
}


// 2019/09/01
// AtCoder Beginner Contest 139 - D

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

int main(){
    // Input
    long long n;
    cin >> n;
    long long ans;

    // Calc Sum
    if(n % 2 == 0){
        ans = (n + 1) * (n / 2) - n;
    } else {
        ans = (n + 1) * (floor(n / 2)) + floor(n / 2) - n;
        ans += 1;
    }

    // Output
    cout << ans << endl;
}

Score : 400 points

Problem Statement

For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}.

Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.

Find the maximum possible value of M_1 + M_2 + \cdots + M_N.

Constraints

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

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible value of M_1 + M_2 + \cdots + M_N.

Sample Input 1

2

Sample Output 1

1

When the permutation \{P_1, P_2\} = \{2, 1\} is chosen, M_1 + M_2 = 1 + 0 = 1.

Sample Input 2

13

Sample Output 2

78

Sample Input 3

1

Sample Output 3

0


#include<bits/stdc++.h>
#define ll long long int
using namespace std;
/*
ll npr(ll n, ll r, ll mod){
    ll val = 1;
    for(ll i=n; i<=(n-r+1); i++){
        ll k = i%mod;
        val = val*k;
        val = val%mod;
    }
return val;
}
*/
int main(){
    ll n;
    cin>>n;
    ll sum = 0;
    /*for(ll i=1; i<=n; i++){
        sum = sum + npr(n , i,  i);
        cout<<sum<<endl;
    }*/
    ll k = n;
    if(n%2 == 0){
        k = n/2;
        sum = (k)*(n-1);
    }
    else{
        k = (n-1)/2;
        sum = (k)*(n);
    }
    cout<<sum;

return 0;
}


#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <complex>
#include <utility>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
#include <bitset>
#include <ctime>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <cassert>
#include <cstddef>
#include <iomanip>
#include <numeric>
#include <tuple>
#include <sstream>
#include <fstream>
#include <functional>

using namespace std;
#define REP(i, n) for (int (i) = 0; (i) < (n); (i)++)
#define FOR(i, a, b) for (int (i) = (a); (i) < (b); (i)++)
#define RREP(i, a) for(int (i) = (a) - 1; (i) >= 0; (i)--)
#define FORR(i, a, b) for(int (i) = (a) - 1; (i) >= (b); (i)--)
#define DEBUG(C) cerr << #C << " = " << C << endl;
using LL = long long;
using VI = vector<int>;
using VVI = vector<VI>;
using VL = vector<LL>;
using VVL = vector<VL>;
using VD = vector<double>;
using VVD = vector<VD>;
using PII = pair<int, int>;
using PDD = pair<double, double>;
using PLL = pair<LL, LL>;
using VPII = vector<PII>;
template<typename T> using VT = vector<T>;
#define ALL(a) begin((a)), end((a))
#define RALL(a) rbegin((a)), rend((a))
#define SORT(a) sort(ALL((a)))
#define RSORT(a) sort(RALL((a)))
#define REVERSE(a) reverse(ALL((a)))
#define MP make_pair
#define FORE(a, b) for (auto &&a : (b))
#define EB emplace_back
#define GREATER(T) T, VT<T> greater<T>
template<typename T> inline bool chmax(T &a, T b){if (a < b){a = b;return true;}return false;}
template<typename T> inline bool chmin(T &a, T b){if (a > b){a = b;return true;}return false;}

const int INF = 1e9;
const int MOD = INF + 7;
const LL LLINF = 1e18;

LL N;

int main(void) {
    cin >> N;

    cout << N * (N - 1) / 2 << endl;
}


#pragma once

#include <bits/stdc++.h>

#define M_PI       3.14159265358979323846   // pi

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> VI;
typedef pair<ll, ll> P;
typedef tuple<ll, ll, ll> t3;

#define rep(a,n) for(int a = 0;a < n;a++)
#define repi(a,b,n) for(int a = b;a < n;a++)

const ull mod = 1000000007;
int INF = 1e8;

int dfs(P start, map<P, vector<P>>& m, set<P>& visit) {
	if (visit.count(start)) return INF;
	visit.insert(start);
	P current = start;
	int dist = 0;
	for (auto e : m[current]) {
		dist = max(dist, dfs(e, m, visit));
	}
	visit.erase(start);
	return min(INF, dist + 1);
}

int main(void)
{
	ll n;
	cin >> n;
	map<P, vector<P>> input;
	set<P> s;
	rep(i, n) {
		vector<P> ps(n-1);
		rep(j, n - 1) {
			int t;
			cin >> t;
			t--;
			auto p = make_pair(min(t, i), max(t, i));
			ps[j] = p;
		}
		rep(j, n - 2) {
			input[ps[j]].push_back(ps[j + 1]);
		}
		s.insert(ps[0]);
	}
	int d = 0;
	for (auto e : s) {
		set<P> ss;
		d = max(d, dfs(e, input, ss));
	}
	if (d == INF) {
		cout << -1 << endl;
		return 0;
	}
	cout << d << endl;
	return 0;
}

Score : 500 points

Problem Statement

N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.

The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

Constraints

3 \leq N \leq 1000

1 \leq A_{i, j} \leq N

A_{i, j} \neq i

A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

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

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day 1: Player 1 vs Player 2, Player 3 vs Player 4

Day 2: Player 1 vs Player 3

Day 3: Player 1 vs Player 4, Player 2 vs Player 3

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.


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

typedef long long ll;

ll mod = 1000000007;

int main(){
    //ios_base::sync_with_stdio(0);
   // cin.tie(0);
    //cout.tie(0);
    int n; cin >> n;
    /*vector<pair<int, int> > v;
    for(int i=0; i<t; i++){
        cin >> a >> b;

    }*/
    int l;
    unordered_map<int, int> available;
    for(int i=0; i<n; i++) available[i] = 1;
    queue<int>v[n];
    for(int i=0; i<n; i++){
        for(int j=0; j<n-1; j++){
            cin >> l;
            --l;
            v[i].push(l);
        }
    }
    int day = 0;
    bool flag = true;
    unordered_map<int, int> played;
    vector<int> vis;
    int cnt = 10000007;
    while(flag && available.size()>0)
    {
        day++;
        //cout << "Day : " << day << endl;
        //cout << "Map elements available :";
        //for(auto idx : available) cout << idx.first << " ";
        //cout << endl;
        flag = false;
        for(auto it = available.begin(); it!=available.end(); ++it)
        {
            cnt--;
            auto i = it->first;
            //cout << "Inside the for loop : auto it " << i << endl;
            if(!played[i])
            {
                int top = v[i].front();
                //cout << top << endl;
                if(!v[top].empty() && !played[top] && v[top].front() == i)
                {
                    played[i] = played[top] = 1;
                    //cout << i << " " << top << endl;
                    v[i].pop();
                    v[top].pop();
                    if(v[i].empty())
                        vis.push_back(i);
                    if(v[top].empty())
                        vis.push_back(top);
                    flag = true;
                }
            }
        }
        for(auto x: vis){
                available.erase(x);
        }
        vis.clear();
        //cout << "Map elements available :";
        //for(auto idx : available) cout << idx.first << " ";
        played.clear();
    }
    if(cnt == 0) cout << (n * (n-1))/2 << endl;
    else if(flag) cout << day << endl;
    else cout << -1 << endl;
}


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

typedef long long ll;

ll mod = 1000000007;

int main(){
    //ios_base::sync_with_stdio(0);
   // cin.tie(0);
    //cout.tie(0);
    int n; cin >> n;
    /*vector<pair<int, int> > v;
    for(int i=0; i<t; i++){
        cin >> a >> b;

    }*/
    int l;
    unordered_map<int, int> available;
    for(int i=0; i<n; i++) available[i] = 1;
    queue<int>v[n];
    for(int i=0; i<n; i++){
        for(int j=0; j<n-1; j++){
            cin >> l;
            --l;
            v[i].push(l);
        }
    }
    int day = 0;
    bool flag = true;
    unordered_map<int, int> played;
    vector<int> vis;
    int cnt = 10000007;
    while(flag && available.size()>0 && cnt > 0)
    {
        day++;
        //cout << "Day : " << day << endl;
        //cout << "Map elements available :";
        //for(auto idx : available) cout << idx.first << " ";
        //cout << endl;
        flag = false;
        for(auto it = available.begin(); it!=available.end(); ++it)
        {
            cnt--;
            auto i = it->first;
            //cout << "Inside the for loop : auto it " << i << endl;
            if(!played[i])
            {
                int top = v[i].front();
                //cout << top << endl;
                if(!v[top].empty() && !played[top] && v[top].front() == i)
                {
                    played[i] = played[top] = 1;
                    //cout << i << " " << top << endl;
                    v[i].pop();
                    v[top].pop();
                    if(v[i].empty())
                        vis.push_back(i);
                    if(v[top].empty())
                        vis.push_back(top);
                    flag = true;
                }
            }
        }
        for(auto x: vis){
                available.erase(x);
        }
        vis.clear();
        //cout << "Map elements available :";
        //for(auto idx : available) cout << idx.first << " ";
        played.clear();
    }
    if(cnt == 0) cout << -1 << endl;
    else if(flag) cout << day << endl;
    else cout << -1 << endl;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define F first
#define S second
#define pii pair<int, int>
#define eb emplace_back
#define all(v) v.begin(), v.end()
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rep3(i, l, n) for (int i = l; i < (n); ++i)
#define sz(v) (int)v.size()
#define inf (int)(1e9+7)
#define abs(x) (x >= 0 ? x : -(x))
#define ceil(a, b) a / b + !!(a % b)
template<typename T1, typename T2> inline void chmin(T1 &a, T2 b) { if (a > b) a = b; }
template<typename T1, typename T2> inline void chmax(T1 &a, T2 b) { if (a < b) a = b; }
ll pow(ll a, int b) { return b ? pow(a * a, b / 2) * (b % 2 ? a : 1) : 1; }
template<typename T> T gcd(T a, T b) { if (b == 0) return a; return gcd(b, a % b); }

double atan(int a, int b) {
    if (a == 0) return (b > 0 ? M_PI / 2 : -M_PI / 2);
    if (b == 0 && a < 0) return M_PI;
    if (a < 0 && b < 0) return atan((double)b / a) - M_PI;
    if (a < 0 && b > 0) return atan((double)b / a) + M_PI;
    return atan((double)b / a);
}

bool comp(pii a, pii b) {
    return atan(a.F, a.S) < atan(b.F, b.S);
}

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

    vector<pii> v;
    rep(i, n) {
        int x, y;
        cin >> x >> y;
        if (x == 0 && y == 0) continue;
        v.eb(pii(x, y));
    }

    double ans = 0;

    sort(all(v), comp);

    // cout << '\n'; rep(i, sz(v)) cout << v[i].F << " " << v[i].S << " " << atan(v[i].F, v[i].S) << '\n';

    rep(i, sz(v)) rep3(j, i, sz(v)) {
        int x = 0, y = 0;
        rep3(k, i, j + 1) {
            x += v[k].F;
            y += v[k].S;
        }
        chmax(ans, sqrt((double)x * x + (double)y * y));
    }

    cout << fixed << setprecision(11) << ans << '\n';
}

Score: 600 points

Problem Statement

E869120 is initially standing at the origin (0, 0) in a two-dimensional plane.

He has N engines, which can be used as follows:

When E869120 uses the i-th engine, his X- and Y-coordinate change by x_i and y_i, respectively. In other words, if E869120 uses the i-th engine from coordinates (X, Y), he will move to the coordinates (X + x_i, Y + y_i).

E869120 can use these engines in any order, but each engine can be used at most once. He may also choose not to use some of the engines.

He wants to go as far as possible from the origin.
Let (X, Y) be his final coordinates. Find the maximum possible value of \sqrt{X^2 + Y^2}, the distance from the origin.

Constraints

1 \leq N \leq 100

-1 \ 000 \ 000 \leq x_i \leq 1 \ 000 \ 000

-1 \ 000 \ 000 \leq y_i \leq 1 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
: :
x_N y_N

Output

Print the maximum possible final distance from the origin, as a real value.
Your output is considered correct when the relative or absolute error from the true answer is at most 10^{-10}.

Sample Input 1

3
0 10
5 -5
-5 -5

Sample Output 1

10.000000000000000000000000000000000000000000000000

The final distance from the origin can be 10 if we use the engines in one of the following three ways:

Use Engine 1 to move to (0, 10).

Use Engine 2 to move to (5, -5), and then use Engine 3 to move to (0, -10).

Use Engine 3 to move to (-5, -5), and then use Engine 2 to move to (0, -10).

The distance cannot be greater than 10, so the maximum possible distance is 10.

Sample Input 2

5
1 1
1 0
0 1
-1 0
0 -1

Sample Output 2

2.828427124746190097603377448419396157139343750753

The maximum possible final distance is 2 \sqrt{2} = 2.82842....
One of the ways to achieve it is:

Use Engine 1 to move to (1, 1), and then use Engine 2 to move to (2, 1), and finally use Engine 3 to move to (2, 2).

Sample Input 3

5
1 1
2 2
3 3
4 4
5 5

Sample Output 3

21.213203435596425732025330863145471178545078130654

If we use all the engines in the order 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5, we will end up at (15, 15), with the distance 15 \sqrt{2} = 21.2132... from the origin.

Sample Input 4

3
0 0
0 1
1 0

Sample Output 4

1.414213562373095048801688724209698078569671875376

There can be useless engines with (x_i, y_i) = (0, 0).

Sample Input 5

1
90447 91000

Sample Output 5

128303.000000000000000000000000000000000000000000000000

Note that there can be only one engine.

Sample Input 6

2
96000 -72000
-72000 54000

Sample Output 6

120000.000000000000000000000000000000000000000000000000

There can be only two engines, too.

Sample Input 7

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

Sample Output 7

148.660687473185055226120082139313966514489855137208


#pragma once
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

typedef long long ll;
#define all(x) (x).begin(), (x).end()  // sortなどの引数を省略
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)

#ifdef _MSC_FULL_VER  //デバッグ出力
#define dout cout
#define debug() if (true)
#define check(x) std::cout << "★" << #x << "の値:" << (x) << endl
#define pass(x) std::cout << "☆" << x << endl
#else
#define dout \
  if (false) cout
#define debug() if (false)
#define check(x) \
  if (false) cout << "★" << #x << "の値:" << (x) << endl
#define pass(x) \
  if (false) cout << "☆" << x << endl
#endif
using namespace std;
int main() {
  int N;
  cin >> N;
  vector<double> list(N+1,9999
  );
  for (int i = 0; i < N; i++) {
    cin >> list[i];
  }
  sort(all(list));
  dout << "====listの内容====\n";
  for (int i = 0; i < N; i++) dout << list[i] << endl;
  dout << "====ここまで====\n";
  rep(i, N-1) {
    dout << i << "/" << list[i] << "/" << list[i+1] << endl;
    list[i + 1] = (list[i] + list[i+1])/2;
  }
  cout << list[N-1];
  return 0;
}
/*
//よく使うやつ
int N;
cin >> N;
vector<int> list(N);
for (int i = 0; i < N; i++) {
  cin >> list[i];
}
// for文
for (int i = 0; i < N; i++) {
}
//配列
vector<int> vec;
vec.at(i)
vector<vector<int>> vec(10, vector<int>(10));
sort(all(vec));
sort(all(vec), greater<int>());
    //配列の内容表示
dout << "====vecの内容====\n";
for (int i = 0; i < N; i++) dout << vec[i] << endl;
dout << "====ここまで====\n";
*/

Score : 300 points

Problem Statement

You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i.

When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where x and y are the values of the ingredients consumed, and you can put this ingredient again in the pot.

After you compose ingredients in this way N-1 times, you will end up with one ingredient. Find the maximum possible value of this ingredient.

Constraints

2 \leq N \leq 50

1 \leq v_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
v_1 v_2 \ldots v_N

Output

Print a decimal number (or an integer) representing the maximum possible value of the last ingredient remaining.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
3 4

Sample Output 1

3.5

If you start with two ingredients, the only choice is to put both of them in the pot. The value of the ingredient resulting from the ingredients of values 3 and 4 is (3 + 4) / 2 = 3.5.

Printing 3.50001, 3.49999, and so on will also be accepted.

Sample Input 2

3
500 300 200

Sample Output 2

375

You start with three ingredients this time, and you can choose what to use in the first composition. There are three possible choices:

Use the ingredients of values 500 and 300 to produce an ingredient of value (500 + 300) / 2 = 400. The next composition will use this ingredient and the ingredient of value 200, resulting in an ingredient of value (400 + 200) / 2 = 300.

Use the ingredients of values 500 and 200 to produce an ingredient of value (500 + 200) / 2 = 350. The next composition will use this ingredient and the ingredient of value 300, resulting in an ingredient of value (350 + 300) / 2 = 325.

Use the ingredients of values 300 and 200 to produce an ingredient of value (300 + 200) / 2 = 250. The next composition will use this ingredient and the ingredient of value 500, resulting in an ingredient of value (250 + 500) / 2 = 375.

Thus, the maximum possible value of the last ingredient remaining is 375.

Printing 375.0 and so on will also be accepted.

Sample Input 3

5
138 138 138 138 138

Sample Output 3

138


#include <iostream>
#include <list>
#include <string>
#include <iomanip>
using namespace std;

void sort(int num[50], int n){
    int temp;
    for(int i=1; i<n; i++){
        for(int j=0; j<n-i; j++){
            if(num[j] > num[j+1]){
                temp = num[j+1];
                num[j+1] = num[j];
                num[j] = temp;
            }
        }
    }
}

int main()
{
    int N;
    long int bite;
    int values[50];
    int bi[50];
    double sum;
    bite = 1;
    cin >> N;
    for(int i=0; i<N; i++){
        cin >> values[i];
        bi[i] = bite;
        if(i> 0){
            bite*=2;
        }
    }
    sort(values, N);
    sum = 0;
    for(int i=0; i<N; i++){
        sum += values[i]*bi[i];
    }

    cout << sum/(bi[N-1]*2) << endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
typedef long long ll;

int main(void){
  int n,m,i,j,l[27][100005]={};
  string s,t;

  cin >> s >> t;
  n=s.size();
  m=t.size();

  for (i=0;i<n;i++) l[s[i]-'a'][i]++;
  for (i=0;i<26;i++) for (j=1;j<=n;j++){
    l[i][j]+=l[i][j-1];
  }

  for (i=0;i<m;i++){
    if (l[t[i]-'a'][n]==0){
      cout << -1 << endl;
      return 0;
    }
  }

  int p=0,lk,rou=0;
  int *sp;
  for (i=0;i<m;i++){
    lk=t[i]-'a';
    sp=lower_bound(l[lk]+p,l[lk]+n,l[lk][p]+1);
    if (p>=n || sp==l[lk]+n){
      p=0;
      sp=lower_bound(l[lk],l[lk]+n,1);
      rou++;
    }
    p=sp-l[lk];
  }

  cout << n*rou+p+1 << endl;

  return 0;
}

Score : 500 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.

Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').

Notes

A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net, c, and contest.

Constraints

1 \leq |s| \leq 10^5

1 \leq |t| \leq 10^5

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print -1.

Sample Input 1

contest
son

Sample Output 1

10

t = son is a subsequence of the string contestcon (the first 10 characters in s' = contestcontestcontest...), so i = 10 satisfies the condition.

On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s'), so i = 9 does not satisfy the condition.

Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition is 10.

Sample Input 2

contest
programming

Sample Output 2

-1

t = programming is not a substring of s' = contestcontestcontest.... Thus, there is no integer i satisfying the condition.

Sample Input 3

contest
sentence

Sample Output 3

33

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


#include <cstdio>
#include <iostream>
#include <cassert>
#include <string>
#include <algorithm>
#include <cstring>
#include <utility>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <unordered_map>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<LL, LL> pll;
const int MAXN = 123456;
char s[MAXN], t[MAXN];
vector<int> idx[87];

int main() {
    scanf("%s", s + 1);
    scanf("%s", t + 1);
    int ns = strlen(s + 1);
    int nt = strlen(t + 1);
    for (int i = 1; i <= ns; i++) {
        int cur = s[i] - 'a';
        idx[cur].push_back(i);
    }
    int ans = 0, cur_idx = 0;
    for (int i = 1; i <= nt; i++) {
        int cur = t[i] - 'a';
        if (idx[cur].empty()) return !printf("-1\n");
        int tmp = upper_bound(idx[cur].begin(), idx[cur].end(), cur_idx) - idx[cur].begin();
        //printf("i = %d tmp = %d\n", i, tmp);
        if (tmp == (int)idx[cur].size()) {
           ans += (ns - cur_idx);
           cur_idx = idx[cur].front();
           ans += cur_idx;
        } else {
           ans += (idx[cur][tmp] - cur_idx);
           cur_idx = idx[cur][tmp];
        }
    }
    printf("%d\n", ans);
    return 0;
}


#include<bits/stdc++.h>
#define int long long
#define P pair<int,int>
#define PP pair<P,int>
#define F first
#define S second
#define f(i,n) for(int i=0;i<(n);i++)
#define INF LLONG_MAX/3
#define eps LDBL_EPSILON
#define mod (int)(1000000007)
#define pie 3.141592653589793238462643383279
#define Bpri priority_queue
#define Spri priority_queue<P,vector<P>,greater<P>>
#define all(x) (x).begin(),(x).end()
using namespace std;
vector<int> v[26];
int gcd(int a,int b){
	if(b==0)return a;
	return gcd(b,a%b);
}
int lcm(int a,int b){
	return a*b/gcd(a,b);
}
signed main(){
	string s,t;
	cin>>s>>t;
	f(i,s.size()){
		v[s[i]-'a'].push_back(i);
	}
	int z=0,ans=0,vz;
	f(i,t.size()){
		vz=(int)(lower_bound(v[t[i]-'a'].begin(),v[t[i]-'a'].end(),z)-v[t[i]-'a'].begin());
		if(vz==(int)v[t[i]-'a'].size())ans++;
		if(v[t[i]-'a'].size()==0){
			puts("-1");
			return 0;
		}
		z=v[t[i]-'a'][vz%(int)(v[t[i]-'a'].size())];
	}
	cout<<ans*(int)s.size()+z+1<<endl;
}


#include<bits/stdc++.h>
#define mid ((l+r)/2)
using namespace std;
int n,ans,a[222222],b[222222],t[888888];
void build(int l,int r,int p){
	if(l==r){scanf("%d",&b[l]),t[p]=b[l];return;}
	build(l,mid,p*2),build(mid+1,r,p*2+1),t[p]=max(t[p*2],t[p*2+1]);
}
void update(int l,int r,int p,int c,int v){
	if(l==r){t[p]=v;return;}
	mid>=c?update(l,mid,p*2,c,v):update(mid+1,r,p*2+1,c,v);
	t[p]=max(t[p*2],t[p*2+1]);
}
int query(int l,int r,int p){
	if(l==r)return l;
	return t[p]==t[p*2]?query(l,mid,p*2):query(mid+1,r,p*2+1);
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]);
	build(1,n,1),b[0]=b[n],b[n+1]=b[1];
	for(int tmp=n;tmp;){
		int p=query(1,n,1),d=b[p]-a[p],k=b[p+1]+b[p-1];
		if(!d){tmp--,update(1,n,1,p,0);continue;}
		if(d<k){printf("-1");return 0;}
		ans+=d/k,b[p]=a[p]+d%k,b[0]=b[n],b[n+1]=b[1],update(1,n,1,p,a[p]==b[p]?0:b[p]);
		if(b[p]==a[p])tmp--;
	}
	printf("%d",ans);
}

Score : 800 points

Problem Statement

There are N positive integers arranged in a circle.

Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For this objective, he will repeatedly perform the following operation:

Choose an integer i such that 1 \leq i \leq N.

Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. Replace the i-th number with a+b+c.

Here the 0-th number is the N-th number, and the (N+1)-th number is the 1-st number.

Determine if Takahashi can achieve his objective.
If the answer is yes, find the minimum number of operations required.

Constraints

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

1 \leq A_i, 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 A_2 ... A_N
B_1 B_2 ... B_N

Output

Print the minimum number of operations required, or -1 if the objective cannot be achieved.

Sample Input 1

3
1 1 1
13 5 7

Sample Output 1

4

Takahashi can achieve his objective by, for example, performing the following operations:

Replace the second number with 3.

Replace the second number with 5.

Replace the third number with 7.

Replace the first number with 13.

Sample Input 2

4
1 2 3 4
2 3 4 5

Sample Output 2

-1

Sample Input 3

5
5 6 5 2 1
9817 1108 6890 4343 8704

Sample Output 3

25


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
typedef long long LL;

vector <LL> v[405][405];
LL n,m;
LL vis[405],p[405];
LL e[405][405],ans[405][405],a[405][405];

LL dfs(LL u){
	if(!u) return 1;
	for(LL i = 1;i <= n + n;i ++){
		if(e[u][i] <= 0) continue;
		if(vis[i]) continue;
		vis[i] = 1;
		if(dfs(p[i])){
			p[u] = i; p[i] = u;
			return 1;
		}
	}
	return 0;
}

void get_match(LL x){
	memset(p,0,sizeof(p));
	for(LL i = 1;i <= n;i ++){
		memset(vis,0,sizeof(vis));
		dfs(i);
	}
	for(LL i = 1;i <= n;i ++){
		e[i][p[i]] --; e[p[i]][i] --;
		ans[x][i] = v[i][p[i]][v[i][p[i]].size() - 1];
		v[i][p[i]].pop_back();
	}
}

int main(){
	ios::sync_with_stdio(false);
	cin >> n >> m;
	for(LL i = 1;i <= n;i ++){
		for(LL j = 1;j <= m;j ++){
			cin >> a[i][j];
			e[i][(a[i][j] - 1) / m + 1 + n] ++;
			e[(a[i][j] - 1) / m + 1 + n][i] ++;
			v[i][(a[i][j] - 1) / m + 1 + n].push_back(a[i][j]);
		}
	}
	for(LL i = 1;i <= m;i ++) get_match(i);
	for(LL i = 1;i <= n;i ++){
		for(LL j = 1;j <= m;j ++){
			cout << ans[j][i] << (j == m ? '\n' : ' ');
		}
	}
	for(LL i = 1;i <= m;i ++){
		for(LL j = 1;j <= n;j ++){
			for(LL k = 1;k <= n;k ++){
				if(ans[i][j] < ans[i][k]) swap(ans[i][j],ans[i][k]);
			}
		}
	}
	for(LL i = 1;i <= n;i ++){
		for(LL j = 1;j <= m;j ++){
			cout << ans[j][i] << (j == m ? '\n' : ' ');
		}
	}
	return 0;
}

Score : 1100 points

Problem Statement

We have a grid with N rows and M columns of squares.
Each integer from 1 to NM is written in this grid once.
The number written in the square at the i-th row from the top and the j-th column from the left is A_{ij}.

You need to rearrange these numbers as follows:

First, for each of the N rows, rearrange the numbers written in it as you like.

Second, for each of the M columns, rearrange the numbers written in it as you like.

Finally, for each of the N rows, rearrange the numbers written in it as you like.

After rearranging the numbers, you want the number written in the square at the i-th row from the top and the j-th column from the left to be M\times (i-1)+j.
Construct one such way to rearrange the numbers. The constraints guarantee that it is always possible to achieve the objective.

Constraints

1 \leq N,M \leq 100

1 \leq A_{ij} \leq NM

A_{ij} are distinct.

Input

Input is given from Standard Input in the following format:

N M
A_{11} A_{12} ... A_{1M}
:
A_{N1} A_{N2} ... A_{NM}

Output

Print one way to rearrange the numbers in the following format:

B_{11} B_{12} ... B_{1M}
:
B_{N1} B_{N2} ... B_{NM}
C_{11} C_{12} ... C_{1M}
:
C_{N1} C_{N2} ... C_{NM}

Here B_{ij} is the number written in the square at the i-th row from the top and the j-th column from the left after Step 1, and C_{ij} is the number written in that square after Step 2.

Sample Input 1

3 2
2 6
4 3
1 5

Sample Output 1

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

Sample Input 2

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

Sample Output 2

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


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

int main(){
    int K, X;
    cin >> K >> X;
    for(int i=X-K+1; i<=X+K-1; i++) cout << i << " \n"[i==X+K-1];
    return 0;
}

Score : 200 points

Problem Statement

There are 2000001 stones placed on a number line. The coordinates of these stones are -1000000, -999999, -999998, \ldots, 999999, 1000000.

Among them, some K consecutive stones are painted black, and the others are painted white.

Additionally, we know that the stone at coordinate X is painted black.

Print all coordinates that potentially contain a stone painted black, in ascending order.

Constraints

1 \leq K \leq 100

0 \leq X \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K X

Output

Print all coordinates that potentially contain a stone painted black, in ascending order, with spaces in between.

Sample Input 1

3 7

Sample Output 1

5 6 7 8 9

We know that there are three stones painted black, and the stone at coordinate 7 is painted black. There are three possible cases:

The three stones painted black are placed at coordinates 5, 6, and 7.

The three stones painted black are placed at coordinates 6, 7, and 8.

The three stones painted black are placed at coordinates 7, 8, and 9.

Thus, five coordinates potentially contain a stone painted black: 5, 6, 7, 8, and 9.

Sample Input 2

4 0

Sample Output 2

-3 -2 -1 0 1 2 3

Negative coordinates can also contain a stone painted black.

Sample Input 3

1 100

Sample Output 3

100


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

int a(int i)
{
  int ans = 0;
  for(; i > 0; i--) {
    ans += i;
  }
  return ans;
}

int main(int argc, char** argv)
{
  int N;
  std::cin >> N;

  std::map<std::string, int> dic;
  std::string S;
  for (int i = 0; i < N; i++) {
    std::cin >> S;
    std::sort(std::begin(S), std::end(S));
    if (dic.find(S) == std::end(dic)) {
      dic[S] = 1;
    }
    else {
      dic[S]++;
    }
  }

  int ans = 0;
  for (auto & e : dic) {
    if (e.second > 1) {
      ans += a(e.second-1);
    }
  }

  std::cout << ans << std::endl;

  return 0;
}

Score : 300 points

Problem Statement

We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.

For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.

Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

s_1, s_2, \ldots, s_N are all distinct.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

If there is no pair i, j such that s_i is an anagram of s_j, print 0.

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


// Green Bin
#include <iostream>
#include <vector>
#include <math.h>
#include <string>
#include <map>
#include <stdio.h>
#include <string.h>
#include <initializer_list>
#include <algorithm>

using namespace std;

int main()
{
    int N;
    cin >> N;
    map<string, int> m;
    for (int i = 0; i < N; i++) {
        string s;
        cin >> s;
        sort(s.begin(), s.end());
        int tmp = m[s];
        tmp++;
        m[s] = tmp;
    }

    int cnt = 0;
    for (auto it = m.begin(); it != m.end(); ++it) {
        int value = it->second;
        if (value > 1) {
            cnt += ((value * (value - 1)) / 2);
        }
    }

    cout << cnt << endl;

    return 0;
}


#include <iostream>
#include <climits>
#include <vector>
#include <set>
#include <map>
#include <utility>
#include <string>
#include <queue>
#include <array>
#include <list>
#include <cmath>
#include <algorithm>
using namespace std;

#define pii pair<int, int>
#define mp make_pair
#define pb push_back

bool func(pii a, pii b){
	if(a.second > b.second)
		return true;
	else if (a.second == b.second)
		return (a.first > b.first);
	return false;
}

int main(void){
	int n, m;
	cin >> n >> m;
	vector<pii> v;
	vector<int> x(m,0);
	for(int i = 0;i < n;i++){
		int a, b;
		cin >> a >> b;
		if(a > m) continue;
		else if(m + 1 - x[a-1] - a > 0){
			x[a-1]++;
			v.pb(mp(a,b));
		}
	}
	int len = v.size();
	sort(v.begin(), v.end(), func);
	vector<int> xxx;
	for(int i = 0;i < m;i++)
		xxx.pb(m-i);
	int ans = 0;
	int temp = INT_MAX;
	for(int i = 0,j= 0;i < len && j < m && v[i].first < temp;i++){
		if(x[v[i].first-1] > 0){
			ans+= v[i].second;
			x[v[i].first-1]--;
			xxx[v[i].first-1]--;
			j++;
			if(xxx[v[i].first-1] == 0)
				temp = v[i].first;
		}
	}
	cout << ans << endl;
}

Score : 400 points

Problem Statement

There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.

You can take and complete at most one of these jobs in a day.

However, you cannot retake a job that you have already done.

Find the maximum total reward that you can earn no later than M days from today.

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

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 maximum total reward that you can earn no later than M days from today.

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

You can earn the total reward of 5 by taking the jobs as follows:

Take and complete the first job today. You will earn the reward of 3 after four days from today.

Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0


#include <algorithm>
#include <array>
#include <bitset>
#include <deque>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
//region cp_helper
using namespace std;
#define _io ios_base::sync_with_stdio(false); cin.tie(nullptr);
#define ll long long
#define ull unsigned long long
#define ii pair<int, int>
#define vi vector<int>
#define vvi vector< vector<int> >
#define vll vector<ll>
#define vii vector<ii>
#define in(n) cin >> n
#define out(n) cout << n
#define outs(n) cout << n << ' '
#define outn(n) cout << n << '\n'
#define vin(a, n) for (int i=0; i<n; i++) in(a[i])
#define viin(a, n) for (int i=0; i<n; i++) in(a[i].first) >> a[i].second;
#define vout(a) for (auto i : a) outs(i)
#define all(a) a.begin(), a.end()
#define qsort(a) sort(all(a))
#define qdsort(a) sort(all(a), greater<>())
const int mod = (int)(1e9) + 7;
//endregion

using namespace std;
int n, m, s[100005], c, total;
int main() { _io
    in(n); in(m);
    vii arr(n);
    viin(arr, n);
    sort(all(arr), [](ii a, ii b) {
        if (a.second == b.second) return a.first < b.first;
        return a.second>b.second;
    });
    for (auto i : arr) {
        if ((m-i.first) >= s[i.first]) {
            total += i.second;
            s[i.first]++;
            c++;
        }
        if (c >= m) break;
    }
    outn(total);
}


#include <iostream>
#include <iomanip>
#include <utility>
#include <cmath>
#include <random>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;

#define rep(i,n) for(int i = 0; i<n; ++i)
const int INF = 100100100;
const int MOD = (int)1e9 + 7;
typedef long long ll;

int main(){
    int a,b,c; cin >> a >> b >> c;
    cout << max(c+b-a,0) << endl; return 0;
}

Score : 100 points

Problem Statement

We have two bottles for holding water.

Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.

Bottle 2 contains C milliliters of water.

We will transfer water from Bottle 2 to Bottle 1 as much as possible.

How much amount of water will remain in Bottle 2?

Constraints

All values in input are integers.

1 \leq B \leq A \leq 20

1 \leq C \leq 20

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2.

Sample Input 1

6 4 3

Sample Output 1

1

We will transfer two milliliters of water from Bottle 2 to Bottle 1, and one milliliter of water will remain in Bottle 2.

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0


#include <iostream>

int main()
{
    int a, b, c;
    std::cin >> a >> b >> c;

    if (c - (a - b) <= 0) { std::cout << 0 << std::endl; }
    else
    {
        std::cout << c - (a - b) << std::endl;
    }

    return 0;
}


#include<iostream>
using namespace std;
typedef long long ll;
const int maxn=1e6+5;
const int mod=1e9+7;
ll  n,k;
ll a[maxn];

int main()
{
    int a,b,c;
    cin>>a>>b>>c;
    if(c-(a-b)<=0) cout<<0;
    else cout<<c-(a-b);
}


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

bool f(int x){
    int keta=0;
    while(x){
        keta++;
        x /=10;
    }
    return keta % 2 == 1;
}

int main(){
    int n;
    cin >> n;
    int ans =0;
    for(int i=0;i<n;i++){
        if(f(i))ans++;

    }
    cout << ans << endl;

}

Score : 200 points

Problem Statement

Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros).

Constraints

1 \leq N \leq 10^5

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of positive integers less than or equal to N that have an odd number of digits.

Sample Input 1

11

Sample Output 1

9

Among the positive integers less than or equal to 11, nine integers have an odd number of digits: 1, 2, \ldots, 9.

Sample Input 2

136

Sample Output 2

46

In addition to 1, 2, \ldots, 9, another 37 integers also have an odd number of digits: 100, 101, \ldots, 136.

Sample Input 3

100000

Sample Output 3

90909


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

int main() {
    long a,b,res;
    cin>>a>>b;
    res=((a+b)/2);
    if(res%2==0)
    cout<<res<<endl;
    else
    cout<<"IMPOSSIBLE\n";
	return 0;
}

Score: 100 points

Problem Statement

We have two distinct integers A and B.

Print the integer K such that |A - K| = |B - K|.

If such an integer does not exist, print IMPOSSIBLE instead.

Constraints

All values in input are integers.

0 \leq A,\ B \leq 10^9

A and B are distinct.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the integer K satisfying the condition.

If such an integer does not exist, print IMPOSSIBLE instead.

Sample Input 1

2 16

Sample Output 1

9

|2 - 9| = 7 and |16 - 9| = 7, so 9 satisfies the condition.

Sample Input 2

0 3

Sample Output 2

IMPOSSIBLE

No integer satisfies the condition.

Sample Input 3

998244353 99824435

Sample Output 3

549034394


#include <iostream>

using namespace std;

int main(void) {
	int N;
	cin >> N;
	int num;
	int count = 0;
	for (int i = 0; i < N; ++i) {
		cin >> num;
		if (num != i+1) {
			++count;
		}
	}
	if (count > 2) {
		cout << "NO" << endl;
	}
	else {
		cout << "YES" << endl;
	}
	return 0;
}

Score : 200 points

Problem Statement

We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.

You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.

Print YES if you can sort p in ascending order in this way, and NO otherwise.

Constraints

All values in input are integers.

2 \leq N \leq 50

p is a permutation of {1,\ 2,\ ...,\ N}.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print YES if you can sort p in ascending order in the way stated in the problem statement, and NO otherwise.

Sample Input 1

5
5 2 3 4 1

Sample Output 1

YES

You can sort p in ascending order by swapping p_1 and p_5.

Sample Input 2

5
2 4 3 5 1

Sample Output 2

NO

In this case, swapping any two elements does not sort p in ascending order.

Sample Input 3

7
1 2 3 4 5 6 7

Sample Output 3

YES

p is already sorted in ascending order, so no operation is needed.


#include<bits/stdc++.h>
#define int long long
#define x first
#define y second
#define pb push_back

#define speed ios_base::sync_with_stdio(0);cin.tie(0);
using namespace std;
signed main()
{
    speed
    int n;cin>>n;
    vector<int> inp(n);
    for(int i=0;i<n;++i){cin>>inp[i];}
    std::vector<int> tinp=inp;
    sort(tinp.begin(),tinp.end());
    int ct=0;
    for(int i=0;i<n;++i)
    {
        if(tinp[i]!=inp[i]){++ct;}
    }
    if(ct==0||ct==2){cout<<"YES";}
    else{cout<<"NO";}
}


#include<bits/stdc++.h>
using namespace std;
int main(){
  int N;
  cin>>N;
  vector<int>A(N+1);
  vector<int>B(N);
  for(int i=0;i<N+1;i++)cin>>A[i];
  for(int i=0;i<N;i++)cin>>B[i];
  int ans=0;
  for(int i=0;i<N;i++){
    if(A[i]<=B[i]){
      ans+=A[i];
      B[i]-=A[i];
    }else{
      ans+=B[i];
      B[i]=0;
    }
    if(A[i+1]<=B[i]){
      ans+=A[i+1];
    }else{
      ans+=B[i];
      A[i+1]-=B[i];
    }
    //cout<<ans<<endl;
  }
  cout<<ans<<endl;

}

Score : 300 points

Problem Statement

There are N+1 towns. The i-th town is being attacked by A_i monsters.

We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.

What is the maximum total number of monsters the heroes can cooperate to defeat?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N

Output

Print the maximum total number of monsters the heroes can defeat.

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.

The first hero defeats two monsters attacking the first town and two monsters attacking the second town.

The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3


#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <vector>
#include <regex>
#include <map>
#include <set>
using namespace std;
int main(){
    int N;
    cin >> N;
    vector<long long> A(N+1);
    vector<long long> B(N);

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

    int ans = 0;
    for(int i=0;i<N;i++){
        if(A[i]>B[i]){
            ans += B[i];
        }else{
            if(B[i]-A[i]<A[i+1]){
                ans += B[i];
            }else{
                ans += A[i]+A[i+1];
            }
        }
        }
    cout << ans << endl;

    return 0;
}


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

int mod = 1'000'000'007;

long long modpow(long long a, long long b, int p){
    if (b == 0) return 1;
    if (b % 2) return a * modpow(a, b - 1, p) % p;
    return modpow(a, b / 2, p) * modpow(a, b / 2, p) % p;
}

int main(){
    string s;
    cin >> s;
    int k = s.size();
    vector<long long> dp(13, 0);
    dp[0] = 1;
    for (int i = 0; i < k; i++){
        vector<long long> next_dp(13, 0);
        long long tmp = modpow(10, k - i - 1, 13);
        if (s[i] == '?'){
            for (int j = 0; j < 13; j++) {
                for (int z = 0; z < 10; z++){
                    next_dp[(tmp * z % 13 + j) % 13] += dp[j];
                }
            }
        }
        else {
            for (int j = 0; j < 13; j++){
                next_dp[(tmp * (s[i] - '0') % 13 + j) % 13] += dp[j];
            }
        }
        dp = next_dp;
    }
    cout << dp[5] % mod << endl;
}

Score : 400 points

Problem Statement

Given is a string S. Each character in S is either a digit (0, ..., 9) or ?.

Among the integers obtained by replacing each occurrence of ? with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0.

Since the answer can be enormous, print the count modulo 10^9+7.

Constraints

S is a string consisting of digits (0, ..., 9) and ?.

1 \leq |S| \leq 10^5

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

??2??5

Sample Output 1

768

For example, 482305, 002865, and 972665 satisfy the condition.

Sample Input 2

?44

Sample Output 2

1

Only 044 satisfies the condition.

Sample Input 3

7?4

Sample Output 3

0

We may not be able to produce an integer satisfying the condition.

Sample Input 4

?6?42???8??2??06243????9??3???7258??5??7???????774????4?1??17???9?5?70???76???

Sample Output 4

153716888


/*
 * Author: aps
 * Time: 2019-07-28 19:43:46
**/
#include<bits/stdc++.h>

#define fi first
#define se second
#define pb push_back
#define all(x) x.begin(), x.end()

using namespace std;

typedef long long int ll;
typedef long double ld;
typedef pair<ll,ll> pll;
typedef vector<ll> vl;
typedef vector<int> vi;
typedef pair<int,int> pii;

const ll inf = 1e18;
const ll mod = 1e9+7;

inline ll add(ll x, ll y) { x += y; if (x >= mod) x -= mod; return x;}
inline ll sub(ll x, ll y) { x -= y; if (x < 0) x += mod; return x;}
inline ll mul(ll x, ll y) { return ((x % mod) * (y % mod)) % mod;}
inline ll power(ll a, ll b) {
    ll x = 1;
    while (b) {
        if (b & 1) x = mul(x, a);
        a = mul(a, a);
        b >>= 1;
    }
    return x;
}
inline ll inv(ll a) { return power(a, mod - 2);}

const int N = 1e5+5;

ll dp[N][13];

int main(){
    ios_base::sync_with_stdio(false); cin.tie(0);
    string s; cin >> s;
    int n = (int)s.length();

    dp[0][0] = 1LL;
    for(int i=0;i < n;i++){
        if(s[i] == '?'){
            for(int d=0;d<10;d++){
                for(int pd=0; pd < 13; pd++){
                    int rem = (pd*10 + d)%13;
                    dp[i+1][rem] = add(dp[i+1][rem],dp[i][pd]);
                }
            }
        } else {
            int d = s[i] - '0';
            for(int pd = 0; pd < 13; pd++){
                int rem = (pd*10 + d)%13;
                dp[i+1][rem] = add(dp[i+1][rem],dp[i][pd]);
            }
        }
    }

    cout << dp[n][5] << endl;
    return 0;
}