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

int main(){
  int N,M;
  cin>>N>>M;
  int mir=N,mal=0;
  vector<int> L(M),R(M);
  for(int i=0;i<M;i++){
    cin>>L.at(i)>>R.at(i);
    mir=min(mir,R.at(i));
    mal=max(mal,L.at(i));
  }
  cout<<mir-mal+1<<endl;

}


#include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3f
#define MOD 1000000007
using namespace std;
typedef long long ll;
typedef pair<int,int>P;

struct Med{
	multiset<int>f,b;
	ll s1=0,s2=0;
	void balance(){
		while(f.size()>=b.size()+2){
			int t=*f.rbegin();
			f.erase(--f.end());
			s1-=t;
			s2+=t;
			b.insert(t);
		}
		while(f.size()<b.size()){
			int t=*b.begin();
			b.erase(b.begin());
			s2-=t;
			s1+=t;
			f.insert(t);
		}
	}
	void insert(int x){
		if(!b.empty()&&*b.begin()<x){
			b.insert(x),s2+=x;
		}
		else f.insert(x),s1+=x;
		balance();
	}
};
Med med;
int main(){
	int q;cin>>q;
	ll t=0;
	rep(i,q){
		int ty;scanf("%d",&ty);
		if(ty==1){
			int a,b;scanf("%d%d",&a,&b);
			t+=b;
			med.insert(a);
		}
		else{
			int x=*med.f.rbegin();
			printf("%d %lld\n",x,t+x*(ll)med.f.size()-med.s1+med.s2-x*(ll)med.b.size());
		}
	}
}

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

Score : 600 points

Problem Statement

There is a function f(x), which is initially a constant function f(x) = 0.

We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:

An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).

An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.

We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.

Constraints

All values in input are integers.

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

-10^9 \leq a, b \leq 10^9

The first query is an update query.

Input

Input is given from Standard Input in the following format:

Q
Query_1
:
Query_Q

See Sample Input 1 for an example.

Output

For each evaluation query, print a line containing the response, in the order in which the queries are given.

The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.

Sample Input 1

4
1 4 2
2
1 1 -8
2

Sample Output 1

4 2
1 -3

In the first evaluation query, f(x) = |x - 4| + 2, which attains the minimum value of 2 at x = 4.

In the second evaluation query, f(x) = |x - 1| + |x - 4| - 6, which attains the minimum value of -3 when 1 \leq x \leq 4. Among the multiple values of x that minimize f(x), we ask you to print the minimum, that is, 1.

Sample Input 2

4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2

Sample Output 2

-1000000000 3000000000

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 s,f=0,l=0;
  cin >> s;

  f = s/100;
  l = s%100;

  if(1<=f<=12  && 1<=l<=12){
    cout << "AMBIGUOUS" << endl;
  } else if(1<=f<=12){
    cout << "MMYY" << endl;
  } else if(1<=l<=12){
    cout << "YYMM" << endl;
  } else{
    cout << "NA" << endl;
  }
}

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


#include <iostream>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
#include <algorithm>
#include <string>

using namespace std;

int main() {
  int n,b;
  cin >> n >> b;
  std::string s;
  cin >> s;

  char cary[n];
  s.copy(cary, n);

  for (int i=0;i<n;i++){
    if (i == b-1) {
      cary[i] = std::tolower(cary[i]);
    }
  }

  cout << cary << endl;
  return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <array>
#include <queue>
#include <stack>
#include <algorithm>
#include <tuple>
#include <numeric>
#include <type_traits>

int main()
{
	int N, K;
	std::string S;

	std::cin >> N >> K;
	std::cin >> S;

	S[K-1] = S[K-1] + ('a' - 'A');

	std::cout << S << "\n";
}


#include <bits/stdc++.h>

using namespace std;

int main(){
    char n[4];
    cin >> n;
    int period[4] = {n[0] - '0', n[1] - '0', n[2] - '0', n[3] - '0'};
    int front = (10 * period[0]) + period[1];
    int back = (10 * period[2]) + period[3];
    if(front > 12 && back > 12){
        cout << "NA" << endl;
    }else if(front == 0 && back >12){
        cout << "NA" << endl;
    }else if(front > 12 && back ==0){
        cout << "NA" << endl;
    }else if(front ==0 && back ==0){
        cout << "NA" << endl;
    }else if(front <=12 && back > 12){
        cout << "MMYY";
    }else if(front > 12 && back <= 12){
        cout << "YYMM";
    }else{
        cout << "AMBIGUOUS";
    }

    return 0;
}

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define ll long long
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	string s;
	cin >> s;
	int a=0,vv=0;

	if((s[0]=='1' && s[1]<='2') || (s[0]=='0' && s[1]!='0'))
	{
		a=1;
	}
	if((s[2]=='1' && s[3]<='2') || (s[2]=='0' && s[3]!='0'))
	{
		vv=1;
	}
	if(a==1 && vv!=1)
	{
		cout << "MMYY";
	}
	else if(a==1)
	{
		cout << "AMBIGUOUS";
	}
	else if(vv==1)
	{
		cout << "YYMM";
	}
	else
	{
		cout << "NA";
	}
	return 0;
}


#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
#define pb push_back
#define AA first
#define BB second
#define ONES(x) __builtin_popcount(x)
#define _ <<" "<<
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
const double eps=1e-6;
const int mod=1e9+7;
const double PI=acos(-1.0);
inline int read(){ int num;    scanf("%2d",&num);   return num;}
const int maxn=1e5+7;
//numerator分子  denominator分母
class Rational {
	public:
    Rational(int n=0,int d=1):num(n),den(d) {} //有参构造函数
    friend Rational operator+(const Rational &r1,const Rational &r2);//相加
    friend Rational operator-(const Rational &r1,const Rational &r2);//相减
    friend Rational operator/(const Rational &r1,const Rational &r2);//相除
    friend Rational operator*(const Rational &r1,const Rational &r2);//相乘
    void simplify();//对有理数进行化简
    void display();  //显示结果
    double num;
    double den;

};
Rational operator+(const Rational &r1,const Rational &r2) {
    Rational r;
    r.num = r1.den*r2.num+r1.num*r2.den;//相加的分子等于r1分母和r2分子相乘，r1分子和r2分母相乘之和
    r.den = r1.den*r2.den;//分母等于两个有理数分母的相乘
    r.simplify();//调用simplify对结果进行化简
    return r;//将结果返回
}
Rational operator-(const Rational &r1,const Rational &r2) {
    Rational r;
    r.num = r1.num*r2.den-r1.den*r2.num;//相加的分子等于r1分母和r2分子相乘，r1分子和r2分母相乘之差
    r.den = r1.den*r2.den;//分母等于两个有理数分母的相乘
    r.simplify();
    return r;
}
Rational operator/(const Rational &r1,const Rational &r2) {
    Rational r;
    if(r1.den==0||r2.den==0||r2.num==0) {
        cout<<"分母或者除数不能为0"<<endl;
    } else if(r1.num==0) {
        cout<<"0/0"<<endl;
    } else {
        r.num = r1.num*r2.den;//相除的分子等于r1分子和r2分母相乘
        r.den = r1.den*r2.num;//分母等于两个r1分母和r2分子相乘
        r.simplify();
        return r;
    }
}
Rational operator*(const Rational &r1,const Rational &r2) {
    Rational r;
    if(r1.den==0||r2.den==0) {
        cout<<"分母不能为0"<<endl;
    } else if(r1.num==0||r2.num==0) {
        cout<<"0/0"<<endl;
    } else {
        r.num = r1.num*r2.den;//分子等于r1分子和r2分母相乘
        r.den = r1.den*r2.num;//分母等于两个r1分母和r2分子相乘
        r.simplify();
        return r;
    }
}
void Rational::simplify() {
    int i,j,temp;
    i=abs(den);
    j=abs(num);
    //如果i对j取余不为0，辗转相除法求最大公约数
    while(temp=i%j) {
        i=j;
        j=temp;
    }
    den/=j;
    num/=j;
    if(den<0) {
        den=-den;
        num=-num;
    }
}
void Rational::display() {
    if(num==0||den==0) {

    } else {
        cout<<num<<"/"<<den<<endl;
    }
}
int main()
{
	Rational r;
    Rational r1(1,3),r2(0,5);
	int a,b,c,d;
	scanf("%d",&a);b=read();//getchar();//c=read();d=read();
	Rational ans(0,1);Rational tmp=(1,a);
	for(int i=1;i<=a;i++)
	{
		int t=i;int cnt=0;
		while(t<b)
		{
			t*=2;cnt++;
		}
		Rational tt(1,1);Rational ttt=(1,2);
		for(int j=1;j<=cnt;j++)
		tt=tt*ttt;
		ans=ans+tt;
		long double aa=ans.num;long double bb=ans.den;
	    //cout<<aa<<" "<<bb<<endl;
	}
	ans=ans*tmp;
	ans.simplify();
	long double aa=ans.num;long double bb=ans.den;
	//cout<<aa<<" "<<bb<<endl;
	long double aaaa=aa/bb;
	printf("%.14Lf\n",aaaa);
	return 0;
}

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


#include <bits/stdc++.h>
using namespace std;
using Graph = vector<vector<int>>;

// DFS

void dfs(Graph &G, map<pair<int, int>, int> &MAP, vector<int> &color, int x) {

  for (int nx : G[x]) {

    if (color[nx] != -1) continue;

    if (MAP[{x, nx}] % 2 == 0) {
      color[nx] = color[x];
      dfs(G, MAP, color, nx);
    }

    else {
      color[nx] = 1 - color[x];
      dfs(G, MAP, color, nx);
    }

  }

  return;

}

int main () {

  // 入力

  int N;
  cin >> N;

  Graph G(N);
  map<pair<int, int>, int> MAP;

  for(int i = 0; i < N - 1; i++) {

    int a, b, w;
    cin >> a >> b >> w;
    a--;
    b--;

    G[a].push_back(b);
    G[b].push_back(a);
    MAP[{a, b}] = w;
    MAP[{b, a}] = w;

  }

  // DFS

  vector<int> color(N, -1);
  color[0] = 0;
  dfs(G, MAP, color, 0);

  // 出力

  for (int i = 0; i < N; i++) {
    cout << color[i] << endl;
  }

}

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

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

Sample Output 2

1
0
1
0
1


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T>
using ordered_set_rev = tree<T, null_type, greater<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T>
using dijkstra = priority_queue<T, vector<T>, greater<T>>;

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define fbo find_by_order //k th index
#define ook order_of_key // strictly smaller than k
#define PI acos(-1.0)
#define inf 0x3f3f3f3f
#define max_ull 18446744073709551615
#define max_ll 9223372036854775807
#define min3(a, b, c) min(a, min(b, c))
#define max3(a, b, c) max(a, max(b, c))
#define min4(a, b, c, d) min(min(a, b), min(c, d))
#define max4(a, b, c, d) max(max(a, b), max(c, d))
#define max5(a, b, c, d, e) max(max3(a, b, c), max(d, e))
#define min5(a, b, c, d, e) min(min3(a, b, c), min(d, e))
#define lead_zero(x) __builtin_clzll(x)
#define trail_zero(x) __builtin_ctzll(x)
#define total_1s(x) __builtin_popcountll(x)
#define first_1(x) __builtin_ffsll(x)
#define log2_(x) __builtin_clz(1) - __builtin_clz(x)
#define isLeap(x) ((x % 400 == 0) || (x % 100 ? x % 4 == 0 : false))
#define QUERY int test;scanf("%d", &test);for (int _T = 1; _T <= test; _T++)
#define FAST ios_base::sync_with_stdio(0), cin.tie(0)
#define all(v) v.begin(), v.end()
#define reunique(v) v.resize(std::unique(all(v)) - v.begin())
#define pii pair<int, int>
#define pll pair<ll, ll>
#define ff first
#define ss second
#define MERGE(v1, v2, v) merge(all(v1), all(v2), back_inserter(v))
#define MP make_pair
#define EB emplace_back
#define read freopen("input.txt", "r", stdin)
#define write freopen("output.txt", "w", stdout)
#define in_range(v, r, l) upper_bound(all(v), r) - lower_bound(all(v), l)
#define LCM(a,b) (a/__gcd(a,b))*b;
ll rdn(int y, int m, int d) {
    /* Rata Die day one is 0001-01-01 */
    if (m < 3)
        y--, m += 12;
    return 365 * y + y / 4 - y / 100 + y / 400 + (153 * m - 457) / 5 + d - 306;
}
/* Direction arrays */
/* int dx[] = {1,-1,0,0}, dy[] = {0,0,1,-1}; */                        // 4 Direction
/*int dx[] = {1,-1,0,0,1,1,-1,-1}, dy[] = {0,0,1,-1,1,-1,1,-1};       */ // 8 Direction
/* int dx[] = {1,-1,1,-1,2,2,-2,-2} , dy[] = {2,2,-2,-2,1,-1,1,-1}; */ // Knight Direction
/* int dx[] = {2,-2,1,1,-1,-1} , dy[] = {0,0,1,-1,1,-1}; */            // Hexagonal Direction
/* int dx[] = {2,-2,1,1,-1,-1} , dy[] = {0,0,1,-1,1,-1}; */            // Hexagonal Direction
/* int day[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; */
const int N=1e5+9;
int par[N];
int hight[N];
int find_(int x)
{
    while(x!=par[x])
    {
        par[x]=par[par[x]];
        x=par[x];
    }
    return x;
}
void UNION(int x,int y)
{
    x=find_(x);
    y=find_(y);
    if(x!=y)
    {
        if(hight[x]<hight[y])
            swap(x,y);
        par[y]=x;
        hight[x]+=hight[y];
    }
}
vector<pii>v[3];
int main() {
    int n,m;
    scanf("%d %d",&n,&m);
    int a,b,c;
    for(int i=0;i<m;i++){
        scanf("%d %d %d",&a,&b,&c);
        v[c%2].push_back(MP(a,b));
    }
    for(int i=1;i<=n;i++){
        par[i]=i;
        hight[i]=1;
    }
    for(pii &i:v[0]){
        UNION(i.ff,i.ss);
    }
    for(pii &i:v[1]){
        UNION(i.ff,i.ss);
    }
    sort(par+1,par+n+1);
    int prev=-1;
    int cnt=0;
    for(int i=1;i<=n;i++){
        if(par[i]!=prev)cnt++;
        prev=par[i];
    }
    printf("%d\n",cnt);
}

Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


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

const int N = 1100000;

int main() {
#ifdef Hwang_Baek_I
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
#endif
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	long long n; cin >> n;
	set<long long> S;
	for (int i = 1; (long long)i * i <= n; i++) {
		if (n % i) continue;
		long long m, k;
		m = i - 1, k = n / i;
		if (m > k) S.insert(m);
		m = n / i - 1, k = i;
		if (m > k) S.insert(m);
	}
	long long ans = 0;
	for (long long t : S) ans += t;
	cout << ans << endl;
	return 0;
}

Score : 500 points

Problem Statement

Snuke received a positive integer N from Takahashi.
A positive integer m is called a favorite number when the following condition is satisfied:

The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: 3 and 7. Print the sum of these, 10.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


#include <bits/stdc++.h>
using namespace std;
int main(){
    int64_t N,ans;
    cin >>N;
    for (int i = 1; i <= (int)(sqrt(N+1)-1); i++)if((N-i) % i == 0)ans+=(N-i)/i;
    cout<<ans<<endl;
    return 0;
}


#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep1(i,n) for(int i=1;i<=(int)(n);i++)
#define all(c) c.begin(),c.end()
#define pb push_back
#define fs first
#define sc second
#define chmin(x,y) x=min(x,y)
#define chmax(x,y) x=max(x,y)
using namespace std;
template<class S,class T> ostream& operator<<(ostream& o,const pair<S,T> &p){
	return o<<"("<<p.fs<<","<<p.sc<<")";
}
template<class T> ostream& operator<<(ostream& o,const vector<T> &vc){
	o<<"{";
	for(const T& v:vc) o<<v<<",";
	o<<"}";
	return o;
}
using ll = long long;
template<class T> using V = vector<T>;
template<class T> using VV = vector<vector<T>>;
constexpr ll TEN(int n) { return (n == 0) ? 1 : 10 * TEN(n-1); }

#ifdef LOCAL
#define show(x) cerr << "LINE" << __LINE__ << " : " << #x << " = " << (x) << endl
#else
#define show(x) true
#endif

int H,W;
V<string> s;
const int X = 187;
int lrd2u[2][X][X][X];
int dul2r[2][X][X][X];

int A[X][X];
bool allEqual(int d,int u,int l,int r){
	int c = A[u][r] - A[u][l] - A[d][r] + A[d][l];
	return c == 0 || c == (u-d)*(r-l);
}

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);		//DON'T USE scanf/printf/puts !!
	cout << fixed << setprecision(20);

	cin >> H >> W;
	s.resize(H);
	rep(i,H) cin >> s[i];
	rep(i,H) rep(j,W){
		if(s[i][j] == '#') A[i+1][j+1] = 1;
	}
	rep(i,H+1) rep(j,W) A[i][j+1] += A[i][j];
	rep(i,H) rep(j,W+1) A[i+1][j] += A[i][j];

	rep(l,W) for(int r=l+1;r<=W;r++){
		lrd2u[0][l][r][H] = H;
		for(int d=H-1;d>=0;d--){
			lrd2u[0][l][r][d] = d;
			if(allEqual(d,d+1,l,r)){
				lrd2u[0][l][r][d] = d + 1;
				if(d != H-1 && s[d][l] == s[d+1][l]) lrd2u[0][l][r][d] = lrd2u[0][l][r][d+1];
			}
		}
	}
	rep(d,H) for(int u=d+1;u<=H;u++){
		dul2r[0][d][u][W] = W;
		for(int l=W-1;l>=0;l--){
			dul2r[0][d][u][l] = l;
			if(allEqual(d,u,l,l+1)){
				dul2r[0][d][u][l] = l+1;
				if(l != W-1 && s[d][l] == s[d][l+1]) dul2r[0][d][u][l] = dul2r[0][d][u][l+1];
			}
		}
	}
	rep(t,100){

		// cerr << " -----------turn =  " << t << endl;
		// rep(l,W) for(int r=l+1;r<=W;r++) rep(d,H){
		// 	cerr << "lrd2u["<<l<<"]["<<r<<"]["<<d<<"] = " << lrd2u[t&1][l][r][d] << endl;
		// }
		// rep(d,H) for(int u=d+1;u<=H;u++) rep(l,W){
		// 	cerr << "dul2r["<<d<<"]["<<u<<"]["<<l<<"] = " << dul2r[t&1][d][u][l] << endl;
		// }

		if(lrd2u[t&1][0][W][0] == H){
			cout << t << endl;
			return 0;
		}

		rep(l,W) for(int r=l+1;r<=W;r++){
			rep(d,H+1){
				lrd2u[1-(t&1)][l][r][d] = lrd2u[t&1][l][r][lrd2u[t&1][l][r][d]];
			}
		}
		rep(d,H) for(int u=d+1;u<=H;u++){
			rep(l,W+1){
				dul2r[1-(t&1)][d][u][l] = dul2r[t&1][d][u][dul2r[t&1][d][u][l]];
			}
		}
		rep(l,W) for(int r=l+1;r<=W;r++){
			rep(d,H+1){
				int u = lrd2u[1-(t&1)][l][r][d];
				chmax(dul2r[1-(t&1)][d][u][l],r);
			}
		}
		rep(d,H) for(int u=d+1;u<=H;u++){
			rep(l,W+1){
				int r = dul2r[1-(t&1)][d][u][l];
				chmax(lrd2u[1-(t&1)][l][r][d],u);
			}
		}
		for(int len=W;len>0;len--){
			rep(l,W){
				int r = l + len;
				if(r > W) break;
				rep(d,H+1){
					chmax(lrd2u[1-(t&1)][l+1][r][d],lrd2u[1-(t&1)][l][r][d]);
					chmax(lrd2u[1-(t&1)][l][r-1][d],lrd2u[1-(t&1)][l][r][d]);
				}
			}
		}
		for(int len=H;len>0;len--){
			rep(d,H){
				int u = d + len;
				if(u > H) break;
				rep(l,W+1){
					chmax(dul2r[1-(t&1)][d+1][u][l],dul2r[1-(t&1)][d][u][l]);
					chmax(dul2r[1-(t&1)][d][u-1][l],dul2r[1-(t&1)][d][u][l]);
				}
			}
		}

	}
}

Score : 1000 points

Problem Statement

Note the unusual memory limit.

For a rectangular grid where each square is painted white or black, we define its complexity as follows:

If all the squares are black or all the squares are white, the complexity is 0.

Otherwise, divide the grid into two subgrids by a line parallel to one of the sides of the grid, and let c_1 and c_2 be the complexities of the subgrids. There can be multiple ways to perform the division, and let m be the minimum value of \max(c_1, c_2) in those divisions. The complexity of the grid is m+1.

You are given a grid with H horizontal rows and W vertical columns where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

Find the complexity of the given grid.

Constraints

1 \leq H,W \leq 185

A_{ij} is # or ..

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the complexity of the given grid.

Sample Input 1

3 3
...
.##
.##

Sample Output 1

2

Let us divide the grid by the boundary line between the first and second columns.
The subgrid consisting of the first column has the complexity of 0, and the subgrid consisting of the second and third columns has the complexity of 1, so the whole grid has the complexity of at most 2.

Sample Input 2

6 7
.####.#
#....#.
#....#.
#....#.
.####.#
#....##

Sample Output 2

4


#include<iostream>

using namespace std;

int main()
{	int a,b,t;
	cin >> a >> b >> t;
	cout << (t/a) * b;
}

Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


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

signed main(){
    int N;
    cin>>N;
    int ans=0;
    int V[N],C[N];
    REP(i,N){
        cin>>V[i];
    }
    REP(i,N){
        cin>>C[i];
    }
    REP(i,N){
        if(V[i]-C[i]>0) ans+=V[i]-C[i];
    }
    cout<<ans<<endl;
}

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


//     nohomo    //
//  Brankonymous //
//     nohomo    //

#include <bits/stdc++.h>

#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define rep(i,l,r) for (int i=l;i<=r;i++)
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define ll long long
#define mod 1000000007
#define random_jbt mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

using namespace std;

int main(){
    int n,v[30],b[30];
    cin>>n;
    int ans=0;
    for (int i=1;i<=n;i++)cin>>v[i];
    for (int i=1;i<=n;i++){
        cin>>b[i];
        ans+=max(0,v[i]-b[i]);
    }
    cout<<ans;
    return 0;
}


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

int main(){
  int n;
  cin >> n;
  int a[n];
  int minus = 0;
  for(int i = 0; i < n; i++) {
    cin >> a[i];
    if(a[i] < 0) minus++;
  }
  int ans = 0;
  for(int i = 0; i < n; i++) {
    ans += abs(a[i]);
  }
  bool f = 1;
  for(int i = 0; i < n; i++) {
    if(a[i] == 0) f = 0;
  }
  int AT[n];
  for(int i = 0; i < n; i++) {
    AT[i] = abs(a[i]);
  }
  if(f) {
    if(minus % 2 == 1) {
      sort(AT, AT + n);
      ans -= AT[0];
    }
  }
  cout << ans << endl;
  return 0;
}

Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

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


#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <queue>
#include <set>
#include <algorithm>
#include <string>
#include <math.h>
#include <limits.h>
#include <stack>
#include <complex>
#include <stdlib.h>
#include <stdio.h>
#include <functional>
#include <cfloat>
#include <math.h>

#define fs first
#define sc second

using namespace std;

typedef long long ll;
typedef pair<ll, int> P;
ll mod = 998244353;

bool pp[2][101000];
int N;
int a[300];
vector<vector<ll>> dp(2, vector<ll>(1010000, 0));
unordered_map<int, int> mp;
vector<int> e;

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

    pp[0][0] = true;
    for(int i = 0; i < N; i++){
        for(int j = 0; j < 101000; j++){
            pp[1][j] = pp[0][j];
            if(j - a[i] >= 0 && pp[0][j-a[i]]){
                pp[1][j] = true;
            }
        }
        for(int j = 0; j < 101000; j++){
            pp[0][j] = pp[1][j];
        }
    }

    for(int i = 0; i < 101000; i++){
        if(pp[0][i]){
            e.push_back(i);
        }
    }

    for(int i = 0; i < e.size(); i++){
        mp[e[i]] = i;
    }

    int n = e.size();
    dp[1][0] = 1;

    for(int i = 0; i < N; i++){
        int p = i % 2;
        int q = 1 - p;
        int x = a[i];
        for(int j = 0; j < n*n; j++){
            int red_w = e[j % n];
            int red_index = j % n;
            int blue_w = e[(j / n)];
            int blue_index = (j / n) * n;
            if(mp.find(x+red_w) != mp.end()){
                // 赤に加える
                int index = mp[red_w + x];
                ll add_red = (dp[p][blue_index + index] + dp[q][j]) % mod;
                dp[p][blue_index + index] = add_red;
            }

            if(mp.find(x+blue_w) != mp.end()){
                // 青に加える
                int index = mp[x + blue_w];
                ll add_blue = (dp[p][index * n + red_index] + dp[q][j]) % mod;
                dp[p][index * n + red_index] = add_blue;
            }
            // 緑に加える
            ll add_green = (dp[p][j] + dp[q][j]) % mod;
            dp[p][j] = add_green;
        }
        fill(dp[q].begin(), dp[q].end(), 0);
    }

    ll ret = 0;
    int p = (N-1) % 2;
    for(int i = 0; i < n*n; i++){
        int red = e[i % n];
        int blue = e[(i / n)];
        int green = s - red - blue;
        if(red + green > blue && red + blue > green && blue + green > red){
            ret = (ret + dp[p][i]) % mod;
        }
    }
    ret = (ret) % mod;

    cout << ret << endl;

    return 0;
}

Score : 600 points

Problem Statement

You are given N integers. The i-th integer is a_i.
Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied:

Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area whose sides have lengths R, G and B.

Constraints

3 \leq N \leq 300

1 \leq a_i \leq 300(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
:
a_N

Output

Print the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the condition is satisfied.

Sample Input 1

4
1
1
1
2

Sample Output 1

18

We can only paint the integers so that the lengths of the sides of the triangle will be 1, 2 and 2, and there are 18 such ways.

Sample Input 2

6
1
3
2
3
5
2

Sample Output 2

150

Sample Input 3

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

Sample Output 3

563038556


#include<iostream>
#include<string>
#include<cmath>
#include<array>
#include<algorithm>
#include<deque>
#include<vector>
#include<utility>
#include<set>
#include<map>
#include<list>
#include<bitset>

using namespace std;
using LLI = long long int;
LLI N;

//array<int, 8>dir_x = { 0,0,1,1,1,-1,-1,-1 };
//array<int, 8>dir_y = { 1,-1,1,0,-1,1,0,-1 };
//array<int, 4>dir_x2 = { 0,0,1,-1 };
//array<int, 4>dir_y2 = { 1,-1,0,0 };
//char alp[] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };

//class UnionFind {
//public:
//	vector<int>data;
//	UnionFind(int size) :data(size, -1) {};
//	bool unionset(int x, int y) {
//		x = root(x), y = root(y);
//		if (x != y) {
//			if (data[y] < data[x]) {
//				swap(x, y);
//			}
//			data[x] += data[y];
//			data[y] = x;
//		}
//		return x != y;
//	}
//	bool findset(int x, int y) {
//		return root(x) == root(y);
//	}
//	int root(int x) {
//		return data[x] < 0 ? x : data[x] = root(data[x]);
//	}
//	int size(int x) {
//		return -data[root(x)];
//	}
//};

//LLI gcd(LLI x, LLI y) {
//	LLI  r;
//	if (x < y) {
//		swap(x,y);
//	}
//	r = x % y;
//	while (r != 0) {
//		x = y;
//		y = r;
//		r = x % y;
//	}
//	return y;
//}
//LLI lcm(LLI x,LLI y) {
//	return x / gcd(x,y) * y;
//}

//long nCr(int n,int r) {
//	long ans = 1;
//	for (int i = n; i > n - r;i--) {
//		ans = ans * i;
//	}
//	for (int i = 1; i < r + 1;i++) {
//		ans = ans / i;
//	}
//	return ans;
//}

//const int n_max = 8;
//array<array<bool, n_max>, n_max>graph;
//int dfs(int v,int N,array<bool,n_max>visited) {
//	int ret = 0;
//	bool all_visited = true;
//	for (int i = 0; i < N;i++) {
//		if (visited[i] == false) {
//			all_visited = false;
//		}
//	}
//	if (all_visited) {
//		return 1;
//	}
//	for (int i = 0; i < N;i++) {
//		if (graph[v][i] == false) {
//			continue;
//		}
//		if (visited[i] == true) {
//			continue;
//		}
//		visited[i] = true;
//		ret += dfs(i,N,visited);
//		visited[i] = false;
//	}
//	return ret;
//}

//vector<vector<int>>sub;
//int dfs(int id) {
//	if (sub[id].size() == 0) {
//		return 1;
//	}
//	int minP = (int)1e9;
//	int maxP = 0;
//	for (int i : sub[id]) {
//		int P = dfs(i);
//		minP = min(minP, P);
//		maxP = max(maxP, P);
//	}
//	return minP + maxP + 1;
//}

#define debug(x) cerr << #x << " : " << x << endl
#define debugv(x) cerr << #x << " : "; for(auto i:x) cerr << i << ", "; cerr<<endl

int main(void) {
	string S;
	bool d = true;
	LLI b = 0, w = 0;
	cin >> N >> S;
	LLI last = N,first = 0;
	for (int i = 0; i < N;i++) {
		if (S[i] == '.') {
			first++;
		}
		else {
			break;
		}
	}
	for (int i = N - 1; i >= first;i--) {
		if (S[i] == '#') {
			if (d == true) {
				last--;
			}
		}
		else {
			w++;
			d = false;
		}
	}
	for (int i = 0; i < last;i++) {
		if (S[i] == '#') {
			b++;
		}
	}
	LLI res = min(b,w);
	cout << res << endl;
}

Score : 300 points

Problem Statement

There are N stones arranged in a row. Every stone is painted white or black.
A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <cmath>
#include <cstring>
#include <iomanip>
#include <random>
#include <chrono>
#include <queue>
#include <ctime>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
#define fs first
#define sc second
#define INF 1000000000
#define MOD 1000000007
#define EPS 0.00000001

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

    bool b = false;
    int cntw = 0;
    for(int i=0; i<N; i++){
        if(S[i]=='#') b = true;
        if(b && S[i]=='.') cntw++;
    }

    bool w = false;
    int cntb = 0;
    for(int i=N-1; i>=0; i--){
        if(S[i]=='.') w = true;
        if(w && S[i]=='#') cntb++;
    }

    cout << min(cntb, cntw) << endl;

    return 0;
}


#include <iostream>
using namespace std;

int main() {
    int a,b;
    cin>>a>>b;
    cout<<(a==b?a+b:max(a,b)*2-1)<<endl;
}

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


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

int main() {
  int A,B;
  cin >> A;
  cin >> B;

  if (A+B >= A+A-1 && A+B >= B+B-1){
    cout << A+B <<endl;}
  else if (A+A-1 >= A+B && A+A-1 >= B+B-1){
    cout << A+A-1 <<endl;}
 else if (B+B-1 >= A+B &&  B+B-1 >= A+A-1 ){
   cout <<  B+B-1 << endl;}
}


#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
    int a, b;
    int ans = 0;
    cin >> a >> b;

    for (int i = 0; i < 2; i++) {
        if (a < b) {
            ans += b;
            b--;
        }
        else {
            ans += a;
            a--;
        }
    }

    cout << ans << endl;
}


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

int main() {
  int n,cnt = 1;
  cin >> n;
  vector<int>height(n);
  for (int i = 0; i < n; i++) {
    cin >> height.at(i);
  }
  for (int i = 1; i < n; i++) {
    bool check = 1;
    for (int j = 0; j < i; j++) {
      if (height.at(i) < height.at(j)) {
        check = 0;
      }
    }
    if (check == 1) cnt ++;
  }
  cout << cnt;
}

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
#define FOR(i,a,b) for(int i =(a) ; i <= (b); i++)
#define ROF(i,a,b) for(int i =(b) ; i >= (a); i--)
#define REP(i,n)  FOR( i, 0, (n) - 1 )
#define PER(i,n)  ROF( i, 0, (n) - 1 )

int main(){
    int N,H[21],max=0,ans=0;
    cin >> N;
    REP(i,N){
        cin >> H[i];
        if(max <= H[i]){
            ans++;
            max = H[i];
        }
    }
    cout << ans << endl;
    return 0;
}


#include <iostream>
using namespace std;
int main(){
	int N;
  cin >> N;
  int height[N];
  for(int i = 0;i<N;i++){
  	cin >> height[i];  }
  int max=0;
  int counter=0;
  for(int k=0;k<N;k++){
	if(max<height[k]){
    	max = height[k];

      ++counter;
    }
  }
  cout << counter <<endl;
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout << fixed << setprecision(15);

  string s;
  cin >> s;
  int si = s.size();

  int cnt1 = 0, cnt2 = 0;
  for (int i = 0; i < si; ++i) {
    if (i % 2 == 0) {
      if (s[i] == '0') {
        ++cnt1;
      } else {
        ++cnt2;
      }
    } else {
      if (s[i] == '1') {
        ++cnt1;
      } else {
        ++cnt2;
      }
    }
  }

  cout << min(cnt1, cnt2) << '\n';

  return 0;
}

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


#include <iostream>
#include <algorithm>
#include <string>
#define rep(i, x, n) for (int i = x; i < n; i++)
using namespace std;
int main()
{
    int N, K;
    cin >> N >> K;
    string S;
    cin >> S;
    int H[100000];
    rep(i, 0, N) { H[i] = 0; }
    int tmp = S[0] - '0';
    H[0] = 1;
    int tmpIdx = 0;
    int ind = 1;
    while (ind < N)
    {
        int si = S[ind] - '0';
        if (tmp == si)
        {
            H[tmpIdx]++;
        }
        else
        {
            H[tmpIdx + 1]++;
            tmpIdx++;
            tmp = si;
        }
        ind++;
    }
    int kukansu = tmpIdx + 1;
    int ruisekiwa[kukansu];
    rep(i, 0, kukansu)
    {
        if (i == 0)
        {
            ruisekiwa[i] = H[i];
        }
        else
        {
            ruisekiwa[i] = ruisekiwa[i - 1] + H[i];
        }
        //  cout << ruisekiwa[i] << endl;
    }
    int kukanlong = 2 * K + 1;
    int max = 0;
    rep(i, 0, kukansu)
    {
        int sum;
        if (i + kukanlong > N)
        {
            kukanlong = N - i;
        }
        if (i == 0)
        {
            if (S[0] == '0' && i + kukanlong < N)
            {
                sum = ruisekiwa[kukanlong -2];
            }
            else
            {
                sum = ruisekiwa[kukanlong-1];
            }
        }else{
            sum=ruisekiwa[i+kukanlong-1]-ruisekiwa[i-1];
        }
        if(max<sum){
            max=sum;
        }
    }
    cout << max << endl;
}

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

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

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

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


#include<iostream>
#include<string>
#include<map>
#define int long long int

using namespace std;

signed main(){

    int a[5], i;
    int tmp = 1000000;
    int pp;

    for(i = 0; i < 5; i++){
        cin >> a[i];

        if(a[i] % 10 == 0){
            continue;
        }

        if(tmp > a[i] % 10){
            tmp = a[i] % 10;
            pp = i;
        }
    }

    int ans = 0;
    for(i = 0; i < 5; i++){
        if(i == pp){
            ans = ans + a[pp];
        }else{
            if(a[i] % 10 != 0){
                ans = ans + a[i] + (10 - a[i] % 10);
            }else{
                ans = ans + a[i];
            }
        }
    }

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

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


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

int main(){

    ll N,a[5];
    cin>>N;
    rep(i,0,5)cin>>a[i];
    sort(a,a+5);
    if(N<=a[0])cout<<5<<endl;
    else cout<<(ll)ceil(N/a[0])+4<<endl;
}

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

Note that the input or output may not fit into a 32-bit integer type.


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

int main(){
    long N;
    cin >> N;
    long tmp;
    long trans[5];

    for(int i = 0; i < 5; i++){
        cin >> tmp;
        trans[i] = tmp;
    }

    long mini = trans[0];

    for(int i = 1; i < 5; i++){
        if(mini > trans[i]) mini = trans[i];
    }

    if(mini >= N) cout << 5 << '\n';
    else cout << 5 + N/mini << '\n';

    return 0;
}


#include <iostream>
#include <algorithm>
#include <array>

typedef long long ll;

int main (void){
  ll N; std::cin >> N;
  std::array<ll, 5> t;
  for(int i=0; i<5; i++){
    std::cin >> t[i];
  }

  ll m = *std::min_element(t.begin(), t.end());
  ll s = N%m == 0 ? N/m : N/m+1;
  std::cout << 4 + s << std::endl;
  return 0;
}


#include <bits/stdc++.h>
#define all(x) begin(x), end(x)
#define dbg(x) cerr << #x << " = " << x << endl
#define _ << ' ' <<
using namespace std;
using ll = long long;
using vi = vector<int>;

ll a[1001], b[1001], c[1001], d[1000001];
int x, y, z, k;
int p, q;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> x >> y >> z >> k;
    for (int i = 0; i < x; ++i)
        cin >> a[i];
    for (int i = 0; i < y; ++i)
        cin >> b[i];
    for (int i = 0; i < z; ++i)
        cin >> c[i];

    for (int i = 0; i < x; ++i)
        for (int j = 0; j < y; ++j)
            d[i * y + j] = a[i] + b[j];

    sort(c, c + z, greater<ll>());
    sort(d, d + (x * y), greater<ll>());

    vector<ll> sol;
    for (int i = 0; i < min(k, x * y); ++i)
        for (int j = 0; j < z; ++j)
            sol.push_back(c[i] + d[j]);

    sort(all(sol), greater<ll>());
    for (int i = 0; i < k; ++i)
        cout << sol[i] << '\n';
}

Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

Note that the input or output may not fit into a 32-bit integer type.


#define rep(i,x) for (int i = 0; i < x; i++)
#define mod 1000000007
#define MOD 998244353
#define INF (1<<31)-1
#define _USE_MATH_DEFINES
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>
#include <functional>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <math.h>
#include <complex>
#include <cassert>
using namespace std;
typedef long long int ll;
typedef pair<ll, ll> p;
typedef complex<double> com;

int main() {
	string a;
	cin >> a;
	int ans = 0;
	string s = "ATGC";
	int cnt = 0;
	rep(i, a.size()) {
		int cnt2 = 0;
		rep(j, 4) {
			if (s[j] == a[i]) {
				cnt2++;
			}
		}
		if (cnt2 > 0) {
			cnt++;
			ans = max(ans, cnt);
		}
		else {
			cnt = 0;
		}
	}
	cout << ans << endl;
	return 0;
}

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

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

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

Constraints

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

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


// スタックサイズ: 100MB

#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <unordered_map>
#include <string>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <functional>
#include <numeric>
#include <iomanip>
#include <queue>
#include <list>
#include <set>
using namespace std;

typedef int64_t ll;
typedef vector<ll> vll;
typedef pair<ll, ll> pll;
const ll INF = 1000000000000000000;
#define fori(i, a, b) for (ll i = (a); i < (b); ++i)
#define ford(i, a, b) for (ll i = (b - 1); (a) <= i; --i)
#define rep(i, n) fori(i, 0, n)
#define all(v) (v).begin(), (v).end()
ll pw(ll x, ll y) { ll r = 1;  rep(i, y) { r *= x; }; return r; }

int main() {

	ll N, Q;
	cin >> N >> Q;
	string s;
	cin >> s;
	vll acc(N, 0);
	fori(i, 1, N) {
		if (s[i - 1] == 'A' && s[i] == 'C') acc[i] = acc[i - 1] + 1;
		else acc[i] = acc[i - 1];
	}

	rep(i, Q) {
		ll l, r;
		cin >> l >> r;
		l -= 1, r -= 1;
		cout << acc[r] - acc[l] << endl;
	}
}

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

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

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

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

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

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


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

/* macro */
#define rep(i,a,b) for(int i=a;i<b;i++)
#define revrep(i,a,b) for(int i = a; i > b; i--)
#define int long long
#define exist(s,e) ((s).find(e)!=(s).end())
#define all(v) (v).begin(), (v).end()
#define each(s,itr) for(auto (itr) = s.begin(); (itr) != s.end(); (itr)++)
#define sum(v) accumulate(all(v), (0LL))
#define isin(a, b, c) (b <= a && a <= c)
#define println cout << "\n";
#define sz(v) (int)v.size()
#define bin(x) static_cast<bitset<16> >(x)

/* alias */
template<class T> using vec = vector<T>;
typedef vector<int> vi;
typedef pair<int, int> pi;
typedef tuple<int, int, int> ti;
typedef map<int, int> mi;
typedef set<int> si;

/* constant */
const int inf = 1LL << 62;
const int mod = 1e9 + 7;
const int dx[8]={1,0,-1,0,-1,1,-1,1};
const int dy[8]={0,1,0,-1,-1,-1,1,1};
const string alphabet = "abcdefghijklmnopqrstuvwxyz";

/* io_method */
int input(){int tmp;cin >> tmp;return tmp;}
string raw_input(){string tmp;cin >> tmp;return tmp;}
template<class T> void printx(T n){cout << n;}
template<class T, class U> void printx(pair<T, U> p){cout << "(" << p.first << "," << p.second << ")";}
template<class T, class U, class V> void printx(tuple<T, U, V> t){cout << "{" << get<0>(t) << "," << get<1>(t) <<"," << get<2>(t) << "}" << endl;}
template<class T> void printx(vector<T> v){cout << "{";rep(i,0,v.size()){printx(v[i]);if(i != v.size()-1)printx(",");}cout << "}";}
template<class T> void print(T n){printx(n);cout << endl;}
template<class T> void print(set<T> s){cout << "{";each(s, e){if(e != s.begin()) printx(",");printx(*e);}cout << "}" << endl;}
template<class T, class U> void print(map<T, U> mp){cout << "{";each(mp, e){cout << "(" << e -> first << "," << e -> second << ")";}cout << "}" << endl;}
template<class T> void printans(vec<T> v){rep(i,0,sz(v)){cout << v[i] << (i == sz(v) - 1 ? "" : " ");}cout << endl;}

/* general_method */
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
template<class T>T cut(T &a, int l, int r){return T(a.begin()+l, a.begin()+r);}

/* main */

int n;
vi arr;
void in(){
    cin >> n;
    rep(i,0,n) arr.push_back(input());
}

void solve(){

    vi ans;
    rep(i,0,n){
        revrep(j,n - 1 - i, -1){
            if(arr[j] - 1 == j){
                ans.push_back(arr[j]);
                vi tmp = cut(arr, 0, j);
                vi b = cut(arr, j + 1, sz(arr));
                for(int e : b) tmp.push_back(e);
                arr = tmp;
                break;
            }
        }
    }

    if(sz(arr) > 0){
        print(-1);
        return ;
    }

    reverse(all(ans));
    printans(ans);

}

signed main(){

    cin.tie(0);
    ios::sync_with_stdio(false);
    in();
    solve();

}

Score : 400 points

Problem Statement

Snuke has an empty sequence a.

He will perform N operations on this sequence.

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

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

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq b_i \leq N

Input

Input is given from Standard Input in the following format:

N
b_1 \dots b_N

Output

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

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

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

After the first operation: (1)

After the second operation: (1,1)

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

Sample Input 2

2
2 2

Sample Output 2

-1

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

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1


#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
    int n, a, b; cin >> n >> a >> b;
    int P[n]; for (int i = 0; i < n; i++) cin >> P[i];

    int lis[n] = {};
    fill(lis, lis+n, 1<<30);
    for (int i = 0; i < n; i++)
        *lower_bound(lis, lis+n, P[i]) = P[i];
    vector<int> s;
    int m = lower_bound(lis, lis+n, 1<<30) - lis - 1;
    // for (int i = 0; i <= m; i++) cerr << lis[i] << ' '; cerr << endl;
    int prevv = 1<<30;
    for (int i = n-1; i >= 0; i--) {
        if (lis[m] <= P[i] && P[i] < prevv) {
            s.push_back(i);
            prevv = P[i];
            m--;
        }
    }
    // for (int x : s) cerr << x << ' '; cerr << endl;
    reverse(s.begin(), s.end());
    bool in_lis[n] = {};
    for (int i : s) in_lis[i] = true;
    int acc_min[n], acc_max[n];
    int temp = 1<<30;
    for (int i = n-1; i >= 0; i--) {
        if (in_lis[i]) temp = min(temp, P[i]);
        acc_min[i] = temp;
    }
    temp = 0;
    for (int i = 0; i < n; i++) {
        if (in_lis[i]) temp = max(temp, P[i]);
        acc_max[i] = temp;
    }
    long long ans = 0;
    for (int i = 0; i < n; i++) {
        if (in_lis[i]) continue;
        auto it = lower_bound(s.begin(), s.end(), i);
        if (it != s.end() && P[i] > P[*it]) ans += a;
        else if (it != s.begin() && P[i] < P[*prev(it)]) ans += b;
    }
    cout << ans << endl;
}

Score : 1000 points

Problem Statement

You are given a permutation p = (p_1, \ldots, p_N) of \{ 1, \ldots, N \}.
You can perform the following two kinds of operations repeatedly in any order:

Pay a cost A. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the left by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, p_r with p_{l + 1}, p_{l + 2}, \ldots, p_r, p_l, respectively.

Pay a cost B. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the right by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, p_r with p_r, p_l, \ldots, p_{r - 2}, p_{r - 1}, respectively.

Find the minimum total cost required to sort p in ascending order.

Constraints

All values in input are integers.

1 \leq N \leq 5000

1 \leq A, B \leq 10^9

(p_1 \ldots, p_N) is a permutation of \{ 1, \ldots, N \}.

Input

Input is given from Standard Input in the following format:

N A B
p_1 \cdots p_N

Output

Print the minimum total cost required to sort p in ascending order.

Sample Input 1

3 20 30
3 1 2

Sample Output 1

20

Shifting (p_1, p_2, p_3) to the left by one results in p = (1, 2, 3).

Sample Input 2

4 20 30
4 2 3 1

Sample Output 2

50

One possible sequence of operations is as follows:

Shift (p_1, p_2, p_3, p_4) to the left by one. Now we have p = (2, 3, 1, 4).

Shift (p_1, p_2, p_3) to the right by one. Now we have p = (1, 2, 3, 4).

Here, the total cost is 20 + 30 = 50.

Sample Input 3

1 10 10
1

Sample Output 3

0

Sample Input 4

4 1000000000 1000000000
4 3 2 1

Sample Output 4

3000000000

Sample Input 5

9 40 50
5 3 4 7 6 1 2 9 8

Sample Output 5

220


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

#define rep(i,n) for(int i=0; i<(n); ++i)
#define rrep(i,n) for(int i=1; i<=(n); ++i)
#define drep(i,n) for(int i=(n)-1; i>=0; --i)
#define foreach(it, v) for(typeof(v.begin()) it=v.begin(); it!=v.end(); ++it)
#define pb push_back
#define sz(x) (int)(x).size()
#define fi first
#define se second

typedef unsigned int uint;
typedef long long int ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vpii;
typedef set<int> si;

//MOD//
const ll MOD = 1000000007;
struct big;
big ex(big a, ll tms);
typedef struct big{
  ll val;
  big():val(0){}
  big(ll val):val((val%MOD+MOD)%MOD){}
  big& operator += (const big& obj){ (val+=obj.val)%=MOD; return *this;}
  big& operator -= (const big& obj){ (val+=MOD-obj.val)%=MOD; return *this;}
  big& operator *= (const big& obj){ (val*=obj.val)%=MOD; return *this;}
  big& operator /= (const big& obj){ (val*=ex(obj,MOD-2).val)%=MOD; return *this;}
  big operator + (const big& obj)const{ return big(*this) += obj;}
  big operator - (const big& obj)const{ return big(*this) -= obj;}
  big operator * (const big& obj)const{ return big(*this) *= obj;}
  big operator / (const big& obj)const{ return big(*this) /= obj;}
  bool operator < (const big& obj)const{ return val < obj.val;}
  bool operator == (const big& obj)const{ return val == obj.val;}
} big;
istream& operator >> (istream& i, big& obj){ i>>obj.val; return i;}
ostream& operator << (ostream& o, const big& obj){ o<<obj.val; return o;}
big ex(big obj, ll tms){
  if(!tms) return 1;
  big ret = ex(obj, tms/2);
  ret *= ret;
  return (tms&1) ? ret*obj : ret;
}
//MOD//

ll pow(ll n, int m){
  if(!m) return 1;
  ll ret = pow(n, m/2);
  ret *= ret;
  return (m&1) ? ret*n : ret;
}

template <class F, class T>
void convert(const F &f, T &t){
  stringstream ss;
  ss << f;
  ss >> t;
}

int N,M;
int c[200001];

//big jst[200000];
big cnt[200001];

big s[200001];

int main(){

  scanf("%d",&N);
  int bef = -1;
  int cc;
  rep (i,N) {
    scanf("%d", &cc);
    if (cc != bef) {
      c[M] = cc;
      bef = cc;
      ++M;
    }
  }

  rep (i,M) {
    big cntbef = i==0 ? 1 : cnt[i-1];
    cnt[i] = cntbef + s[c[i]];
    s[c[i]] += cntbef;
  }

  cout << cnt[M-1] << endl;

  return 0;
}

Score : 700 points

Problem Statement

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

Snuke will perform the following operation zero or more times:

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

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

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
C_1
:
C_N

Output

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

Sample Input 1

5
1
2
1
2
2

Sample Output 1

3

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

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

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

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

Sample Input 2

6
4
2
5
4
2
4

Sample Output 2

5

Sample Input 3

7
1
3
1
2
3
3
2

Sample Output 3

5


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

const int MOD = 1000000007;
const int INF = 999999999;

int main(){
   int N, M;
   cin >> N >> M;
   vector<P> A(N);
   rep(i, N){
      cin >> A[i].first >> A[i].second;
   }
   sort(A.begin(), A.end());
   /*rep(i, N){
      cout << A[i].first << endl;
   }*/
   int ans = 0;
   rep(i, N){
      if(M > 0){
         if(A[i].second >= M){
            ans += A[i].first * M;
            M = 0;
         }else{
            ans += A[i].first * A[i].second;
            M -= A[i].second;
         }
      }else{
         break;
      }
   }
   cout << ans << endl;
return 0;}

Score : 300 points

Problem Statement

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

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

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

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

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

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

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

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

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

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


#include <bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < (int)(n); i++)
using namespace std;
using ll = long long;
using P = pair<int, int>;
using vi = vector<int>;
using vc = vector<char>;
using vs = vector<string>;
using vll = vector<long long>;
using vvi = vector<vector<int>>;
using vvc = vector<vector<char>>;
using vvll = vector<vector<long long>>;
template<class T> inline bool chmax(T &a, T b) { if (a<b) {a=b; return 1;} return 0;}
template<class T> inline bool chmin(T &a, T b) { if (b<a) {a=b; return 1;} return 0;}

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

    int n, m;
    cin >> n >> m;
    vector<P> ab(n);
    rep(i, n) {
        int a, b;
        cin >> a >> b;
        ab[i] = P(a, b);
    }
    sort(ab.begin(), ab.end());
    ll ans = 0;
    for (auto p : ab) {
        if (m <= 0) break;
        ans += (ll)p.first * min((ll)m, (ll)p.second);
        m -= min(m, p.second);
    }
    cout << ans << endl;

}


#include <stdio.h>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;

static const long MAX = 1e5 + 3;
int n, m, B[MAX];
long A[MAX], C[MAX][2], c, ans;

long h(long key, long i) {
    long r = (key % MAX + i * (1 + key % (MAX - 1))) % MAX;
    return r;
}

void insert(long key, long value) {
    long i = 0;

    while ( true ) {
        if ( C[h(key, i)][0] == key ) {
            break;
        } else if ( C[h(key, i)][0] ) {
            i++;
        } else {
            C[h(key, i)][0] = key;
            C[h(key, i)][1] = value;
            break;
        }
    }
}

long find(long key) {
    long i = 0;

    while ( true ) {
        if ( C[h(key, i)][0] == key ) {
            return C[h(key, i)][1];
            break;
        } else if ( C[h(key, i)][0] ) {
            i++;
        } else {
            return 0;
            break;
        }
    }
}

int main() {
    scanf("%d %d", &n, &m);

    for ( int i = 0; i < n; i++ ) {
        scanf("%ld %d", &A[i], &B[i]);
    }

    for ( int i = 0; i < n; i++ ) {
        scanf("%ld %d", &A[i], &B[i]);
        insert(A[i], B[i]);
    }

    c = 0;
    ans = 0;

    while ( m > 0 ) {
        m -= find(c);
        ans += c * find(c);
        c++;
    }

    ans += (c - 1) * m;
    printf("%ld\n", ans);
    return 0;
}


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

typedef pair<long long int, int> P;
int n, m;
priority_queue<P, vector<P>, greater<P>> que;
int main()
{
    cin >> n >> m;
    for (int i = 0; i < n; i++)
    {
        long long int x;
        int y;
        cin >> x >> y;
        que.push(P(x, y));
    }
    long long int ans = 0;
    while (m)
    {
        P p = que.top();
        que.pop();
        if (p.second > m)
        {
            ans += p.first * m;
            m = 0;
        }
        else
        {
            ans += p.first * p.second;
            m -= p.second;
        }
        cout << ans << endl;
    }
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main(){
  string S;
  cin >> S;
  int n = S.size();
  int t=0;
  int ans=0;
  while(t==0){
    t = 1;
    for(int i=0;i<n-1;i++){
      if(S[i]!=S[i+1]){
        S.erase(i,2);
        t = 0;
        ans++;
        ans++;
        break;
      }
      n = S.size();
    }
  }
  cout << ans << endl;
}

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

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

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

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

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

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

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


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

int main(){

    string s;
    cin >> s;

    int ans = 0;
    for (int i=0; i<s.size(); i++){
        char lbuf = s.at(i), rbuf = s.at(min(i+1, (int)(s.size()-1)));

        if (lbuf != rbuf){
            s.at(min(i+1, (int)(s.size()-1))) = s.at(max(0, i-1));;
            ans += 2;
        }
//        cout << i << endl;      // debug
    }

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


#include <bits/stdc++.h>

typedef long long ll;
using namespace std;

int main() {
    string S;
    cin >> S;
    int a[2];
    int len = S.length();
    for (int i = 0; i < len; i++) {
        a[S[i] - '0']++;
    }
    cout << min(a[0], a[1]) * 2 << endl;
}


#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <iomanip>
#include <set>
#include <ctime>
#include <tuple>
#include <bitset>
#include <assert.h>
#include <deque>
using namespace std;

/*
using PAIR = pair<string, int>;
sort(sp.begin(), sp.end(), [](PAIR l, PAIR r){
        return l.first<r.first || (l.first==r.first && l.second > r.second);
        });
*/

typedef long long ll;

#define fi first
#define se second
#define rep(i, n) for (ll i = 0; i < n; i++)
#define debugA() cerr << "AAAAA" << endl
#define debug_() cerr << "-------------" << endl
#define debug(x) cerr << #x << ": " << x << endl
#define debug_vec(v)                   \
    for (int i = 0; i < v.size(); i++) \
    {                                  \
        cout << v[i] << " ";           \
    }                                  \
    cout << endl;
#define debug_vec2(v)                         \
    for (int i = 0; i < v.size(); i++)        \
    {                                         \
        for (int j = 0; j < v[i].size(); j++) \
        {                                     \
            cout << v[i][j] << " ";           \
        }                                     \
        cout << endl;                         \
    }

using Graph = vector<vector<int>>;
using P = pair<int, int>;
using P1 = pair<int, pair<int, int>>; // クラスカル法とかで、{cost, {from, to}}的に使う。
const int INF = 1001001001;
const double pi = acos(-1);

class UnionFind
{
public:
    // 親の番号を格納する。親だった場合は -(その集合のサイズ)とする。
    vector<int> Parent;

    // 作るときはParentの値を全て-1にする。
    UnionFind(int N)
    {
        Parent = vector<int>(N, -1);
    }

    // Aがどのグループに所属しているか調べる。
    int root(int A)
    {
        if (Parent[A] < 0)
            return A;
        return Parent[A] = root(Parent[A]);
    }

    // 自分のいる頂点の数をイラべる。
    int size(int A)
    {
        return -Parent[root(A)]; // 親を取ってきたい。
    }

    // AとBをくっつける。
    bool unite(int A, int B)
    {
        // root(A)をroot(B)にくっつける。
        A = root(A);
        B = root(B);
        if (A == B)
        {
            return false;
        }
        // 大きい方(A)に小さい方(B)をくっつけたい。
        // 大小が逆ならひっくり返す。
        if (size(A) < size(B))
        {
            swap(A, B);
        }

        // Aのサイズを更新する。
        Parent[A] += Parent[B];
        // Bの親をAに変更する。
        Parent[B] = A;
        return true;
    }
};

int main()
{
    int n, m;
    cin >> n >> m;
    vector<pair<int, int>> b(m);
    for (int i = 0; i < m; i++)
    {
        int x, y;
        cin >> x >> y;
        x--;
        y--;
        b[i] = {x, y};
    }
    vector<ll> ans(m, 0);
    UnionFind tree(n);
    ans[m - 1] = n * (n - 1) / 2;
    for (int i = 0; i < m - 1; i++)
    {
        int x = b[m - 1 - i].fi;
        int y = b[m - 1 - i].se;
        if (tree.root(x) == tree.root(y))
        {
            ans[m - 2 - i] = ans[m - 1 - i];
        }
        else
        {
            ans[m - 2 - i] = ans[m - 1 - i] - tree.size(x) * tree.size(y);
            tree.unite(x, y);
        }
    }
    for (int i = 0; i < m; i++)
    {
        cout << ans[i] << endl;
    }

    return 0;
}

Score : 400 points

Problem Statement

There are N islands and M bridges.

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

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

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

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

Sample Input 1

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

Sample Output 1

0
0
4
5
6

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

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


/*
URL_HERE
*/
/*

*/
#ifdef _WIN32
#pragma warning(disable:4996)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <unordered_map>
using namespace std;

FILE* _fin = stdin;
FILE* _fout = stdout;
#define PI 3.141592653589793238462643383279502884197169399375105820974
#define ten5p1 100001
#define ten6p1 1000001
#define ten8p1 100000001
#define ten9p1 1000000001
#define uint unsigned int
#define ll long long
#define ull unsigned long long
#define rep(var,n) for(int var=0;var<n;++var)
#define repi(n) rep(i,n)
#define repj(n) rep(j,n)
#define repi1(n) for(int i=1;i<n;++i)
#define repj1(n) for(int j=1;j<n;++j)
int _min(int a, int b) { return a <= b ? a : b; }
int _min(ll a, ll b) { return a <= b ? a : b; }
int _max(int a, int b) { return a >= b ? a : b; }
int _max(ll a, ll b) { return a >= b ? a : b; }
void zero(int* data, int n) { memset(data, 0, sizeof(int) * n); }
void zero(ll* data, int n) { memset(data, 0, sizeof(ll) * n); }
void zero(char* data, int n) { memset(data, 0, sizeof(char) * n); }
char readc() { char var; fscanf(_fin, "%c", &var); return var; }
int readi() { int var; fscanf(_fin, "%d", &var); return var; }
double readlf() { double var; fscanf(_fin, "%lf", &var); return var; }
ll readll() { ll var; fscanf(_fin, "%lld", &var); return var; }
void repread(int* data, int n) { repi(n) data[i] = readi(); }
void repread(ll* data, int n) { repi(n) data[i] = readll(); }
int reads(char* str, int maxsize)
{
	for (;;) { if (fgets(str, maxsize, _fin) == NULL) break; if (str[0] != '\n' && str[0] != '\r') break; }
	int slen = strlen(str); if (slen == 0) return 0;
	if (str[slen - 1] == '\n' || str[slen - 1] == '\r') str[--slen] = 0;
	return slen;
}

#define writec(var) fprintf(_fout,"%c",var)
#define writecsp(var) fprintf(_fout,"%c ",var)
#define writecln(var) fprintf(_fout,"%c\n",var)
#define writei(var) fprintf(_fout,"%d",var)
#define writeisp(var) fprintf(_fout,"%d ",var)
#define writellsp(var) fprintf(_fout,"%lld ",var)
#define writeiln(var) fprintf(_fout,"%d\n",var)
#define writellln(var) fprintf(_fout,"%lld\n",var)
#define writeulln(var) fprintf(_fout,"%llu\n",var)
#define writefln(var) fprintf(_fout,"%f\n",var)
#define writes(str) fprintf(_fout,"%s",str)
#define writesp() fprintf(_fout," ")
#define writeln() fprintf(_fout,"\n")
#define RUN_LOCAL(testfilename) {_fin = fopen(testfilename, "r"); if(_fin==NULL) _fin=stdin;}
#define swap(type,a, b) {type t=a;a=b;b=t;}
#define sort(data,n) std::sort(data,data+n)
//#define mod(a,b) b==0 ? 0 : a==0 ? 0 :(a>0 ? a%b : b + a % b) //what the hell is this...
ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b); }
ll lcm(ll a, ll b) { ll g = gcd(a, b); return (a / g) * b; }
void reverse(char* data, int n) { int k = n >> 1; repi(k) { char tmp = data[i]; data[i] = data[n - i - 1]; data[n - i - 1] = tmp; } }
void reverse(int* data, int n) { int k = n >> 1; repi(k) { int tmp = data[i]; data[i] = data[n - i - 1]; data[n - i - 1] = tmp; } }

#define _Vec(type, name) \
struct name { type* data; int size; int n; };\
void init(name* t, int size) { t->data = (type*)malloc(sizeof(type) * size); t->size = size; t->n = 0; }\
void resize(name* t) { int ns = t->size * 1.2f; t->data = (type*)realloc(t->data, sizeof(type) * ns); t->size = ns; }\
void add(name* t, type val) { if (t->n >= t->size) resize(t); int k = t->n; t->data[k] = val; t->n = k + 1; }\
void free(name* t) { free(t->data);}
_Vec(int, Veci)
_Vec(long long, Vecll)
_Vec(char*, Vecs)

#define _ispal(type, name) int name(type* a, type* b, int n){repi(n){if (a[i] != b[n - i - 1]){return 0;}}return 1;}
_ispal(int, ispali)
_ispal(char, ispalc)

#define _Pair(type, name) struct name{type x, y;}; \
int cmp_##name(const void* _a, const void* _b)\
{\
	name* a = (name*)_a;name* b = (name*)_b;\
	if (a->x < b->x) return -1;\
	else\
	{\
		if (a->x == b->x)\
		{\
			if (a->y == b->y) return 0;\
			if (a->y < b->y) return -1;\
			else return 1;\
		}\
		else\
		{\
			return 1;\
		}\
	}\
}\
void sort_##name(name* d, int n){qsort(d, n, sizeof(name), cmp_##name);}
	_Pair(int, Pairi)

	int cmp_Str(const void* _a, const void* _b) { char* a = *((char**)_a); char* b = *((char**)_b); return strcmp(a, b); }
void sort_Str(char** str, int n) { qsort(str, n, sizeof(char*), cmp_Str); }

ll expmod(ll x, ll n, ll m) {
	ll ans = 1;
	for (; n;) {
		if (n & 1) ans = (ans * x) % m;
		x = (x * x) % m;
		n >>= 1;
	}
	return ans;
}

ll combmod(ll n, ll k, ll m) {
	ll ret = 1;
	ll div = 1;
	for (ll i = 0; i < k; ++i) {
		ret = (ret * (n - i) % m) % m;
		div = (div * (i + 1)) % m;
	}
	div = expmod(div, m - 2, m) % m;
	return (ret * div) % m;
}

int next_perm(int* data, int n)
{
	//find first i,i+1 where d[i]<d[i+1]
	int rootidx = -1;
	for (int i = n - 2; i >= 0; --i)
	{
		if (data[i] < data[i + 1])
		{
			rootidx = i;
			break;
		}
	}

	if (rootidx == -1) return 0;

	int ceilingidx = rootidx + 1;
	//find smallest d[x] after d[rooti] where d[x]>d[rooti]
	for (int i = rootidx + 2; i < n; ++i)
	{
		if (data[i] > data[rootidx] && data[i] < data[ceilingidx])
		{
			ceilingidx = i;
		}
	}

	swap(int, data[rootidx], data[ceilingidx]);
	sort(&data[rootidx + 1], n - rootidx - 1);
	return 1;
}
int count_digits(ll a)
{
	int k = 0;
	for (;;)
	{
		if (a == 0)break;
		k++;
		a /= 10;
	}
	return k;
}

/*
use only when val EXISTS in data
*/
int bs_exists(int* data, int n, int val)
{
	int left = 0;
	int right = n - 1;
	for (; left < right;)
	{
		int mid = (left + right + 1) >> 1;
		if (data[mid] <= val) left = mid;
		else right = mid - 1;
	}
	return right;
}
//------------------------------------------

//------------

void dfs(int* bestmana, int currentmana, int* l, int nl, int maxnl, int a, int b, int c,int tA,int tB,int tC)
{
	if (nl == maxnl)
	{
		//gotta make sure at least 1 stick was added
		if (a == 0 || b == 0 || c == 0)return;
		int totalmanacost = abs(a - tA) + abs(b - tB) + abs(c - tC);//this makes it so that lengths match
		totalmanacost += currentmana;
		if (totalmanacost < *bestmana)
		{
			*bestmana = totalmanacost;
		}
		return;
	}

	dfs(bestmana, currentmana, l, nl + 1, maxnl, a , b, c, tA, tB, tC);//dont use stick
	dfs(bestmana, currentmana + 10, l, nl + 1, maxnl, a + l[nl], b, c, tA, tB, tC);//add stick to a
	dfs(bestmana, currentmana + 10, l, nl + 1, maxnl, a, b + l[nl], c, tA, tB, tC);//add stick to b
	dfs(bestmana, currentmana + 10, l, nl + 1, maxnl, a, b, c + l[nl], tA, tB, tC);//add stick to c
}

int main()
{

	RUN_LOCAL("xxtop2_0.txt");
	int n = readi();
	int a = readi();
	int b = readi();
	int c = readi();
	static int l[10];
	repread(l, n);

	int bestmana = 1e9;
	dfs(&bestmana, 0, l, 0, n, 0, 0, 0, a, b, c);
	writeiln(bestmana);//initial placement of sticks are not considered joining
	return 0;
}

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


#include <bits/stdc++.h>

using namespace std;

int main() {
	int n, k, a[55], p = 99;
	cin >> n >> k;
	for (int i = 0; i < n; i++)
		cin >> a[i];
	stringstream s;
	for (int i = 0; i < k + 1; i++) {
		int m = 111, x;
		for (int j = 0; j < n; j++)
			if (j != p && a[j] < m) m = a[x = j];
		if (!m) {
			cout << -1 << endl;
			return 0;
		}
		for (int j = 0; j < n; j++)
			if (j != p && j != x)
				s << j + 1 << ' ', a[j]--;
		s << x + 1 << ' ', a[x]--;
		p = x;
	}
	cout << n + (n - 1)*k << '\n' << s.str() << endl;
	return 0;
}

Score : 1000 points

Problem Statement

Snuke participated in a magic show.

A magician prepared N identical-looking boxes.
He put a treasure in one of the boxes, closed the boxes, shuffled them, and numbered them 1 through N.

Since the boxes are shuffled, now Snuke has no idea which box contains the treasure.
Snuke wins the game if he opens a box containing the treasure.
You may think that if Snuke opens all boxes at once, he can always win the game.
However, there are some tricks:

Snuke must open the boxes one by one. After he opens a box and checks the content of the box, he must close the box before opening the next box.

He is only allowed to open Box i at most a_i times.

The magician may secretly move the treasure from a closed box to another closed box, using some magic trick.
For simplicity, assume that the magician never moves the treasure while Snuke is opening some box.
However, he can move it at any other time (before Snuke opens the first box, or between he closes some box and opens the next box).

The magician can perform the magic trick at most K times.

Can Snuke always win the game, regardless of the initial position of the treasure and the movements of the magician?

Constraints

2 \leq N \leq 50

1 \leq K \leq 50

1 \leq a_i \leq 100

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 \cdots a_N

Output

If the answer is no, print a single -1.

Otherwise, print one possible move of Snuke in the following format:

Q
x_1 x_2 \cdots x_Q

It means that he opens boxes x_1, x_2, \cdots, x_Q in this order.

In case there are multiple possible solutions, you can output any.

Sample Input 1

2 1
5 5

Sample Output 1

7
1 1 2 1 2 2 1

If Snuke opens the boxes 7 times in the order 1 \rightarrow 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2 \rightarrow 1, he can always find the treasure regardless of its initial position and the movements of the magician.

Sample Input 2

3 50
5 10 15

Sample Output 2

-1


#include<iostream>
using namespace std;
int main()
{
    // 整数の入力
    int a,b;
    cin >> a >> b;
    int c;
    if (b % a == 0){
        c = a + b;
    } else
    {
        c = b - a;
    }
    cout << c << endl;
    return 0;
}

Score : 100 points

Problem Statement

You are given positive integers A and B.

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

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

4 12

Sample Output 1

16

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

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define MOD 1000000007
#define PI 3.141592653589793
const int INF = 100000000;
int dx[] = {0,1,-1,0,1,-1,1,-1};
int dy[] = {1,0,0,-1,1,-1,-1,1};

int main(){
    int n, m;
    cin >> n >> m;
    vector<int> v(m+1, 0);
    for(int i = 0; i < n; i++){
        int k;
        cin >> k;
        while(k--){
            int a;
            cin >> a;
            v[a]++;
        }
    }
    int ans = 0;
    for(auto i: v)
        if(i == n)
            ans++;
    cout << ans << endl;
}

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

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

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

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

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

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

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

Constraints

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

1

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

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3


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

int main() {
    int a,b;
    cin>>a>>b;
    vector<int> vec(b,0);
    rep(i,a){
        int c;
        cin>>c;
        for(int j=0;j<c;j++){
            int d;
            cin>>d;
            d--;
            vec.at(d)++;
    }
    }

    int count =0;
    rep(i,b){
        if(vec.at(i)==a){
            count++;
        }
    }
    cout<<count<<endl;
}


#include<iostream>
using namespace std;

int main() {
	int N, M;
	int K[30];
	int A[30][30];
	int like[30];
	int ans = 0;

	for (int i = 0; i < 30; i++) {
		like[i] =0;
		for (int j = 0; j < 30; j++) {
			//A[i][j] = false;
		}
	}
	cin >> N >> M;
	for (int i = 0; i < N; i++) {
		cin >>K[i];
		for (int j = 0; j < K[i]; j++) {
			cin >> A[i][j];
		}
	}
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < K[i]; j++) {
			like[A[i][j]]++;
		}
	}

	for (int i = 0; i < M; i++) {
		if (like[i] == N) {
			ans++;
		}
	}

	printf("%d", ans);
}