#include<bits/stdc++.h>
#define INF (1e9)
#define N 105
#define M 16
using namespace std;
typedef pair<int,int> P;
int n,m,k,d[M],G[N][N],dp[(1<<M)];
map<int,int> to;

int bfs(){
  queue<P> q;
  fill(dp,dp+(1<<M),INF);
  dp[0]=0;
  q.push(P(0,0));
  while(!q.empty()){
    P t=q.front(); q.pop();
    int cost=t.first,node=t.second;
    if(node==(1<<m)-1)return cost;
    if(dp[node]<cost)continue;
    for(int i=0;i<k;i++){
      int next=(1<<m)-1;
      for(int j=0;j<m;j++)
	if(!(node&(1<<j))&&to.count(G[d[j]][i]))
	  next=next&~(1<<to[G[d[j]][i]]);
      if(dp[next]>cost+1){
	dp[next]=cost+1;
	q.push(P(dp[next],next));
      }
    }
  }
}

int main(){
  cin>>n>>m>>k;
  for(int i=0;i<m;i++){
    cin>>d[i]; d[i]--;
    to[d[i]]=i;
  }
  for(int i=0;i<n;i++)
    for(int j=0;j<k;j++){
      cin>>G[i][j];
      G[i][j]--;
    }
  cout<<bfs()<<endl;
  return 0;
}

真っ暗な部屋

目を覚ますと、A君は真っ暗な部屋の中にいた。
どうやらA君は N 個の部屋から構成されたダンジョンに迷い込んでしまったようだ。
あなたはA君がどの部屋に迷い込んだのかを知ることはできなかったが、幸いにもダンジョンのマップを手に入れることができた。
A君の進むべき道を示し明るい部屋に導こう。

N 個の部屋のうち M 個の部屋が真っ暗な部屋であり、それぞれ D_1, D_2, ..., D_M 番目の部屋が真っ暗な部屋であることが分かっている。
また、全ての部屋からちょうど K 本の一方通行の道が順に並んでおり、i 番目の部屋から出る道はそれぞれ
v_{i,1}, v_{i,2}, ..., v_{i,K} 番目の部屋に繋がっている。
あなたは、A君に対し今いる部屋から a_1, a_2, ..., a_l 番目の道を順に進ませることができる。
ただし、A君は明るい部屋に到達したらそれ以降の指示は無視する。
あなたは、指示の前後においてA君が今いる部屋の情報を知ることはできないため、A君がどの部屋にいたとしても明るい部屋に辿り着けるような指示列を伝えなければならない。

そのような指示のうち、最も短いものの長さを答えよ。

Constraints

2 ≤ N ≤ 100

1 ≤ M ≤ min(16, N − 1)

1 ≤ K ≤ N

1 ≤ D_i ≤ N

D_i は全て異なる

1 ≤ v_{i, j} ≤ N

全ての暗い部屋は少なくとも1つの明るい部屋に到達可能である

Input Format

入力は以下の形式で標準入力から与えられる。

N M K
D_1 D_2 ... D_M
v_{1,1} v_{1,2} ... v_{1,K}
v_{2,1} v_{2,2} ... v_{2,K}
...
v_{N,1} v_{N,2} ... v_{N,K}

Output Format

答えを一行に出力せよ。

Sample Input 1

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

Sample Output 1

2

1, 1 という指示を出すと

A君の初期位置が部屋1である場合、2つ目の移動で部屋3に到達する

A君の初期位置が部屋2である場合、1つ目の移動で部屋3に到達する

Sample Input 2

3 2 2
1 2
2 3
1 2
2 1

Sample Output 2

3

2, 1, 2 という指示を出すと

A君の初期位置が部屋1である場合、1つ目の移動で部屋3に到達する

A君の初期位置が部屋2である場合、3つ目の移動で部屋3に到達する

Sample Input 3

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

Sample Output 3

3

非連結であるケースや、自己辺、多重辺があるケースに気をつけよう


#include<bits/stdc++.h>
using namespace std;
string t,p;
char c;
int i,j,k,l,x;
main(){
  for(cin>>t>>p;i<t.size();++i){
    if(t[i]==c&&t[i]!=p[j]){
      c='0';
      break;
    }
    if(t[i]==p[j])++j,c=t[i];
  }
  x=c-'0'?1:0;
  c='0';
  for(reverse(t.begin(),t.end()),reverse(p.begin(),p.end());k<t.size();++k){
    if(t[k]==c&&t[k]!=p[l]){
      c='0';
      break;
    }
    if(t[k]==p[l])++l,c=t[k];
  }
  x&=c-'0'?1:0;
  cout<<(x&&j==p.size()?"yes\n":"no\n");
}

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

C： たったひとつの部分列 - Unique Subsequence -

問題

ある日えびちゃんは、机の上に長さ n のテキスト文字列 T と長さ m のパターン文字列 P (m \leq n) が置かれていることに気づきました。えびちゃんは、文字列に現れる「たったひとつの部分列」が大好きであるため、 P が T のたったひとつの部分列であるかどうかをすぐに調査し始めました。

P が T のたったひとつの部分列であるという性質は以下のように表されます。ここで、文字列 X の i 文字目を X_i と書きます。

長さ m の数列 S = (s_1, ..., s_m) (ただし、 s_1 < s_2 < ... < s_m) で、各 i (i = 1, ..., m) について T_{s_i} = P_i である数列 S が一意に定まる。

調査を始めてから数時間、えびちゃんは文字列をぐっと睨んでいましたが、文字列が長すぎるために疲れてしまったようです。それを見かねたあなたは、えびちゃんを手伝ってあげることにしました。えびちゃんのために、 P が T のたったひとつの部分列であるならば “yes” を、そうでないならば “no” を出力するプログラムを作成してください。

入力形式

T
P

1 行目には、テキスト文字列 T が与えられる。
2 行目には、パターン文字列 P が与えられる。

制約

1 \leq |P| \leq |T| \leq 5 \times 10^5

T および P は英字小文字 ‘a’-’z’ で構成される。

出力形式

P が T のたったひとつの部分列であるならば “yes” を、そうでないならば “no” を1行に出力してください。

入力例1

aizucamp
azu

出力例1

yes

入力例2

abracadabra
rada

出力例2

no

入力例3

hokkaido
dekai

出力例3

no

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>
#define X first
#define Y second
#define pb push_back
#define eb pb
#define rep(X,Y) for(int X=0;X<(Y);++X)
#define reps(X,O,Y) for(int X=O;X<(Y);++X)
#define all(X) (X).begin(),(X).end()

using namespace std;
using ll=long long;

const int N=11234567;
int prime[N];

int main(){
	fill(prime,prime+N,1);
	prime[0]=prime[1]=0;
	rep(i,N)if(prime[i])for(int j=i+i;j<N;j+=i) prime[j]=0;
	// rep(i,10) cout<<prime[i];cout<<endl;
	int n;
	cin>>n;
	if(n<=2){ cout<<0<<endl; return 0;}
	int re=0;
	reps(i,3,n+1)if(prime[i] && prime[i+2]) ++re;
	cout<<re*2<<endl;
}

C: 素数

問題

ある日、素数が大好きなそすうさ君は $p + q$ が素数となるペア $(p, q)$ で遊んでいた。
そすうさ君は突然、このペアのうち、 $p$ と $q$ がともに $N$ 以下の素数であるペアがいくつあるか気になりだした。
そすうさ君に代わって個数を求めよ。

制約

入力値は全て整数である。

$1 \leq N \leq 10^7$

入力形式

入力は以下の形式で与えられる。

$N$

出力

ペアの個数を出力せよ。また、末尾に改行も出力せよ。

サンプル

サンプル入力 1

3

サンプル出力 1

2

ペアは $(2, 3), (3, 2)$ の二つである。

サンプル入力 2

20

サンプル出力 2

8


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

int main(){
  long long int mi = 100000000000,ma = -100000000000,a,n;
  cin >> n;
  for(int i=0;i<n;i++){
    cin >> a;
    ma = max(ma,a-mi);
    mi = min(mi,a);
  }
  cout<<ma<<endl;
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Maximum Profit

You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.

Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2, ... n-1$), and reports the maximum value of $R_j - R_i$ where $j > i$ .

Input

The first line contains an integer $n$. In the following $n$ lines, $R_t$ ($t = 0, 1, 2, ... n-1$) are given in order.

Output

Print the maximum value in a line.

Constraints

$2 \leq n \leq 200,000$

$1 \leq R_t \leq 10^9$

Sample Input 1

6
5
3
1
3
4
3

Sample Output 1

3

Sample Input 2

3
4
3
2

Sample Output 2

-1


#include <iostream>
#include<stdio.h>
using namespace std;
#define MAX 200000
#define mm  10000000000
typedef long long ll;
int L[MAX],R[MAX];
ll merge(int A[],int n,int left,int mid,int right)
{

    int i,j,k;
    ll cnt=0;
    int n1=mid-left;
    int n2=right-mid;
    for(i=0; i<n1; i++)L[i]=A[left+i];
    for(i=0; i<n2; i++)R[i]=A[mid+i];
    L[n1]=R[n2]=mm;
    i=0;
    j=0;
    for(k=left; k<right; k++)
    {
        if(L[i]<=R[j])
        {
            A[k]=L[i++];
        }
        else
        {
            A[k]=R[j++];
            cnt+=n1-i;//=mid+j-k-i;
        }
    }
    return cnt;

}
ll mergeSort(int A[],int n,int left, int right)
{
    int mid;
    ll v1,v2,v3;
    if(left+1<right)
    {
        mid=(left+right)/2;
        v1=mergeSort(A,n,left,mid);
        v2=mergeSort(A,n,mid,right);
        v3=merge(A,n,left,mid,right);
        return v1+v2+v3;
    }
    return 0;
}
int main()
{
    int A[MAX],n;
    scanf("%d",&n);
    for(int i=0; i<n; i++)
    {
        scanf("%d",&A[i]);
    }
    ll ans=mergeSort(A,n,0,n);
    cout<<ans<<endl;
    return 0;
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

The Number of Inversions

For a given sequence $A = \{a_0, a_1, ... a_{n-1}\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program:

bubbleSort(A)
cnt = 0 // the number of inversions
for i = 0 to A.length-1
for j = A.length-1 downto i+1
if A[j] < A[j-1]
swap(A[j], A[j-1])
cnt++

return cnt

For the given sequence $A$, print the number of inversions of $A$. Note that you should not use the above program, which brings Time Limit Exceeded.

Input

In the first line, an integer $n$, the number of elements in $A$, is given. In the second line, the elements $a_i$ ($i = 0, 1, .. n-1$) are given separated by space characters.

output

Print the number of inversions in a line.

Constraints

$ 1 \leq n \leq 200,000$

$ 0 \leq a_i \leq 10^9$

$a_i$ are all different

Sample Input 1

5
3 5 2 1 4

Sample Output 1

6

Sample Input 2

3
3 1 2

Sample Output 2

2


#include <cstdio>
#include <cstdlib>
#pragma warning(disable : 4996)
struct Node {
	int key;
	Node *p, *l, *r;
};
Node *root, *NIL;
void insert(int key_) {
	Node *x = root, *y = NIL, *z;
	z = (Node*)malloc(sizeof(Node));
	z->key = key_, z->l = NIL, z->r = NIL;
	while (x != NIL) {
		y = x;
		x = (z->key < x->key) ? x->l : x->r;
	}
	z->p = y;
	if (y == NIL) root = z;
	else if (z->key < y->key) y->l = z;
	else y->r = z;
}
void walk1(Node *x) { if (x == NIL) return; walk1(x->l); printf(" %d", x->key); walk1(x->r); }
void walk2(Node *x) { if (x == NIL) return; printf(" %d", x->key); walk2(x->l); walk2(x->r); }
int n, v; char c[8];
int main() {
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%s", &c);
		if (c[0] == 'i') scanf("%d", &v), insert(v);
		else walk1(root), printf("\n"), walk2(root), printf("\n");
	}
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Binary Search Tree I

Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.

Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$.

The following figure shows an example of the binary search tree.

For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree.

1 insert(T, z)
2 y = NIL // parent of x
3 x = 'the root of T'
4 while x ≠ NIL
5 y = x // set the parent
6 if z.key < x.key
7 x = x.left // move to the left child
8 else
9 x = x.right // move to the right child
10 z.p = y
11
12 if y == NIL // T is empty
13 'the root of T' = z
14 else if z.key < y.key
15 y.left = z // z is the left child of y
16 else
17 y.right = z // z is the right child of y

Write a program which performs the following operations to a binary search tree $T$.

insert $k$: Insert a node containing $k$ as key into $T$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given.

Output

For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


#include<iostream>
#include<cstdio>
#define MAX 2000000+5
using namespace std;
int heap[MAX];
int num;
void maxheapify(int i){
	int largest;
	int left=i*2;int right=i*2+1;
	if(left<=num&&heap[left]>heap[i]){
		largest=left;
	}else{
		largest=i;
	}
	if(right<=num&&heap[largest]<heap[right]){
		largest=right;
	}
	if(largest!=i){
		swap(heap[largest],heap[i]);
		maxheapify(largest);
	}
	return;
}
void insert(int i){
num++;
heap[num]=i;
int t=num;
while(t>1&&heap[t/2]<heap[t]){
	swap(heap[t],heap[t/2]);
	t=t/2;
}
return;
}
void extract(){
	cout<<heap[1]<<endl;
	heap[1]=heap[num];num--;
	maxheapify(1);
	return;
}
int main(){
	char s[10];
	num=0;
	while(scanf("%s",&s)){
		if(s[0]=='i') {
			int i;scanf("%d",&i);insert(i);
		}else if(s[0]=='e'&&s[1]=='x'){
			extract();
		}else break;

		}
	}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Priority Queue

A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations:

$insert(S, k)$: insert an element $k$ into the set $S$

$extractMax(S)$: remove and return the element of $S$ with the largest key

Write a program which performs the $insert(S, k)$ and $extractMax(S)$ operations to a priority queue $S$.
The priority queue manages a set of integers, which are also keys for the priority.

Input

Multiple operations to the priority queue $S$ are given. Each operation is given by "insert $k$", "extract" or "end" in a line. Here, $k$ represents an integer element to be inserted to the priority queue.

The input ends with "end" operation.

Output

For each "extract" operation, print the element extracted from the priority queue $S$ in a line.

Constraints

The number of operations $\leq 2,000,000$

$0 \leq k \leq 2,000,000,000$

Sample Input 1

insert 8
insert 2
extract
insert 10
extract
insert 11
extract
extract
end

Sample Output 1

8
10
11
2


#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main()
{
	priority_queue<int> Q;
	string S;
	while(true)
	{
		cin >> S;
		if (S == "end")
		{
			return 0;
		}
		else
		{
			if (S == "insert")
			{
				int a;
				cin >> a;
				Q.push(a);
			}
			else
			{
				cout << Q.top() << endl;
				Q.pop();
			}
		}
	}
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n)   FOR(i,0,n)
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pint;

struct rect{int ht;int pos;};
int tb[100001];
int area_rect(int size,int buf[]){
    stack<rect> st;
    int mx=0;
    buf[size]=0;
    rep(i,size+1){
        rect r;
        r.ht=buf[i];
        r.pos=i;
        if(st.empty()) st.push(r);
        else{
            if(st.top().ht<r.ht) st.push(r);
            else if (st.top().ht>r.ht){
                int ti=i;
                while(!st.empty()&&st.top().ht>=r.ht){
                    rect pre=st.top();st.pop();
                    int area=pre.ht*(i-pre.pos);
                    mx=max(mx,area);
                    ti=pre.pos;
                }
                r.pos = ti;
                st.push(r);
            }
        }
    }
    return mx;
}
int main(){
    int n;
    cin>>n;
    rep(i,n) cin>>tb[i];
    int mx=area_rect(n,tb);
    cout<<mx<<endl;
    return 0;
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Largest Rectangle in a Histogram

A histogram is made of a number of contiguous bars, which have same width.

For a given histogram with $N$ bars which have a width of 1 and a height of $h_i$ = $h_1, h_2, ... , h_N$ respectively, find the area of the largest rectangular area.

Constraints

$1 \leq N \leq 10^5$

$0 \leq h_i \leq 10^9$

Input

The input is given in the following format.

$N$

$h_1$ $h_2$ ... $h_N$

Output

Print the area of the largest rectangle.

Sample Input 1

8
2 1 3 5 3 4 2 1

Sample Output 1

12

Sample Input 2

3
2 0 1

Sample Output 2

2


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

#define MOD 1000000007
using ll = long long;

bool operator<(const pair<int, int>& a, const pair<int, int>& b) {
	if (a.first == b.first) {
		return a.second < b.second;
	}
	return a.first < b.first;
}

const int INF = (1LL << 31) - 1;
const int sqrtN = 512;

struct SqrtDecomposition {
	int N, K;
	vector<ll> data; //内部の値, どのタイミングで変更したか
	vector<ll> bucketSum;
	vector<ll> bucketAdd;
	SqrtDecomposition(int n) : N(n) {
		K = (N + sqrtN - 1) / sqrtN;
		data.assign(K*sqrtN, 0);
		bucketSum.assign(K, 0);
		bucketAdd.assign(K, 0);
	}

	// [s, t)
	void add(ll s, ll t, ll x) {
		for (int k = 0; k < K; ++k) {
			ll l = k * sqrtN, r = (k + 1) *sqrtN;
			if (r <= s || t <= l) continue;
			if (s <= l && r <= t) {
				bucketAdd[k] += x;
			}
			else {
				for (int i = max(s, l); i < min(t, r); ++i) {
					data[i] += x;
					bucketSum[k] += x;
				}
			}
		}
	}

	//[x, y)
	ll getSum(ll s, ll t) {
		ll sum = 0;
		for (int k = 0; k < K; ++k) {
			ll l = k * sqrtN, r = (k + 1)*sqrtN;
			if (r <= s || t <= l) continue;
			if (s <= l && r <= t) {
				sum += bucketSum[k] + bucketAdd[k] * sqrtN;
			}
			else {
				for (int i = max(s, l); i < min(t, r); ++i) {
					sum += data[i] + bucketAdd[k];
				}
			}
		}
		return sum;
	}
};
int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	ll n, q; cin >> n >> q;
	SqrtDecomposition sd(n);

	for (int i = 0; i < q; ++i) {
		ll com; cin >> com;
		if (com == 0) {
			ll s, t, x; cin >> s >> t >> x;
			sd.add(s, t+1, x);
		}
		else {
			ll x, y; cin >> x>> y;
			cout << sd.getSum(x, y+1) << endl;
		}
	}
	int a; cin >> a;
	return 0;
}

RSQ and RAQ

Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:

add(s, t, x): add x to as, as+1, ..., at.

getSum(s, t): report the sum of as, as+1, ..., at.

Note that the initial values of ai (i = 1, 2, . . . , n) are 0.

Input

n q
query1
query2
:
queryq

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:

0 s t x

or

1 s t

The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes getSum(s, t).

Output

For each getSum operation, print the sum;

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

1 ≤ s ≤ t ≤ n

0 ≤ x < 1000

Sample Input 1

3 5
0 1 2 1
0 2 3 2
0 3 3 3
1 1 2
1 2 3

Sample Output 1

4
8

Sample Input 2

4 3
1 1 4
0 1 4 1
1 1 4

Sample Output 2

0
4


// clang-format off
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define main signed main()
#define loop(i, a, n) for (int i = (a); i < (n); i++)
#define rep(i, n) loop(i, 0, n)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define prec(n) fixed << setprecision(n)
constexpr int INF = sizeof(int) == sizeof(long long) ? 1000000000000000000LL : 1000000000;
constexpr int MOD = 1000000007;
constexpr double PI = 3.14159265358979;
template<typename A, typename B> bool cmin(A &a, const B &b) { return a > b ? (a = b, true) : false; }
template<typename A, typename B> bool cmax(A &a, const B &b) { return a < b ? (a = b, true) : false; }
bool odd(const int &n) { return n & 1; }
bool even(const int &n) { return ~n & 1; }
template<typename T = int> T in() { T x; cin >> x; return x; }
template<typename T = int> T in(T &&x) { T z(forward<T>(x)); cin >> z; return z; }
template<typename T> istream &operator>>(istream &is, vector<T> &v) { for (T &x : v) is >> x; return is; }
template<typename A, typename B> istream &operator>>(istream &is, pair<A, B> &p) { return is >> p.first >> p.second; }
template<typename T> ostream &operator<<(ostream &os, const vector<vector<T>> &v) { int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "" : "\n"); return os; }
template<typename T> ostream &operator<<(ostream &os, const vector<T> &v) { int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "" : " "); return os; }
template<typename A, typename B> ostream &operator<<(ostream &os, const pair<A, B> &p) { return os << p.first << ' ' << p.second; }
template<typename Head, typename Value> auto vectors(const Head &head, const Value &v) { return vector<Value>(head, v); }
template<typename Head, typename... Tail> auto vectors(Head x, Tail... tail) { auto inner = vectors(tail...); return vector<decltype(inner)>(x, inner); }
// clang-format on

template<typename LSTTrait> class LazySegTree {
  using FoldMonoid = typename LSTTrait::FoldMonoid;
  using ActionMonoid = typename LSTTrait::ActionMonoid;
  using T = typename FoldMonoid::value_type;
  using Q = typename ActionMonoid::value_type;

  LSTTrait lstTrait; // apply :: (T, Q) -> T, pow :: (Q, int) -> Q
  FoldMonoid foldM;
  ActionMonoid actionM;
  int size = 1;
  vector<T> tree; // 1-indexed
  vector<Q> lazy; // 1-indexed

  void push(int i) {
    stack<pair<int, int>> s;
    for (int d = 1; i /= 2; d *= 2) s.emplace(i, d);
    for (int x, d; s.size(); s.pop()) {
      tie(x, d) = s.top();
      update(x * 2, lazy[x], d);
      update(x * 2 + 1, lazy[x], d);
      lazy[x] = actionM.id();
    }
  }

  void update(const int &i, const Q &x, const int &d) {
    tree[i] = lstTrait.apply(tree[i], lstTrait.pow(x, d));
    if (i < size) lazy[i] = actionM(lazy[i], x);
  }

  void build(int i) {
    for (int d = 2; i /= 2; d *= 2) tree[i] = lstTrait.apply(foldM(tree[i * 2], tree[i * 2 + 1]), lstTrait.pow(lazy[i], d));
  }

public:
  LazySegTree(const int &n = 0) {
    while (size < n) size *= 2;
    tree.assign(size * 2, foldM.id());
    lazy.assign(size, actionM.id());
  }

  LazySegTree(const int &n, const T &x) {
    while (size < n) size *= 2;
    tree.assign(size * 2, x);
    lazy.assign(size, actionM.id());
    for (int i = size - 1; i >= 1; i--) tree[i] = foldM(tree[i * 2], tree[i * 2 + 1]);
  }

  template<typename InputIterator> LazySegTree(InputIterator first, InputIterator last) {
    int n = distance(first, last);
    while (size < n) size *= 2;
    tree.resize(size * 2, foldM.id());
    lazy.assign(size, actionM.id());
    copy(first, last, tree.begin() + size);
    for (int i = size - 1; i >= 1; i--) tree[i] = foldM(tree[i * 2], tree[i * 2 + 1]);
  }

  void act(int l, int r, const Q &x) { // [l, r) += x
    int l0 = l += size, r0 = r += size;
    push(l0), push(r0 - 1);
    for (int d = 1; l < r; l /= 2, r /= 2, d *= 2) {
      if (l & 1) update(l++, x, d);
      if (r & 1) update(--r, x, d);
    }
    build(l0);
    build(r0 - 1);
  }

  T fold(int l, int r) { // [l, r)
    T accl = foldM.id(), accr = foldM.id();
    for (push(l += size), push((r += size) - 1); l < r; l /= 2, r /= 2) {
      if (l & 1) accl = foldM(accl, tree[l++]);
      if (r & 1) accr = foldM(tree[--r], accr);
    }
    return foldM(accl, accr);
  }
};

template<typename T> struct sumMonoid {
  using value_type = T;
  value_type id() { return 0; }
  value_type operator()(const value_type &a, const value_type &b) { return a + b; }
};

template<typename T> struct updateMonoid {
  using value_type = pair<bool, T>;
  value_type id() { return {false, T()}; }
  value_type operator()(const value_type &a, const value_type &b) { return b.first ? b : a; }
};

template<typename T> struct RSQ_RUQ_Trait {
  using FoldMonoid = sumMonoid<T>;
  using ActionMonoid = updateMonoid<T>;
  typename FoldMonoid::value_type apply(typename FoldMonoid::value_type t, typename ActionMonoid::value_type q) { return q.first ? q.second : t; }
  typename ActionMonoid::value_type pow(typename ActionMonoid::value_type q, const int &d) { return {q.first, q.second * d}; }
};

main {
  int n, q;
  cin >> n >> q;
  LazySegTree<RSQ_RUQ_Trait<int>> lst(n, 0);
  while (q--) {
    if (in()) {
      int s, t;
      cin >> s >> t;
      cout << lst.fold(s, t + 1) << endl;
    } else {
      int s, t, x;
      cin >> s >> t >> x;
      lst.act(s, t + 1, {true, x});
    }
  }
}

RSQ and RUQ

Write a program which manipulates a sequence $A$ = {$a_0, a_1, ..., a_{n-1}$} with the following operations:

$update(s, t, x)$: change $a_s, a_{s+1}, ..., a_t$ to $x$.

$getSum(s, t)$: print the sum of $a_s, a_{s+1}, ..., a_t$.

Note that the initial values of $a_i ( i = 0, 1, ..., n-1 )$ are 0.

Input

$n$ $q$
$query_1$
$query_2$
:
$query_q$

In the first line, $n$ (the number of elements in $A$) and $q$ (the number of queries) are given. Then, $i$-th query $query_i$ is given in the following format:

0 $s$ $t$ $x$

or

1 $s$ $t$

The first digit represents the type of the query. '0' denotes $update(s, t, x)$
and '1' denotes $find(s, t)$.

Output

For each $getSum$ query, print the sum in a line.

Constraints

$1 ≤ n ≤ 100000$

$1 ≤ q ≤ 100000$

$0 ≤ s ≤ t < n$

$-1000 ≤ x ≤ 1000$

Sample Input 1

6 7
0 1 3 1
0 2 4 -2
1 0 5
1 0 1
0 3 5 3
1 3 4
1 0 5

Sample Output 1

-5
1
6
8


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

using namespace std;

struct edge {int u,v,cost;};
edge cookies[100000000];

int V,E;
int par[1000000],rank[10000000];

void init(int n){
  for(int i=0;i<n;i++){
    par[i]=i;
    rank[i]=0;
  }
}

int find(int x){
  if(par[x]==x){
    return x;
  } else {
    return par[x]=find(par[x]);
  }
}

void unite(int x,int y){
  x=find(x);
  y=find(y);
  if(x==y) return;

  if(rank[x]<rank[y]){
    par[x]=y;
  } else {
    par[y]=x;
    if(rank[x]==rank[y]) rank[x]++;
  }
}

bool same(int x,int y){
  return find(x)==find(y);
}

bool comp(const edge& e1,const edge& e2){
  return e1.cost<e2.cost;
}

int kruskal(){
  sort(cookies,cookies+E,comp);
  init(V);
  int res=0;

  for(int i=0;i<E;i++){
    edge e=cookies[i];
    if(!same(e.u,e.v)){
      unite(e.u,e.v);
      res+=e.cost;
    }
  }
  return res;

}

int main(){
  scanf("%d%d",&V,&E);
  for(int i=0;i<E;i++){
    scanf("%d%d%d",&cookies[i].u,&cookies[i].v,&cookies[i].cost);
  }

  printf("%d\n",kruskal());

  return 0;

}

Minimum Spanning Tree

Find the sum of weights of edges of the Minimum Spanning Tree for a given weighted undirected graph G = (V, E).

Input

|V| |E|
s0 t0 w0
s1 t1 w1
:
s|E|-1 t|E|-1 w|E|-1

, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target verticess of i-th edge (undirected) and wi represents the weight of the i-th edge.

Output

Print the sum of the weights of the Minimum Spanning Tree.

Constraints

1 ≤ |V| ≤ 10,000

0 ≤ |E| ≤ 100,000

0 ≤ wi ≤ 10,000

The graph is connected

There are no parallel edges

There are no self-loops

Sample Input 1

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

Sample Output 1

3

Sample Input 2

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

Sample Output 2

5


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

using namespace std;
typedef pair<int, int> P;
static const int INF = 1e9;
static const int SIZE = 100001;

struct edge
{
	int to, cost;
};

vector<edge> G[SIZE];
int d[SIZE];
int n;

void bfs(int v)
{
	for (int i = 0; i < n; ++i)
	{
		d[i] = INF;
	}
	d[v] = 0;
	priority_queue < P, vector<P>, greater<P> > pque;
	pque.push(P(0, v));
	while (!pque.empty())
	{
		P p = pque.top();
		pque.pop();
		int vertex = p.second;
		for (int i = 0; i < G[vertex].size(); ++i)
		{
			edge e = G[vertex][i];
			if (d[e.to] > d[vertex] + e.cost)
			{
				d[e.to] = d[vertex] + e.cost;
				pque.push(P(d[e.to], e.to));
			}
		}
	}
}

void solve()
{
	cin >> n;
	for (int i = 0; i < n - 1; ++i)
	{
		int s, t, w;
		cin >> s >> t >> w;
		edge e1, e2;
		e1.to = t;
		e2.to = s;
		e1.cost = e2.cost = w;
		G[s].push_back(e1);
		G[t].push_back(e2);
	}
	bfs(0);
	int maxDist = 0;
	int maxv = 0;
	for (int i = 1; i < n; ++i)
	{
		if (maxDist < d[i])
		{
			maxDist = d[i];
			maxv = i;
		}
	}
	bfs(maxv);
	maxDist = 0;
	for (int i = 0; i < n; ++i)
	{
		if (maxDist < d[i])
		{
			maxDist = d[i];
		}
	}
	cout << maxDist << endl;
}

int main()
{
	solve();
	return(0);
}

Diameter of a Tree

Given a tree T with non-negative weight, find the diameter of the tree.

The diameter of a tree is the maximum distance between two nodes in a tree.

Input

n
s1 t1 w1
s2 t2 w2
:
sn-1 tn-1 wn-1

The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively.

In the following n-1 lines, edges of the tree are given.

si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge.

Output

Print the diameter of the tree in a line.

Constraints

1 ≤ n ≤ 100,000

0 ≤ wi ≤ 1,000

Sample Input 1

4
0 1 2
1 2 1
1 3 3

Sample Output 1

5

Sample Input 2

4
0 1 1
1 2 2
2 3 4

Sample Output 2

7


#include<iostream>
using namespace std;
int main(){
	int x = 0;
	cin >> x;
	for (int i = 0; i >= 0;i++){
		if (x != 0){
			cout << "Case" << " " << i << "; " <<x<< endl;
		}
	}
	return 0;
}

Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem.

Input

The input consists of multiple datasets. Each dataset consists of an integer x in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print x in the following format:

Case i: x

where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.

Constraints

1 ≤ x ≤ 10000

The number of datasets ≤ 10000

Sample Input

3
5
11
7
8
19
0

Sample Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19


#include<bits/stdc++.h>
using namespace std;
int main(){
    int n,m,l;
    cin>>n>>m>>l;

    int a[100][100];
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++) cin>>a[i][j];

    int b[100][100];
    for(int i=0;i<m;i++)
        for(int j=0;j<l;l++) cin>>b[i][j];

    long long c[100][100] = {};
    for(int i=0;i<n;i++)
        for(int j=0;j<l;j++)
            for(int k=0;k<m;k++) c[i][j] += a[i][k] * b[k][j];

    for(int i=0;i<n;i++){
        for(int j=0;j<l;j++){
            if(j) cout<<" ";
            cout<<c[i][j];
        }
        cout<<endl;
    }
    return 0;
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Matrix Multiplication

Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula:

\[
c_{ij} = \sum_{k=1}^m a_{ik}b_{kj}
\]

where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ respectively.

Input

In the first line, three integers $n$, $m$ and $l$ are given separated by space characters

In the following lines, the $n \times m$ matrix $A$ and the $m \times l$ matrix $B$ are given.

Output

Print elements of the $n \times l$ matrix $C$ ($c_{ij}$). Print a single space character between adjacent elements.

Constraints

$1 \leq n, m, l \leq 100$

$0 \leq a_{ij}, b_{ij} \leq 10000$

Sample Input

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

Sample Output

1 8 5
0 9 6
4 23 14

Note

      解説


#include "bits/stdc++.h"

#define REP(i,num) for(int i=0;i<(num);++i)
#define ALL(c) c.begin(),c.end()
#define PRINTALL(c) for(auto& x:c){cout<<x<<' ';}cout<<endl;
#define PAIRCOMP(c,comp) [](const pair<ll,ll>& lhs,const pair<ll,ll>& rhs){return lhs.c comp rhs.c;}

using namespace std;
using ll = long long;

constexpr ll atcoder_mod = 1e9+7;

template<typename T=int>
T in(){T x; cin >> x; return (x);}
template<typename T=int,typename C=vector<T>>
C vecin(int N){C x(N);REP(i,N){x[i]=in<T>();}return move(x);}

void vout(){cout << endl;}
template<typename Head,typename... Tail>
void vout(Head&& h,Tail&&... t){cout << ' ' << h;vout(forward<Tail>(t)...);}
void out(){cout << endl;}
template<typename Head,typename... Tail>
void out(Head&& h,Tail&&... t){cout << h;vout(forward<Tail>(t)...);}

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

	int Q=in();
	set<int> S;
	REP(i,Q){
		int q=in();
		if(q==1){
			out(S.find(in())==S.end()?0:1);
		}
		else if(q==2){
			S.erase(in());
		}
		else{
			S.insert(in());
			out(S.size());
		}
	}
	return 0;
}

Set: Delete

For a set $S$ of integers, perform a sequence of the following operations. Note that each value in $S$ must be unique.

insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation.

find($x$): Report the number of $x$ in $S$ (0 or 1).

delete($x$): Delete $x$ from $S$.

Input

The input is given in the following format.

$q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given by

0 $x$

or

1 $x$

or

2 $x$

where the first digits 0, 1 and 2 represent insert, find and delete operations respectively.

Output

For each insert operation, print the number of elements in $S$.

For each find operation, print the number of specified elements in $S$.

Constraints

$1 \leq q \leq 200,000$

$0 \leq x \leq 1,000,000,000$

Sample Input 1

8
0 1
0 2
0 3
2 2
1 1
1 2
1 3
0 2

Sample Output 1

1
2
3
1
0
1
3


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

struct UnionFind{
	vector<int> par;

	UnionFind(int N){
		par.resize(N,-1);
	}

	int root(int x){
		if(par[x] < 0) return x;
		return par[x] = root(par[x]);
	}

	void unite(int x, int y){
		int rx = root(x);
		int ry = root(y);
		if(rx == ry) return;
		if(par[rx] < par[ry]){
			par[rx] += par[ry];
			par[ry] = rx;
		} else {
			par[ry] += par[rx];
			par[rx] = ry;
		}

	}

	bool same(int x, int y){
		return par[x] == par[y];
	}

};

int main(){
	int N,M; cin >> N >> M;
	UnionFind uf(N);
	for(int i=0; i<M; i++){
		int a,b; cin >> a >> b;
		a--; b--;
		uf.unite(a,b);
	}
	set<int> s;
	for(int i=0; i<N; i++){
		s.insert(uf.root(i));
	}
	cout << s.size()-1 << endl;
	return 0;
}

Score : 300 points

Problem Statement

There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M.
Road i connects City A_i and City B_i.

Snuke can perform the following operation zero or more times:

Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.

After he finishes the operations, it must be possible to travel from any city to any other cities by following roads (possibly multiple times).

What is the minimum number of roads he must build to achieve the goal?

Constraints

2 \leq N \leq 100,000

1 \leq M \leq 100,000

1 \leq A_i < B_i \leq N

No two roads connect the same pair of cities.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

Print the answer.

Sample Input 1

3 1
1 2

Sample Output 1

1

Initially, there are three cities, and there is a road between City 1 and City 2.

Snuke can achieve the goal by building one new road, for example, between City 1 and City 3.
After that,

We can travel between 1 and 2 directly.

We can travel between 1 and 3 directly.

We can travel between 2 and 3 by following both roads (2 - 1 - 3).


/*
これを入れて実行
g++ code.cpp
./a.out
 */

#include <iostream>
#include <cstdio>
#include <stdio.h>
#include <vector>
#include <string>
#include <cstring>
#include <queue>
#include <deque>
#include <stack>
#include <algorithm>
#include <utility>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <math.h>
#include <tuple>
#include <iomanip>
#include <bitset>
#include <functional>
#include <cassert>
#include <random>

#define all(x) (x).begin(),(x).end()
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

using namespace std;
typedef long long ll;
typedef long double ld;

int dy4[4] = {-1, 0, +1, 0};
int dx4[4] = {0, +1, 0, -1};
int dy8[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dx8[8] = {0, 1, 1, 1, 0, -1, -1, -1};

const long long INF = 1LL << 60;
const ll MOD = 1e9 + 7;

bool greaterSecond(const pair<int, int>& f, const pair<int, int>& s){
    return f.second > s.second;
}

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

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

ll conbinationMemo[100][100];

void cmemoInit(){
    rep(i, 100){
        rep(j, 100){
            conbinationMemo[i][j] = -1;
        }
    }
}

ll nCr(ll n, ll r){
    if(conbinationMemo[n][r] != -1) return conbinationMemo[n][r];
    if(r == 0 || r == n){
        return 1;
    } else if(r == 1){
        return n;
    }
    return conbinationMemo[n][r] = (nCr(n - 1, r) + nCr(n - 1, r - 1));
}

ll nPr(ll n, ll r){
    r = n - r;
    ll ret = 1;
    for (ll i = n; i >= r + 1; i--) ret *= i;
    return ret;
}
//-----------------------ここから-----------
struct UnionFind{
    vector<ll> parent;
    vector<ll> s;

    UnionFind(ll n){
        parent.resize(n);
        s.resize(n, 1);
        for(int i = 0; i < n; i++) parent[i] = i;
    }

    ll root(ll node){
        if(parent[node] == node){
            return node;
        } else {
            return parent[node] = root(parent[node]);
        }
    }

    void unite(ll x, ll y){
        ll rootx = root(x);
        ll rooty = root(y);
        if(rootx == rooty) return;
        if(s[rootx] < s[rooty]) swap(rootx, rooty);
        s[rootx] += s[rooty];
        parent[rooty] = rootx;
    }

    bool isSame(ll x, ll y){
        return root(x) == root(y);
    }

    ll size(ll x){
        return s[root(x)];
    }
};
int main(void){
    ll n;
    cin >> n;
    vector<pair<pair<ll,ll>,ll>> vecx, vecy;
    rep(i, n){
        ll x, y;
        cin >> x >> y;
        vecx.push_back({{x, y}, i});
    }

    sort(all(vecx));

    UnionFind uf(n);
    vector<pair<ll,ll>> mi(200200, {INF, INF});
    set<pair<ll,ll>> rt;
    for(ll i = 0; i < n; i++){
        for(auto &j : rt){
            if(j.first < vecx[i].first.second){
                uf.unite(vecx[i].second, j.second);
            } else {
                break;
            }
        }
        ll root = uf.root(vecx[i].second);
        if(mi[root].first > vecx[i].first.second){
            rt.erase({mi[root].first, root});
            mi[root] = {vecx[i].first.second, vecx[i].second};
            rt.insert({mi[root].first, root});
        }
    }

    rep(i, n){
        cout << uf.size(i) << endl;
    }

}

Score : 300 points

Problem Statement

There are N cities on a 2D plane. The coordinate of the i-th city is (x_i, y_i). Here (x_1, x_2, \dots, x_N) and (y_1, y_2, \dots, y_N) are both permuations of (1, 2, \dots, N).

For each k = 1,2,\dots,N, find the answer to the following question:

Rng is in City k.
Rng can perform the following move arbitrarily many times:

move to another city that has a smaller x-coordinate and a smaller y-coordinate, or a larger x-coordinate and a larger y-coordinate, than the city he is currently in.

How many cities (including City k) are reachable from City k?

Constraints

1 \leq N \leq 200,000

(x_1, x_2, \dots, x_N) is a permutation of (1, 2, \dots, N).

(y_1, y_2, \dots, y_N) is a permutation of (1, 2, \dots, N).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print N lines. In i-th line print the answer to the question when k = i.

Sample Input 1

4
1 4
2 3
3 1
4 2

Sample Output 1

1
1
2
2

Rng can reach City 4 from City 3, or conversely City 3 from City 4.

Sample Input 2

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

Sample Output 2

3
3
1
1
2
3
2


#pragma GCC optimize(2)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#define File(x) freopen(x".in","r",stdin),freopen(x".out","w",stdout);
#define re register
#define ri re int
#define gtch() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
#define For(i,a,b) for(ri i=a;i<=b;++i)
#define iFor(i,a,b) for(ri i=a;i>=b;--i)
using namespace std;
typedef long long ll;
char buf[1<<21],*p1=buf,*p2=buf;
inline ll fr()
{
	re char ch=getchar();re ll res=0;int bl=0;
	while(!isdigit(ch)) bl=(ch=='-'),ch=getchar();
	while(isdigit(ch)) res=(res<<1)+(res<<3)+ch-'0',ch=getchar();
	return bl?-res:res;
}
const int MAXN=100;
const int INF=9e8+5;
string s;
signed main()
{
//	File("temp")
	cin>>s;
	cout<<s;
	if(s[s.size()-1]=='s')cout<<"es";
	else cout<<"s";
	return 0;
}

Score : 100 points

Problem Statement

In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.

In Taknese, the plural form of a noun is spelled based on the following rules:

If a noun's singular form does not end with s, append s to the end of the singular form.

If a noun's singular form ends with s, append es to the end of the singular form.

You are given the singular form S of a Taknese noun. Output its plural form.

Constraints

S is a string of length 1 between 1000, inclusive.

S contains only lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the plural form of the given Taknese word.

Sample Input 1

apple

Sample Output 1

apples

apple ends with e, so its plural form is apples.

Sample Input 2

bus

Sample Output 2

buses

bus ends with s, so its plural form is buses.

Sample Input 3

box

Sample Output 3

boxs


/*input
6
1 1
2 2
3 3
4 4
5 5
6 6
*/

#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>;

int main() {
  int n;
  cin >> n;
  int cnt = 0;
  rep(i, n) {
    int a, b;
    cin >> a >> b;
    if (a == b) {
      cnt++;
      if (cnt == 3) {
        cout << "Yes" << endl;
        return 0;
      }
    }
    else cnt = 0;
  }
  cout << "No" << endl;
}

Score : 200 points

Problem Statement

Tak performed the following action N times: rolling two dice.
The result of the i-th roll is D_{i,1} and D_{i,2}.

Check if doublets occurred at least three times in a row.
Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold.

Constraints

3 \leq N \leq 100

1\leq D_{i,j} \leq 6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
D_{1,1} D_{1,2}
\vdots
D_{N,1} D_{N,2}

Output

Print Yes if doublets occurred at least three times in a row. Print No otherwise.

Sample Input 1

5
1 2
6 6
4 4
3 3
3 2

Sample Output 1

Yes

From the second roll to the fourth roll, three doublets occurred in a row.

Sample Input 2

5
1 1
2 2
3 4
5 5
6 6

Sample Output 2

No

Sample Input 3

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

Sample Output 3

Yes


// #pragma GCC optimize("Ofast")
// #pragma GCC target("avx,avx2,fma")
// #pragma GCC optimization ("unroll-loops")

#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;

#define fo(i,n)             for(int i=0;i<n;i++)
#define nl                  "\n"
#define ff                  first
#define ss                  second
#define int                 long long
#define pb                  push_back
#define mp                  make_pair
#define vec(x)              vector<x>
#define matrix(x)           vector<vector<x>>
#define sz(x)               (int)x.size()
#define mem(a,b)            memset(a, b, sizeof a)
#define vii                 vector<pair<int,int>>
#define pii                 pair<int,int>
#define vi                  vector<int>
#define mii                 map<int,int>
#define uii                 unordered_map<int,int,custom_hash>
#define pqb                 priority_queue<int>
#define pqs                 priority_queue<int,vi,greater<int> >
#define gcd(a,b)            __gcd(a,b)
#define lcm(a,b)            (a*(b/gcd(a,b)))
#define setbits(x)          __builtin_popcountll(x)
#define zrobits(x)          __builtin_ctzll(x)
#define mod                 1000000007
#define MOD                 998244353
#define inf                 1e18
#define ps(x,y)             fixed<<setprecision(y)<<x
#define mk(arr,n,type)      type *arr=new type[n];
#define w(x)                int x; cin>>x; while(x--)
#define all(v)              v.begin(),v.end()
#define rep(i,begin,end)    for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define len(s)              s.length()

#define watch(x)            cout << #x << " = " << x << endl

#define deb(...) cerr << "[" << #__VA_ARGS__ << "] : [", DBG(__VA_ARGS__)
void DBG() { cerr << "]\n";}
template<typename T, typename ...Args> void DBG(T first, Args... args)
{cerr << first; if(sizeof...(args))cerr<<", "; DBG(args...); }

mt19937                     rng(chrono::steady_clock::now().time_since_epoch().count());

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; //for storing unique elements
typedef tree<int , null_type , less_equal<int> , rb_tree_tag , tree_order_statistics_node_update> ordered_set; //for repeating elements

int power(int a,int b,int m=mod)
{int ans=1;while(b>0){if(b&1)ans=(ans*a)%m;a=(a*a)%m;b>>=1;}
return ans;}

void babuBhaiya()
{

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

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

const int N = 1e5+1;
const double pi = acos(-1);

/*/-----------------------Modular Arithmetic---------------/*/
inline int add(int x,int y){
    x+=y;
    if (x>=mod) return x-mod;
    return x;
}
inline int sub(int x,int y){
    x-=y;
    if (x<0) return x+mod;
    return x;
}
inline int mul(int x,int y){
    return (x*1ll*y)%mod;
}
/*/-----------------------------Code begins----------------------------------/*/

void solve(){

    int n; cin>>n;
    vi v;
    fo(i,n){
        int a,b; cin>>a>>b;
        if(a == b) v.pb(i);
    }
    if(sz(v)<3){
        cout<<"No\n";
    }
    else{
        bool flag = false;
        for(int i = 2;i<sz(v);i++){
            if(v[i]==v[i-1]+1 and v[i-1]==v[i-2]+1){
                flag = true;
                break;
            }
        }
        if(flag) cout<<"Yes";
        else cout<<"No";
    }

}

int32_t main()
{
    babuBhaiya();

    int t;

    t = 1;
   // cin>>t;

    while(t--){
        solve();
    }

    return 0;
}


#include <iostream>

using namespace std;
int counting(int x) {
    int ans = 0;
    for (int i=1; i * i <= x; i++) {
        if (x % i == 0) {
            if (i * i == x) ans++;
            else ans += 2;
        }
    }
    return ans;
}
int main() {
    int N;
    cin >> N;
    int ans = 0;
    for (int nc = 1; nc <= N-1; nc++) {
        ans += counting(nc);
    }
    cout << ans << endl;
    return 0;
}

Score : 300 points

Problem Statement

Given is a positive integer N.
How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?

Constraints

2 \leq N \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

3

Sample Output 1

3

There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).

Sample Input 2

100

Sample Output 2

473

Sample Input 3

1000000

Sample Output 3

13969985


#include<bits/stdc++.h>
typedef long long int lli;

#define em emplace_back
#define rep(i,j,n) for(lli i=j;i<n;i++)
#define repf(i,a,j,n) for(lli i=j,a=0;i<n;i++,a++)
#define repg(i,j,n) for(int i=j;i>n;--i)
using namespace std;
lli m = 998244353;

void solve(){

    lli n,k;
    cin>>n>>k;

    vector<lli> v;

    vector<lli> arrfront(n+1,0);

    unordered_map<lli,lli> s;

    rep(i,0,k){
        lli a,b;
        cin>>a>>b;
        if(a==b){
            v.em(a);
            continue;
        }
        rep(j,a,b+1){
            v.em(j);
        }
    }

    vector<lli> arrback(n+1,0);
    sort(v.begin(), v.end());
    lli ans = 0;
    rep(i,1,n){

        if(arrfront[i]==0){
            if(i!=1){
                continue;
            }else{
                arrfront[i] = 1;
            }
        }

        rep(j,0,v.size()){
            if(i+v[j]>n){
                break;
            }
            arrfront[i+v[j]] = arrfront[i+v[j]]%m;
            arrfront[i+v[j]] = (arrfront[i+v[j]]%m + arrfront[i]%m)%m;
            arrfront[i+v[j]] = arrfront[i+v[j]]%m;

        }
    }

    cout<<(arrfront[n]%m);

}

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

    return 0;
}

Score : 400 points

Problem Statement

There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.

Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.

You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K].
Let S be the union of these K segments.
Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.

When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.

To help Tak, find the number of ways to go to Cell N, modulo 998244353.

Constraints

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

1 \leq K \leq \min(N, 10)

1 \leq L_i \leq R_i \leq N

[L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
L_1 R_1
L_2 R_2
:
L_K R_K

Output

Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.

Sample Input 1

5 2
1 1
3 4

Sample Output 1

4

The set S is the union of the segment [1, 1] and the segment [3, 4], therefore S = \{ 1, 3, 4 \} holds.

There are 4 possible ways to get to Cell 5:

1 \to 2 \to 3 \to 4 \to 5,

1 \to 2 \to 5,

1 \to 4 \to 5 and

1 \to 5.

Sample Input 2

5 2
3 3
5 5

Sample Output 2

0

Because S = \{ 3, 5 \} holds, you cannot reach to Cell 5.
Print 0.

Sample Input 3

5 1
1 2

Sample Output 3

5

Sample Input 4

60 3
5 8
1 3
10 15

Sample Output 4

221823067

Note that you have to print the answer modulo 998244353.


#include<iostream>
#include<vector>
using LL = long long;
using namespace std;
int mod = 998244353;
int main() {
	LL N, K;
	cin >> N >> K;
	vector<LL> Li(K), Ri(K);
	vector<bool> S_has(N + 1, false);
	for (int i = 0; i < K; i++) {
		cin >> Li[i] >> Ri[i];
		for (int j = Li[i]; j <= Ri[i]; j++) {
			S_has[j] = true;
		}
	}
	vector<LL> Dp(N + 1, 0);
	Dp[1] = 1;

	for (int i = 2; i <= N; i++) {
		Dp[i] += Dp[i - 1];
		for (int k = 0; k < K; k++) {
			if (i - Li[k] > 0) {
				Dp[i] += Dp[i - Li[k]];
			}
			if (i - Ri[k] - 1 > 0) {
				Dp[i] -= Dp[i - Ri[k] - 1];
			}
		}
		while (Dp[i] < 0) {
			Dp[i] += mod;
		}
		Dp[i] = Dp[i] % mod;

	}
	LL ans = Dp[N] - Dp[N - 1];
	while (ans < 0) {
		ans += mod;
	}
	cout << ans << endl;

	return 0;
}


#include <bits/stdc++.h>
#include <set>
using namespace std;
using pii = pair<int,int>;
using pll = pair<long long, long long>;
const long long INF = 1<<29;

const int MOD = 1000000007;
long long ruizyou(long long m,long long n){
  if(m == 0)return 0;
  if(m == 1)return 1;
  long long ans = 1;
  long long tmp = m;
  for(int i=0;i<=30;i++){
    if(n & (1<<i)){
      ans *= tmp;
      ans %= MOD;
    }
    tmp *= tmp;
    tmp %= MOD;
  }
  return ans;
}
long long kaizyou(long long x){
  if(x == 0)return 1;
  return x * kaizyou(x-1) % MOD;
}
long long comb(long long x,long long y){
  long long bunsi = kaizyou(x);
  long long bunbo = kaizyou(x-y) * kaizyou(y) % MOD;
  return bunsi * ruizyou(bunbo,MOD-2) % MOD;
}
struct unionfind{
  vector<int> par;
  vector<vector<int>> children;
  vector<int> hukasa;
  vector<int> kazu;
  unionfind(int n){
    par = vector<int>(n);
    hukasa = vector<int>(n,0);
    kazu = vector<int>(n,1);
    for(int i=0;i<n;i++){
      par.at(i) = i;
    }
  }
  int root(int x){
    if(par.at(x) == x)return x;
    return root(par.at(x));
  }
  void unite(int x,int y){
    int rx = root(x);
    int ry = root(y);
    if(rx == ry)return;
    if(hukasa.at(rx) >= hukasa.at(ry)){
      par.at(ry) = rx;
      hukasa.at(rx) = max(hukasa.at(ry) + 1,hukasa.at(rx));
      kazu.at(rx) += kazu.at(ry);
    }
    else{
      par.at(rx) = ry;
      kazu.at(ry) += kazu.at(rx);
    }
  }
  void newkazu(){
    int n = kazu.size();
    for(int i=0;i<n;i++){
      kazu.at(i) = kazu.at(root(i));
    }
  }
  bool same(int x,int y){
    return root(x) == root(y);
  }
};
int ctoi(char a){
  return a - '0';
}
long long gcd(long long a,long long b){
  long long c = max(a,b);
  long long d = min(a,b);
  if(d % c == 0)return c;
  return gcd(c,d%c);
}
long long lcm(long long a,long long b){
  return a * b / gcd(a,b);
}
void hukasa(vector<vector<int>> s,vector<vector<int>> table,int &ans,pii frm,int n,int m){
  int x,y;
  tie(x,y) = frm;
  set<pii> se;
  if(x-1 >= 0)se.insert(pii(x-1,y));
  if(x+1 < n)se.insert(pii(x+1,y));
  if(y-1 >= 0)se.insert(pii(x,y-1));
  if(y+1 < m)se.insert(pii(x,y+1));
  for(auto t:se){
    int tx,ty;
    tie(tx,ty) = t;
    if(s.at(tx).at(ty) && table.at(tx).at(ty) == -1){
      table.at(tx).at(ty) = table.at(x).at(y) + 1;
      ans = max(ans,table.at(tx).at(ty));
      hukasa(s,table,ans,t,n,m);
      table.at(tx).at(ty) = -1;
    }
  }
}
void daiku(int frm,vector<vector<pii>> g,vector<int> &cost,int n){
  priority_queue<pii,vector<pii>,greater<pii>> q;
  q.push(pii(cost.at(frm),frm));
  vector<bool> kakutei(n,false);
  while(!q.empty()){
    pii now = q.top();
    q.pop();
    int n1,n2;
    tie(n1,n2) = now;
    if(kakutei.at(n2))continue;
    kakutei.at(n2) = true;
    for(auto t:g.at(n2)){
      int tx,ty;
      tie(tx,ty) = t;
      if(cost.at(tx) > n1 + ty){
        cost.at(tx) = n1 + ty;
        q.push(pii(cost.at(tx),tx));
      }
    }
  }
}

int main(){
  long long n,x,m;
  cin >> n >> x >> m;
  long long a = 0;
  long long b = 0;
  int unko = n;
  int flag = 0;
  unordered_set<long long> se;
  while(unko){
    if(se.count(x)){
      flag = 1;
      break;
    }
    se.insert(x);
    unko--;
    b += x;
    a++;
    x *= x;
    x %= m;
    if(x == 0 || x == 1)break;
  }
  if(x == 0)cout << b << endl;
  else if(x == 1){
    //cout << 'n' << endl;
    cout << b + n - a << endl;
  }
  else if(flag == 1){
    long long ans = 0;
    ans += b * (n/a);
    n %= a;
    for(int i=0;i<n;i++){
      ans += x;
      x *= x;
      x %= m;
    }
    cout << ans << endl;
  }
  else cout << b <<endl;
}

Score : 500 points

Problem Statement

Let us denote by f(x, m) the remainder of the Euclidean division of x by m.

Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M).
Find \displaystyle{\sum_{i=1}^N A_i}.

Constraints

1 \leq N \leq 10^{10}

0 \leq X < M \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X M

Output

Print \displaystyle{\sum_{i=1}^N A_i}.

Sample Input 1

6 2 1001

Sample Output 1

1369

The sequence A begins 2,4,16,256,471,620,\ldots Therefore, the answer is 2+4+16+256+471+620=1369.

Sample Input 2

1000 2 16

Sample Output 2

6

The sequence A begins 2,4,0,0,\ldots Therefore, the answer is 6.

Sample Input 3

10000000000 10 99959

Sample Output 3

492443256176507


//header{{{
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/tag_and_trait.hpp>
#include <ext/pb_ds/trie_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

#define rep(i,n) for(int i=0;i<(n);++i)
#define reps(i,n) for(int i=1;i<=(n);++i)
#define all(x) begin(x),end(x)
#define Fixed fixed << setprecision(12)
#define int int_fast64_t
using pii = pair<int,int>;
constexpr int INF  = 0x3f3f3f3f;
constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL;
constexpr int mod1 = 1e9+7;
constexpr int mod2 = 998244353;

template <class Func>
class FixPoint : Func {
public:
    explicit constexpr FixPoint(Func&& f) noexcept : Func(forward<Func>(f)) {}

    template <class... Args>
    constexpr decltype(auto) operator()(Args&&... args) const {
        return Func::operator()(*this, std::forward<Args>(args)...);
    }
};

template <class Func>
static inline constexpr decltype(auto) makeFixPoint(Func&& f) noexcept {
    return FixPoint<Func>{forward<Func>(f)};
}

template <class A, class B> inline bool chmax(A &a, const B &b) { return b > a && (a = b, true); }
template <class A, class B> inline bool chmin(A &a, const B &b) { return b < a && (a = b, true); }

template <class T> using min_heap = priority_queue<T,vector<T>,greater<T> >;
template <class T> using max_heap = priority_queue<T>;
template <class A, class B> using umap = unordered_map<A,B>;
template <class T> using Set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <class K, class V> using Umap = gp_hash_table<K, V>;
using Trie = trie<string, null_type, trie_string_access_traits<>, pat_trie_tag, trie_prefix_search_node_update>;

inline int square(int a){ return a * a;}
inline int updiv(int a,int b){ return (a + b - 1) / b; }

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

signed main(){
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout.setf(ios_base::fixed);
    cout.precision(10);

    int x;
    cin >> x;

    if(x == 0){
        cout << 1 << '\n';
    }else{
        cout << 0 << '\n';
    }

    return 0;
}

Score : 100 points

Problem Statement

Given is an integer x that is greater than or equal to 0, and less than or equal to 1.
Output 1 if x is equal to 0, or 0 if x is equal to 1.

Constraints

0 \leq x \leq 1

x is an integer

Input

Input is given from Standard Input in the following format:

x

Output

Print 1 if x is equal to 0, or 0 if x is equal to 1.

Sample Input 1

1

Sample Output 1

0

Sample Input 2

0

Sample Output 2

1


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

int main() {
	int x;
	cin >> x;
	if (x == 0) {
		cout << 1 << endl;
	}
	else cout << 0 << endl;

	return 0;
}


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

int main() {
  int x;
  cin >> x;
  if (x==0) cout << 1 << endl;
  else cout << 0 << endl;
}


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

int main()
{
   ll a, b, c, d;
   cin >> a >> b >> c >> d;

   cout <<  max(max((b*c),(b*d)),max((a*d),(a*c)))<< endl;

}

Score : 200 points

Problem Statement

Given are integers a,b,c and d.
If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?

Constraints

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

-10^9 \leq c \leq d \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

Print the answer.

Sample Input 1

1 2 1 1

Sample Output 1

2

If x = 1 and y = 1 then x \times y = 1.
If x = 2 and y = 1 then x \times y = 2.
Therefore, the answer is 2.

Sample Input 2

3 5 -4 -2

Sample Output 2

-6

The answer can be negative.

Sample Input 3

-1000000000 0 -1000000000 0

Sample Output 3

1000000000000000000


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

int main() {
 int64_t a, b, c, d;
 cin >> a >> b >> c >> d;

 if (a >= 0 && c >= 0) cout << b * d << endl;
 else if (b <= 0 && d <= 0) cout << a * c << endl;
 else if (a >= 0 && d <= 0) cout << a * d << endl;
 else if (b <= 0 && c >= 0) cout << b * c << endl;
 else if (a * b <= 0 && c * d <= 0) cout << max(a * c, b * d) << endl;
 else cout << b * d << endl;

}


#include <iostream>
#include <vector>
#include <limits.h>
#include <cmath>
using namespace std;
int main(void){
    // Your code here!
    long x1,x2,y1,y2;
    cin>>x1>>x2>>y1>>y2;
    long answer=-1*pow(10,18);
    vector<vector<long>> vec={{x1,x2},{y1,y2}};
    for(int i=0;i<2;i++){
        for(int j=0;j<2;j++){
            if(vec[0][i]*vec[1][j]>answer){
                answer=vec[0][i]*vec[1][j];
            }
        }
    }
    cout<<answer;
}


#include <bits/stdc++.h>
//#include <chrono>
//#pragma GCC optimize("Ofast")
using namespace std;
#define reps(i,s,n) for(int i = s; i < n; i++)
#define rep(i,n) reps(i,0,n)
#define Rreps(i,n,e) for(int i = n - 1; i >= e; --i)
#define Rrep(i,n) Rreps(i,n,0)
#define ALL(a) a.begin(), a.end()
#define fi first
#define se second
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;

ll N,M,H,W,Q,K,A,B;
string S;
typedef pair<ll, ll> P;
const ll INF = (1LL<<60);

template <unsigned long long mod > class modint{
public:
    ll x;
    constexpr modint(){x = 0;}
    constexpr modint(ll _x) : x((_x < 0 ? ((_x += (LLONG_MAX / mod) * mod) < 0 ? _x + (LLONG_MAX / mod) * mod : _x) : _x)%mod){}
    constexpr modint operator-(){
        return x == 0 ? 0 : mod - x;
    }
    constexpr modint& operator+=(const modint& a){
        if((x += a.x) >= mod) x -= mod;
        return *this;
    }
    constexpr modint operator+(const modint& a) const{
        return modint(*this) += a;
    }
    constexpr modint& operator-=(const modint& a){
        if((x -= a.x) < 0) x += mod;
        return *this;
    }
    constexpr modint operator-(const modint& a) const{
        return modint(*this) -= a;
    }
    constexpr modint& operator*=(const modint& a){
        (x *= a.x)%=mod;
        return *this;
    }
    constexpr modint operator*(const modint& a) const{
        return modint(*this) *= a;
    }
    constexpr modint pow(unsigned long long pw) const{
        modint res(1), comp(*this);
        while(pw){
            if(pw&1) res *= comp;
            comp *= comp;
            pw >>= 1;
        }
        return res;
    }
    //以下、modが素数のときのみ
    constexpr modint inv() const{
        return modint(*this).pow(mod - 2);
    }
    constexpr modint& operator/=(const modint &a){
        (x *= a.inv().x)%=mod;
        return *this;
    }
    constexpr modint operator/(const modint &a) const{
        return modint(*this) /= a;
    }
};
#define mod2 1000000007
using mint = modint<mod2>;

ostream& operator<<(ostream& os, const mint& a){
    os << a.x;
    return os;
}
using vm = vector<mint>;
int main() {
    cin>>N;
    mint res(10);
    res = res.pow(N);
    res -= mint(9).pow(N) * 2;
    res += mint(8).pow(N);
    cout<<res<<endl;
}

Score : 300 points

Problem Statement

How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?

0 \leq A_i \leq 9

There exists some i such that A_i=0 holds.

There exists some i such that A_i=9 holds.

The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^9 + 7.

Sample Input 1

2

Sample Output 1

2

Two sequences \{0,9\} and \{9,0\} satisfy all conditions.

Sample Input 2

1

Sample Output 2

0

Sample Input 3

869121

Sample Output 3

2511445


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

int main(){
  int s;
  cin>>s;
  vector<long long> dp(s+1,0);
  long long max = pow(10,9)+7;

  dp[0] = 1;
  for(int i=3;i<=s;i++){
    dp[i] = (dp[i-1]+dp[i-3])%max;
  }
  cout<<dp[s]<<endl;
  return 0;
}

Score : 400 points

Problem Statement

Given is an integer S.
Find how many sequences there are whose terms are all integers greater than or equal to 3, and whose sum is equal to S.
The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq S \leq 2000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer.

Sample Input 1

7

Sample Output 1

3

3 sequences satisfy the condition: \{3,4\}, \{4,3\} and \{7\}.

Sample Input 2

2

Sample Output 2

0

There are no sequences that satisfy the condition.

Sample Input 3

1729

Sample Output 3

294867501


#pragma optimization_level 3
#include <bits/stdc++.h>
#define  f               first
#define  s               second
#define  sym(s)          s = "#" + s + "#";
#define  all(x)          (x).begin(), (x).end()
#define  alll(x,n)       x+1, x+n+1
#define  newl            cout<<"\n";
#define  foo(i,a,n)      for(ll i = (a); i <= n; i++)
#define  deb1(a)         cout<<a<<"\n";
#define  deb2(a,b)       cout<<a<<" "<<b<<"\n";
#define  deb3(a,b,c)     cout<<a<<" "<<b<<" "<<c<<"\n";
#define  deb4(a,b,c,d)   cout<<a<<" "<<b<<" "<<c<<" "<<d<<"\n";
#define  debp(a)         cout<<a.f<<" "<<a.s<<"\n";
#define  debv(a)         for(auto it: a)cout<<it<<" ";newl;
#define  debm(a)         for(auto it: a)cout<<"{"<<it.f<<","<<it.s<<"}, ";newl;
#define  deb1d(a,n)      foo(i,1,n)cout<<a[i]<<" ";newl;
#define  deb2d(a,n,m)    foo(i,1,n){foo(j,1,m){cout<<a[i][j]<<" ";}newl;}

using namespace std;
using ll              =  long long;
using ld              =  long double;
const ll   MOD        =  1e+9 + 7;
const ll   INF        =  LLONG_MAX;
const int  N          =  (int)2e+5 + 8;

ll n, x[N], y[N];

void MAIN(int tc){
    cin >> n;\
    ll mnx, mxx, mny, mxy;
    mnx = mny = INF;
    mxx = mxy = -INF;
    for(int i = 1; i <= n; i++){
        cin >> x[i] >> y[i];
        mnx = min(mnx, x[i]);
        mxx = max(mxx, x[i]);
        mny = min(mny, y[i]);
        mxy = max(mxy, y[i]);
    }

    set<pair<ll,ll>> points;
    ll tmn, tmx;

    tmn = INF; tmx = -INF;
    for(int i = 1; i <= n; i++){
        if(x[i] == mnx){
            tmn = min(tmn, y[i]);
            tmx = max(tmx, y[i]);
        }
    }
    points.insert({mnx,tmn});
    points.insert({mnx,tmx});

    tmn = INF; tmx = -INF;
    for(int i = 1; i <= n; i++){
        if(x[i] == mxx){
            tmn = min(tmn, y[i]);
            tmx = max(tmx, y[i]);
        }
    }
    points.insert({mxx,tmn});
    points.insert({mxx,tmx});

    tmn = INF; tmx = -INF;
    for(int i = 1; i <= n; i++){
        if(y[i] == mny){
            tmn = min(tmn, x[i]);
            tmx = max(tmx, x[i]);
        }
    }
    points.insert({tmn, mny});
    points.insert({tmx, mny});

    tmn = INF; tmx = -INF;
    for(int i = 1; i <= n; i++){
        if(y[i] == mxy){
            tmn = min(tmn, x[i]);
            tmx = max(tmx, x[i]);
        }
    }
    points.insert({tmn, mxy});
    points.insert({tmx, mxy});

    ll res = 0;
    for(auto [x1,y1]: points){
        for(auto [x2, y2]: points){
            res = max(res, abs(x1 - x2) + abs(y1 - y2));
        }
    }

    deb1(res);

}

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

    int test_cases = 1;
    //cin>>test_cases;
    for(int i = 1; i <= test_cases; i++){
        MAIN(i);
    }
}

Score : 500 points

Problem Statement

There are N points on the 2D plane, i-th of which is located on (x_i, y_i).
There can be multiple points that share the same coordinate.
What is the maximum possible Manhattan distance between two distinct points?

Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-y_j|.

Constraints

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

1 \leq x_i,y_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the answer.

Sample Input 1

3
1 1
2 4
3 2

Sample Output 1

4

The Manhattan distance between the first point and the second point is |1-2|+|1-4|=4, which is maximum possible.

Sample Input 2

2
1 1
1 1

Sample Output 2

0


Score : 600 points

Problem Statement

Given are two sequences A and B, both of length N.
A and B are each sorted in the ascending order.
Check if it is possible to reorder the terms of B so that for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output any of the reorderings that achieve it.

Constraints

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

1\leq A_i,B_i \leq N

A and B are each sorted in the ascending order.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N

Output

If there exist no reorderings that satisfy the condition, print No.

If there exists a reordering that satisfies the condition, print Yes on the first line.
After that, print a reordering of B on the second line, separating terms with a whitespace.

If there are multiple reorderings that satisfy the condition, you can print any of them.

Sample Input 1

6
1 1 1 2 2 3
1 1 1 2 2 3

Sample Output 1

Yes
2 2 3 1 1 1

Sample Input 2

3
1 1 2
1 1 3

Sample Output 2

No

Sample Input 3

4
1 1 2 3
1 2 3 3

Sample Output 3

Yes
3 3 1 2


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

using ll=long long;
#define rng(i,l,r) for(int i=int(l);i<int(r);i++)
#define rep(i,r) rng(i,0,r)
#define rrng(i,l,r) for(int i=int(r)-1;i>=int(l);i--)
#define rrep(i,r) rrng(i,0,r)
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define F first
#define S second
#define bg begin()
#define ed end()
#define all(x) x.bg,x.ed
#define si(x) int(x.size())
#define inf INT_MAX/2-100
#define infl LLONG_MAX/3
#ifdef LOCAL
#define dmp(x) cerr<<__LINE__<<' '<<#x<<' '<<x<<endl
#else
#define dmp(x) void(0)
#endif

template<class t,class u>bool chmax(t&a,u b){if(a<b)a=b;return a<b;}
template<class t,class u>bool chmin(t&a,u b){if(b<a)a=b;return b<a;}

template<class t>using vc=vector<t>;
template<class t>using vvc=vector<vector<t>>;

using pi=pair<int,int>;
using pl=pair<ll,ll>;
using vi=vc<int>;
using vl=vc<ll>;

ll readl(void){
	ll x;
	cin>>x;
	return x;
}
int readi(void){
	int x;
	cin>>x;
	return x;
}

string readstr(){
	string s;
	cin>>s;
	return s;
}
vi readvi(int n,int off=0){
	vi v(n);
	rep(i,n)v[i]=readi(),v[i]+=off;
	return v;
}

vl readvl(int n,int off=0){
	vl v(n);
	rep(i,n)v[i]=readl(),v[i]+=off;
	return v;
}

template<class t>
void print(t x,int suc=1){
	cout<<x;
	if(suc==1)cout<<"\n";
	if(suc==2)cout<<" ";
}

template<class t>
void print(const vc<t>&v,int suc=1){
	rep(i,si(v))print(v[i],i==int(si(v))-1?1:suc);
}

template<class t>
bool inc(t a,t b,t c){
	return !(c<b||b<a);
}

template<class t>
void compress(vc<t>&v){
	sort(all(v));
	v.erase(unique(all(v)),v.ed);
}

template<class t>
int lwb(const vc<t>&v,const t&a){
	return lower_bound(all(v),a)-v.bg;
}

template<class t>
struct Compress{
	vc<t>v;
	Compress()=default;
	Compress(const vc<t>&x){
		add(x);
	}
	Compress(const initializer_list<vc<t> >&x){
		for(auto &p:x)add(p);
	}
	void add(const t&x){
		v.eb(x);
	}
	void add(const vc<t>&x){
		copy(all(x),back_inserter(v));
	}
	void build(){
		compress(v);
	}
	int get(const t&x)const{
		return lwb(v,x);
	}
	vc<t>get(const vc<t>&x)const{
		vc<t>res(x);
		for(auto &p:res)p=get(p);
		return res;
	}
	const t &operator[](int x)const{
		return v[x];
	}
	int size(){
		return v.size();
	}
};
void Yes(bool ex=true){
	cout<<"Yes\n";
	if(ex)exit(0);
}
void YES(bool ex=true){
	cout<<"YES\n";
	if(ex)exit(0);
}
void No(bool ex=true){
	cout<<"No\n";
	if(ex)exit(0);
}
void NO(bool ex=true){
	cout<<"NO\n";
	if(ex)exit(0);
}
void orYes(bool x,bool ex=true){
	if(x)Yes(ex);
	else No(ex);
}
void orYES(bool x,bool ex=true){
	if(x)YES(ex);
	else NO(ex);
}
void Possible(bool ex=true){
	cout<<"Possible\n";
	if(ex)exit(0);
}
void POSSIBLE(bool ex=true){
	cout<<"POSSIBLE\n";
	if(ex)exit(0);
}
void Impossible(bool ex=true){
	cout<<"Impossible\n";
	if(ex)exit(0);
}
void IMPOSSIBLE(bool ex=true){
	cout<<"IMPOSSIBLE\n";
	if(ex)exit(0);
}
void orPossible(bool x,bool ex=true){
	if(x)Possible(ex);
	else Impossible(ex);
}
void orPOSSIBLE(bool x,bool ex=true){
	if(x)POSSIBLE(ex);
	else IMPOSSIBLE(ex);
}

ll n,k,a[55][55];
int main(void){
	cin.tie(0);
	ios::sync_with_stdio(0);
	cin>>n>>k;
	rep(i,n)rep(j,n)cin>>a[i][j];
	mcf_graph<ll,ll> g(n*2+2);
	rep(i,n){
		rep(j,n){
			g.add_edge(i,n+j,1,1e9-a[i][j]);
		}
	}
	rep(i,n){
		g.add_edge(n*2,i,k,0);
		g.add_edge(n+i,n*2+1,k,0);
	}
	vc<pl>p=g.slope(n*2,n*2+1);
	for(auto &i:p){
		swap(i.F,i.S);
		i.F=i.S*1e9-i.F;
	}
	sort(all(p));
	print(p.back().F);
	mcf_graph<ll,ll> ans(n*2+2);
	rep(i,n){
		rep(j,n){
			ans.add_edge(i,n+j,1,1e9-a[i][j]);
		}
	}
	rep(i,n){
		ans.add_edge(n*2,i,k,0);
		ans.add_edge(n+i,n*2+1,k,0);
	}
	ans.flow(n*2,n*2+1,p.back().S);
	rep(i,n){
		rep(j,n){
			if(ans.get_edge(i*n+j).flow==1)cout<<'X';
			else cout<<'.';
		}
		cout<<endl;
	}
}

Score : 100 points

Problem Statement

You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j).
A nonnegative integer A_{i,j} is written for each square (i,j).

You choose some of the squares so that each row and column contains at most K chosen squares.
Under this constraint, calculate the maximum value of the sum of the integers written on the chosen squares.
Additionally, calculate a way to choose squares that acheives the maximum.

Constraints

1 \leq N \leq 50

1 \leq K \leq N

0 \leq A_{i,j} \leq 10^9

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N K
A_{1,1} A_{1,2} \cdots A_{1,N}
A_{2,1} A_{2,2} \cdots A_{2,N}
\vdots
A_{N,1} A_{N,2} \cdots A_{N,N}

Output

On the first line, print the maximum value of the sum of the integers written on the chosen squares.

On the next N lines, print a way that achieves the maximum.

Precisely, output the strings t_1,t_2,\cdots,t_N, that satisfies t_{i,j}=X if you choose (i,j) and t_{i,j}=. otherwise.

You may print any way to choose squares that maximizes the sum.

Sample Input 1

3 1
5 3 2
1 4 8
7 6 9

Sample Output 1

19
X..
..X
.X.

Sample Input 2

3 2
10 10 1
10 10 1
1 1 10

Sample Output 2

50
XX.
XX.
..X


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

int main(){
    long long d,t,s;
    cin >> d >> t >> s;
    if(d/s <= t){
        cout << "Yes" << endl;
    }else{
        cout << "No" << endl;
    }
    return 0;
}

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.

Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

If Takahashi will reach the place in time, print Yes; otherwise, print No.

Sample Input 1

1000 15 80

Sample Output 1

Yes

It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.

Sample Input 2

2000 20 100

Sample Output 2

Yes

It takes 20 minutes to go 2000 meters to the place at a speed of 100 meters per minute. They have planned to meet in 20 minutes so he will arrive just on time.

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.


#include <iostream>
#include <string>

using namespace std;

int main(){
  int d,t,s;
  cin >> d >> t >> s ;
  if(d > t * s) cout  << 'Yes';
  else cout << 'No';
  return 0;
}


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

int main() {
  string s, t;
  cin >> s >> t;
  int count = s.size() - t.size();
  vector<long long int> wa(count);
  int size = t.size();
  rep(i, count){
    rep(j, size){
      char S, T;
      S = s.at(i + j); T = t.at(j);
      if(S != T) wa[i]++;
    }
  }
  Vsort(wa);
  cout << wa[0] << endl;
}

Score : 200 points

Problem Statement

Given are two strings S and T.

Let us change some of the characters in S so that T will be a substring of S.

At least how many characters do we need to change?

Here, a substring is a consecutive subsequence. For example, xxx is a substring of yxxxy, but not a substring of xxyxx.

Constraints

The lengths of S and T are each at least 1 and at most 1000.

The length of T is at most that of S.

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the minimum number of characters in S that need to be changed.

Sample Input 1

cabacc
abc

Sample Output 1

1

For example, changing the fourth character a in S to c will match the second through fourth characters in S to T.

Since S itself does not have T as its substring, this number of changes - one - is the minimum needed.

Sample Input 2

codeforces
atcoder

Sample Output 2

6


#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
    string str,ptr;
    cin>>str>>ptr;
    int mx=0;
    for(int i=0; i<ptr.size(); i++)
    {
        int x=i;
        int cnt=0;
        for(int j=i; j<str.size(); j++)
        {
            if(str[j]==ptr[x])
            {
                cnt++;
            }
            else
            {

                mx=max(cnt,mx);
                cnt=0;
            }
            x++;
        }
        mx=max(cnt,mx);
    }
    cout<<ptr.size()-mx<<endl;

}


#include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
#define x first
#define y second
#define PQ priority_queue
#define pb push_back
#define fu(i,a,j) for(int i=a;i<j;i++)
#define fd(i,a,j) for(int i=a;i>=j;i--)
#define SYNC ios::sync_with_stdio(0),cin.tie(NULL),cout.tie(NULL)
#define MOD 1000000007
#define MOD2 1000000021
#define MAXN 2000000
#define INF 1e9
using namespace std;

typedef long long ll;
typedef long double ld;
typedef double db;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<string> vs;

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

ll m_pow(ll a, ll b, ll M = MOD) { ll res = 1; for (; b; b >>= 1, a = (a * a) % M)if (b & 1)res = (res * a) % M; return res; }
ll gcd(ll a, ll b) { if (a < b) swap(a, b); for (; b; a %= b, swap(a, b)); return a; }
ll lcm(ll a, ll b) { return a * b / gcd(a, b); };
db dis(pii a, pii b) { return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); }
int dr[] = { 0, 1, 0, -1, 1,1,-1,-1 };
int dc[] = { 1, 0, -1, 0, 1,-1,1,-1 };

int n, m, k, t;

string ansok[2] = { "NO","YES" };

pii a[200005];
int par[200005];
int sz[200005];
int Find(int u) {
	if (par[u] < 0) { return u; }
	return par[u] = Find(par[u]);
}
bool Union(int u, int v) {
	u = Find(u);
	v = Find(v);
	if (u == v)
		return 0;
	par[v] = u;
	sz[u] += sz[v];
	return 1;
}
int main()
{
	SYNC;
	memset(par, -1, sizeof par);
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
		sz[i] = 1;
	for (int i = 0; i < m; i++) {
		int u, v;
		cin >> u >> v;
		Union(u,v);
	}
	int mx = 0;
	for (int i = 1; i <= n; i++) {
		mx = max(mx, sz[Find(i)]);
	}
	cout << mx << '\n';
	return 0;
}

Score : 400 points

Problem Statement

There are N persons called Person 1 through Person N.

You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.

If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.

Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group.

At least how many groups does he need to make?

Constraints

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

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

1\leq A_i,B_i\leq N

A_i \neq B_i

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
\vdots
A_M B_M

Output

Print the answer.

Sample Input 1

5 3
1 2
3 4
5 1

Sample Output 1

3

Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal.

Sample Input 2

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

Sample Output 2

4

Sample Input 3

10 4
3 1
4 1
5 9
2 6

Sample Output 3

3


#include<bits/stdc++.h>

#define si(a) scanf("%d",&a)
#define sl(a) scanf("%lld",&a)
#define sd(a) scanf("%lf",&a)
#define sc(a) scahf("%c",&a);
#define ss(a) scanf("%s",a)
#define pi(a) printf("%d\n",a)
#define pl(a) printf("%lld\n",a)
#define pc(a) putchar(a)
#define ms(a) memset(a,0,sizeof(a))
#define repi(i, a, b) for(register int i=a;i<=b;++i)
#define repd(i, a, b) for(register int i=a;i>=b;--i)
#define reps(s) for(register int i=head[s];i;i=Next[i])
#define ll long long
#define ull unsigned long long
#define vi vector<int>
#define pii pair<int,int>
#define mii unordered_map<int,int>
#define msi unordered_map<string,int>
#define lowbit(x) ((x)&(-(x)))
#define ce(i, r) i==r?'\n':' '
#define pb push_back
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define INF 0x3f3f3f3f
#define pr(x) cout<<#x<<": "<<x<<endl
using namespace std;

inline int qr() {
    int f = 0, fu = 1;
    char c = getchar();
    while (c < '0' || c > '9') {
        if (c == '-')fu = -1;
        c = getchar();
    }
    while (c >= '0' && c <= '9') {
        f = (f << 3) + (f << 1) + c - 48;
        c = getchar();
    }
    return f * fu;
}

const int N = 4e5 + 10;

struct Seg_Tree {
    struct T {
        int l, r, ans, add;
    } t[N * 4];

    void build(int p, int l, int r) {
        t[p].l = l, t[p].r = r, t[p].ans=INF, t[p].add = 0;
        if (l == r)return;
        int mid = (l + r) >> 1;
        build(p << 1, l, mid);
        build(p << 1 | 1, mid + 1, r);
    }

    void spread(int p) {
        if (t[p].add) {
            t[p << 1].ans = t[p].l - t[p].add;
            t[p << 1].add = t[p].add;
            t[p << 1 | 1].ans = ((t[p].l + t[p].r) >> 1) + 1 - t[p].add;
            t[p << 1 | 1].add = t[p].add;
            t[p].add = 0;
        }
    }

    void change(int p, int l, int r, int c) {
        //if (t[p].r < l || t[p].l > r)return;
        if (l <= t[p].l && t[p].r <= r) {
            t[p].ans = l - c, t[p].add = c;
            return;
        }
        spread(p);
        int mid = (t[p].l + t[p].r) >> 1;
        if (l <= mid)change(p << 1, l, r, c);
        if (r > mid)change(p << 1 | 1, l, r, c);
        t[p].ans = min(t[p << 1].ans, t[p << 1 | 1].ans);
    }

    int ask(int p, int x) {
        if (t[p].l == t[p].r)return x - t[p].ans;
        spread(p);
        int mid = (t[p].l + t[p].r) >> 1;
        return x <= mid ? ask(p >> 1, x) : ask(p << 1 | 1, x);
    }
} tr;

int n, m, now = 1;

int main() {
    n = qr(), m = qr();
    tr.build(1, 1, m);
    repi(i, 1, n) {
        int l = qr(), r = qr();
        if (now >= l && now <= r)tr.change(1, now, r, -INF), now = r + 1;
        else if (now < l)tr.change(1, l, r, tr.ask(1, l - 1));
        if (now > m) {
            repi(j, i, n)puts("-1");
            return 0;
        }
        pi(i + tr.t[1].ans);
    }
    return 0;
}

Score : 600 points

Problem Statement

There is a grid of squares with H+1 horizontal rows and W vertical columns.

You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top.

For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print -1 instead.

Constraints

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

1 \leq A_i \leq B_i \leq W

Input

Input is given from Standard Input in the following format:

H W
A_1 B_1
A_2 B_2
:
A_H B_H

Output

Print H lines. The i-th line should contain the answer for the case k=i.

Sample Input 1

4 4
2 4
1 1
2 3
2 4

Sample Output 1

1
3
6
-1

Let (i,j) denote the square at the i-th row from the top and j-th column from the left.

For k=1, we need one move such as (1,1) → (2,1).

For k=2, we need three moves such as (1,1) → (2,1) → (2,2) → (3,2).

For k=3, we need six moves such as (1,1) → (2,1) → (2,2) → (3,2) → (3,3) → (3,4) → (4,4).

For k=4, it is impossible to reach any square in the fifth row from the top.


#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
#define out(x) cout << x << '\n'
#define lli long long int
#define uli unsigned long long int
#define rep(i, m, n) for (lli i = m; i < (n); i++)
#define repe(i, m, n) for (lli i = m; i <= (n); i++)
#define ALL(x) (x).begin(), (x).end()
#define SIZE(x) ((lli)(x).size())
#define MAX(x) *max_element(ALL(x))
#define MIN(x) *min_element(ALL(x))
#define _GLIBCXX_DEBUG
const lli INF = 2147483647;
const lli MINF = -2147483648;
const lli LINF = 9223372036854775807;
const lli MOD = 1000000007; //10^9+7
const double PI = acos(-1);
#define SORT(n) sort(n.begin(), n.end())
#define SORTR(n) sort(n.begin(), n.end(), greater<int>())
#define REV(n) reverse(n.begin(), n.end())
#define pb push_back
#define eb emplace_back
#define mp make_pair
using vi = vector<int>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
using vlli = vector<lli>;
using vvli = vector<vlli>;
using vs = vector<string>;
using vvs = vector<vs>;
using vb = vector<bool>;
using vvb = vector<vb>;
using ll = long long;
//---------------------------------------------------------------------------------------------------
// vector入力
template <typename T>
istream &operator>>(istream &is, vector<T> &vec)
{
  for (T &x : vec)
    is >> x;
  return is;
}
// vector出力
template <typename T>
ostream &operator<<(ostream &os, vector<T> &vec)
{
  // os << '{';
  for (int i = 0; i < vec.size(); i++)
  {
    os << vec[i] << (i + 1 == vec.size() ? "" : "");
  }
  // os << '}';
  return os;
}
// aよりもbが大きいならばaをbで更新する(更新されたならばtrueを返す)
template <typename T>
bool chmax(T &a, const T &b)
{
  if (a < b)
  {
    a = b; // aをbで更新
    return true;
  }
  return false;
}
// aよりもbが小さいならばaをbで更新する(更新されたならばtrueを返す)
template <typename T>
bool chmin(T &a, const T &b)
{
  if (a > b)
  {
    a = b; // aをbで更新
    return true;
  }
  return false;
}
//---------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------
void solve()
{
  lli a = 0, b = 0, c = 0, h = 0, n = 0, x, t, w = 0, ans = 0, count = 0;
  vector<pair<lli, lli>> pr;
  map<lli, lli> ma;
  set<lli> st;

  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> n >> x >> t;
  while (n > count)
  {
    count += x;
    ans += t;
  }
  out(ans);
  // if ()
  // {
  //   out("Yes");
  // }
  // else
  // {
  //   out("No");
  // }
}

//---------------------------------------------------------------------------------------------------
signed main()
{
  solve();
}

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.


#include <bits/stdc++.h>
#define ll long long
#define the_flash ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0)

using namespace std;

int main()
{
    the_flash;
    int n, x, t, sum = 0;
    cin >> n >> x >> t;

    if (x > 1)
    {
        while (x * t <= n)
            x += x;
    }
    else
    {
        cout << n * t << "\n";
        return 0;
    }

    cout << x << "\n";
    return 0;
}


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

int main() {
    int N; cin >> N;
    int X; cin >> X;
    int T; cin >> T;
    int ans = 0;
    int tako = 0;

    while(true){
        ans += T;
        tako += X;
        if(tako >= N){
            break;
        }
    }
    cout << ans << endl;
}


#include<stdio.h>
int main()
{
   long long int n,s=0,a,b,i,m;
    scanf("%lld",&n);
    scanf("%lld",&a);
    m=a;
    for(i=1;i<n;i++)
    {
        scanf("%lld",&b);
        if(b>m)m=b;
         else if(b<m)
           s=m-b+s;
    }
    printf("%lld\n",s);
}

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.


#include <bits/stdc++.h>

#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define endl "\n"

using namespace std;
using ll = long long;
using P = pair<int, int>;

const ll MOD = 1000000007LL; // = 10^9 + 7
const double PI = 3.14159265358979;

int h, w;
int seen[1010][1010];

vector<string> mp;
int dx[4] = {0, -1, 0, 1};
int dy[4] = {-1, 0, 1, 0};

void bfs(queue<P> que, int lv)
{
  if (que.empty()) return;
  queue<P> tmp;
  tmp.push(que.front());

  // 歩き
  while(!que.empty())
  {
    P tp = que.front();
    que.pop();
    for(int i = 0; i < 4; ++i)
    {
      int ny = tp.first  + dy[i];
      int nx = tp.second + dx[i];

      if (ny < 0 || h <= ny) continue;
      if (nx < 0 || w <= nx) continue;

      if (seen[ny][nx] == 0 && mp[ny][nx] == '.')
      {
        seen[ny][nx] = lv;
        que.push(P(ny, nx));
        tmp.push(P(ny, nx));
      }
    }
  }

  // ワープ
  queue<P> next_que;
  while(!tmp.empty())
  {
    P tp = tmp.front();
    tmp.pop();
    for(int y = -2; y <= 2; ++y)
    {
      int ny = tp.first + y;
      if (ny < 0 || h <= ny) continue;

      for(int x = -2; x <= 2; ++x)
      {
        int nx = tp.second + x;
        if (nx < 0 || w <= nx) continue;

        if (seen[ny][nx] == 0 && mp[ny][nx] == '.')
        {
          seen[ny][nx] = lv + 1;
          next_que.push(P(ny, nx));
        }
      }
    }
  }
  bfs(next_que, lv + 1);
}

void solve()
{
  int cy, cx;
  int dy, dx;

  cin >> h >> w;
  cin >> cy >> cx;
  cin >> dy >> dx;

  mp.resize(h);
  cx--; cy--;
  dx--; dy--;
  for(int i = 0; i < h; ++i)
  {
    cin >> mp[i];
  }

  queue<P> que;
  que.push(P(cy, cx));
  seen[cy][cx] = 1;

  bfs(que, 1);
  /*
  for(int ih = 0; ih < h; ++ih)
  {
    for(int iw = 0; iw < w; ++iw)
    {
      cout << seen[ih][iw];
    }
    cout << endl;
  }
  //*/
  cout << seen[dy][dx] - 1;

}

int main()
{
  fastio;
  solve();

  return 0;
}

Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

Sample Input 1

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

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

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

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2


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

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

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

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

ll ans = 1e10;
ll n,m,xi,yi , xf,yf;
ll a[1004][1004];

bool check(ll x, ll y)
{
	return (x >= 0 && y >= 0 && x < n && y < m);
}

ll b[] = {0 , 0 , 1, -1};
ll d[] = {-1 , 1 , 0 , 0};

void solve(ll cx ,ll cy ,ll fx ,ll fy ,ll cnt)
{
	if(cx == fx && cy == fy)
	{
		ans = min(ans,cnt);
	}

	a[cx][cy] = 1;

	for(ll i=0;i<4;i++)
	{
		ll nx = cx + b[i];
		ll ny = cy + d[i];

		if(check(nx,ny))
		{
			if(a[nx][ny] == 0)
				solve(nx,ny,fx,fy,cnt);
		}
	}

	for(ll i=-2;i<3;i++)
	{
		for(ll j=-2;j<3;j++)
		{
			ll nx = cx + i;
			ll ny = cy + j;
			if(check(nx,ny))
			{
				if(a[nx][ny] == 0)
				{
					solve(nx,ny,fx,fy,cnt+1);
				}
			}
		}
	}
}

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

	cin >> n >> m >> xi >> yi >> xf >> yf;
	ll i,j;

	for(i=0;i<n;i++)
	{
		for(j=0;j<m;j++)
		{
			char c;
			cin >> c;

			if(c == '.')
				a[i][j] = 0;
			else
				a[i][j] = 2;
		}
	}

	solve(xi-1, yi - 1 , xf-1 , yf-1 ,0);

	if(ans == 1e10)
		cout << -1 << endl;
	else
		cout << ans << endl;
}


// https://atcoder.jp/contests/abc175/tasks/abc175_c
#include <iostream>
#include <vector>
#include <deque>
#include <tuple>
#include <algorithm>
#include <iterator> // std::back_inserter

using namespace std;

int main()
{
    long long x, k, d;
    cin >> x >> k >> d;
    long long mod = x % d;
    long long div = x / d;
    if (d * k < x)
    {
        cout << x - d * k << endl;
        exit(0);
    }
    long long a = (x / d) * d;
    if ((k - div) % 2 == 0)
    {
        cout << x - a << endl;
    }
    else
    {
        cout << d - (x - a) << endl;
    }
}

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.


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

int main(){
  long long x,k,d;
  cin >> x >> k >> d;
  //xは現在の座標
  //kは移動回数
  //dは一回の移動距離

  while(abs(x)>abs(d)){
      if(x>=0){
        x-=d;
        k--;
      }
      else{
        x+=d;
        k--;
      }
    if(k==0) break;
  }
  if(k%2==0){
    cout << abs(x) << endl;
    return 0;}
  else{
    if(x>=0)x-=d;
    else x+=d;
  }
    cout << abs(x) << endl;
    return 0;
  }