#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <queue>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#define FOR(i,a,b) for (int i=(a),for_##i##_max=(b);i<=(for_##i##_max);++i)
#define RFOR(i,a,b) for (int i=(a),rfor_##i##_min=(b);i>=(rfor_##i##_min);--i)
#define REP(i,n) for (int i=0,rep_##i##_len=(n);i<(rep_##i##_len);++i)
#define RREP(i,n) for (int i=(n)-1;i>=0;--i)

namespace { // Basics

template<typename T>
void chmin(T &x, T y) {
  x = std::min(x, y);
}

template<typename T>
void chmax(T &x, T y) {
  x = std::max(x, y);
}

template<typename T>
__attribute__((unused))
const auto minimum = static_cast<T const &(*)(T const &, T const &)>(std::min);

template<typename T>
__attribute__((unused))
const auto maximum = static_cast<T const &(*)(T const &, T const &)>(std::max);

template<typename T>
__attribute__((unused))
T constexpr infty = std::numeric_limits<T>::max / 3;
template<>
__attribute__((unused))
auto constexpr infty<int> = 1'100'100'100;
template<>
__attribute__((unused))
auto constexpr infty<long long int> = 100'500'400'300'200'100LL;

using lli = long long int;
using ld = long double;

} // namespace

using namespace std;

template <typename T>
struct node_t {
  T key;
  node_t *lc, *rc;
  explicit node_t(T v): key(v), lc(nullptr), rc(nullptr) {}
};

template <typename T>
void insert(node_t<T> *&t, T v) {
  using ptr_t = node_t<T> *;
  ptr_t z = new node_t<T>(v);
  ptr_t y = nullptr;
  ptr_t x = t;
  while (x) {
    y = x;
    if (z->key < x->key) {
      x = x->lc;
    } else {
      x = x->rc;
    }
  }
  if (!y) {
    t = z;
  } else if (z->key < y->key) {
    y->lc = z;
  } else {
    y->rc = z;
  }
}

template <typename T>
void inorder_walk(node_t<T> *t) {
  using ptr_t = node_t<T> *;
  stack<tuple<ptr_t, bool>> stk;
  stk.emplace(t, false);
  while (!stk.empty()) {
    ptr_t ptr; bool op;
    tie(ptr, op) = stk.top(); stk.pop();
    if (!ptr) { continue; }
    if (op) {
      cout << " " << ptr->key;
    } else {
      stk.emplace(ptr->rc, false);
      stk.emplace(ptr, true);
      stk.emplace(ptr->lc, false);
    }
  }
  cout << endl;
}

template <typename T>
void preorder_walk(node_t<T> *t) {
  using ptr_t = node_t<T> *;
  stack<ptr_t> stk;
  stk.push(t);
  while (!stk.empty()) {
    auto const ptr = stk.top(); stk.pop();
    if (!ptr) { continue; }
    cout << " " << ptr->key;
    stk.push(ptr->rc);
    stk.push(ptr->lc);
  }
  cout << endl;
}

int main() {
  using Tree = node_t<lli> *;
  Tree tree = nullptr;
  int M; cin >> M;
  REP(query, M) {
    string S; cin >> S;
    if (S[0] == 'i') {
      lli K; cin >> K;
      insert(tree, K);
    } else {
      inorder_walk(tree);
      preorder_walk(tree);
    }
  }
  return 0;
}

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 <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
#define f first
#define s second
const int limB = 1<<22;
const int mt = 20;
const ll inf = 9223372036854775807;

int W = 1;
pll ords[limB];

void precalca(int N, ll* vals, ll* wts) {
    if(N<=0) return;
    for(int msk=(1<<N)-1; msk>=0; msk--) {
        ll a = 0, b = 0;
        for(int i=0; i<N; i++) {
            if((1<<i) & msk) continue;
            a += vals[i];
            b += wts[i];
        }
        ords[W++] = {b, a};
    }
    sort(ords, ords+W);
}

ll maxVal(ll k) {
    if(k<0) return 0;
    int pos = upper_bound(ords, ords+W, pll(k, inf)) - ords;
    return ords[pos-1].s;
}

int main() {
    int N ;
    ll maxW ;
    ll vals[50], wts[50];
    ll ans = 0;
    scanf("%d%lld", &N, &maxW);
    for(int i=0; i<N; i++)
        scanf("%lld%lld", &vals[i], &wts[i]);
    precalca(N-mt, vals + mt, wts + mt);
    for(int msk=(1<<mt)-1; msk>=0; msk--) {
        ll a = 0, b = 0;
        for(int i=0; i<mt; i++) {
            if((1<<i) & msk) continue;
            a += vals[i];
            b += wts[i];
        }
        if(b > maxW)
            continue;
        ans = max(ans, a + maxVal(maxW - b));
    }
    printf("%lld\n", ans);
}

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

Huge Knapsack Problem

You have N items that you want to put them into a knapsack. Item i has value vi and weight wi.

You want to find a subset of items to put such that:

The total value of the items is as large as possible.

The items have combined weight at most W, that is capacity of the knapsack.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1
v2 w2
:
vN wN

The first line consists of the integers N and W. In the following N lines, the value and weight of the i-th item are given.

Output

Print the maximum total values of the items in a line.

Constraints

1 ≤ N ≤ 40

1 ≤ vi ≤ 1015

1 ≤ wi ≤ 1015

1 ≤ W ≤ 1015

Sample Input 1

4 5
4 2
5 2
2 1
8 3

Sample Output 1

13

Sample Input 2

2 20
5 9
4 10

Sample Output 2

9

Submitted source-code file size, in bytes.

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

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


#include <bits/stdc++.h>
using namespace std;
#define ll long long
int n;
ll v;
ll a[5][1005];
ll b[1005*1005];
ll c[1005*1005];
int main(){
	cin>>n>>v;
	for(int i=0;i<4;i++)for(int j=0;j<n;j++)cin>>a[i][j];
	for(int i=0;i<n;i++)for(int j=0;j<n;j++)b[i*n+j]=a[0][i]+a[1][j],c[i*n+j]=a[2][i]+a[3][j];
	sort(b,b+n*n);sort(c,c+n*n);
	ll ans=0;
	for(int i=0;i<n*n;i++){
		pair<ll*,ll*>res=equal_range(c,c+n*n,v-b[i]);
		ans+=res.second-res.first;
	}
	cout<<ans<<"\n";
	return 0;
}

Coin Combination Problem

You have 4 bags A, B, C and D each of which includes N coins (there are totally 4N coins). Values of the coins in each bag are ai, bi, ci and di respectively.

Find the number of combinations that result when you choose one coin from each bag (totally 4 coins) in such a way that the total value of the coins is V. You should distinguish the coins in a bag.

Constraints

1 ≤ N ≤ 1000

1 ≤ ai, bi, ci, di ≤ 1016

1 ≤ V ≤ 1016

All input values are given in integers

Input

The input is given in the following format.

N V
a1 a2 ... aN
b1 b2 ... bN
c1 c2 ... cN
d1 d2 ... dN

Output

Print the number of combinations in a line.

Sample Input 1

3 14
3 1 2
4 8 2
1 2 3
7 3 2

Sample Output 1

9

Sample Input 2

5 4
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Sample Output 2

625


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <utility>
#include <numeric>
#include <array>
#include <cmath>
#include <memory>
using namespace std;
#define DEB(variable) cout << #variable << '=' << variable << endl

#define FOR(LoopVariable,numberOFbegin,numberOFend) for (long long int LoopVariable = (numberOFbegin); (LoopVariable) < (numberOFend); (LoopVariable)++)
#define DEFOR(LoopVariable,numberOFbegin,numberOFend) for (long long int LoopVariable = (numberOFbegin)-1; (LoopVariable) >= (numberOFend); (LoopVariable)--)
#define REP(LoopVariable,numberOFend) for(long long int LoopVariable = 0;(LoopVariable)<(numberOFend);LoopVariable++)

using llint = long long int;

constexpr long long int linf = numeric_limits<long long int>::max()-5;
constexpr long long int inf= numeric_limits<int>::max()-5;
constexpr long long int mod = 1000000007;

int main(){

    llint n, k, l, r;
    cin >> n >> k >> l >> r;
    vector<llint> v(n);
    REP(i,n){
        cin >> v[i];
    }

    vector<vector<llint>> grid1(1+(n/2), vector<llint>()), grid2(1+(n+1)/2, vector<llint>());
    for (llint bit = 0; bit < (1<<(n / 2));bit++){
        llint tmp = 0;
        REP(j,n/2){
            if(bit&(1<<j)){
                tmp += v[j];
            }
        }
        grid1[__builtin_popcountll(bit)].push_back(tmp);
    }
    for (llint bit = 0; bit < (1<<((n+1) / 2));bit++){
        llint tmp = 0;
        REP(j,(n+1)/2){
            if(bit&(1<<j)){
                tmp += v[(n/2)+j];
            }
        }
        grid2[__builtin_popcountll(bit)].push_back(tmp);
    }

    REP(i,1+n/2){
        sort(grid1[i].begin(), grid1[i].end());
    }
    REP(i,1+(n+1)/2){
        sort(grid2[i].begin(), grid2[i].end());
    }
    llint result = 0;
    REP(i,1+(n/2)){
        if(i<=k){
            REP(j,grid1[i].size()){
                if(k-i>=0&&k-i<=(n+1)/2){
                    result += distance(lower_bound(grid2[k - i].begin(), grid2[k - i].end(),l-grid1[i][j] ),
                    upper_bound(grid2[k - i].begin(), grid2[k - i].end(),r-grid1[i][j] ));
                }
              //  cout << result << endl;
            }
        }
    }
    cout << result << endl;
    return 0;
}

Coin Combination Problem II

You have N coins each of which has a value ai.
Find the number of combinations that result when you choose K different coins in such a way that the total value of the coins is greater than or equal to L and less than or equal to R.

Constraints

1 ≤ K ≤ N ≤ 40

1 ≤ ai ≤ 1016

1 ≤ L ≤ R ≤ 1016

All input values are given in integers

Input

The input is given in the following format.

N K L R
a1 a2 ... aN

Output

Print the number of combinations in a line.

Sample Input 1

2 2 1 9
5 1

Sample Output 1

1

Sample Input 2

5 2 7 19
3 5 4 2 2

Sample Output 2

5


#include <bits/stdc++.h>
#define FOR(i, a, b) for(int i=(a); i<(b); i++)
#define REP(i, n) FOR(i, 0, n)
#define all(x) (x).begin(), (x).end()
#define bit(x) (1L << (x))
using ll = long long;
using namespace std;

template<typename T>
vector<T> make_v(size_t a,T b){return vector<T>(a,b);}

template<typename... Ts>
auto make_v(size_t a,Ts... ts){
  return vector<decltype(make_v(ts...))>(a,make_v(ts...));
}

template<class Monoid>
class SegmentTree{
private:
  using T = typename Monoid::T;
  const size_t n;
  vector<T> d;

  void build(){
    for(size_t b = n - 1; b > 0; b--) d[b] = Monoid::op(d[b << 1], d[b << 1 | 1]);
  }

public:
  SegmentTree(size_t n)
    : n(n), d(2 * n, Monoid::identify()) {}

  template<typename InputItr>
  SegmentTree(InputItr first, InputItr last)
    : n(distance(first - last)), d(2 * n, Monoid::identify()){
    copy(first, last, next(d.begin(), n));
    build();
  }

  void modify(size_t k, T v){
    for(d[k += n] = v; k > 1; k >>= 1) d[k >> 1] = Monoid::op(d[k], d[k ^ 1]);
  }

  T query(T l, T r){
    T res {Monoid::identify()};
    for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
      if (l&1) res = Monoid::op(res, d[l++]);
      if (r&1) res = Monoid::op(res, d[--r]);
    }
    return res;
  }

  void dump(){
    FOR(i, n, 2 * n) cout << i - n << ": " << d[i] << endl;
  }
};

template<typename U = ll>
struct RSQ{
  using T = U;
  static T op(const T& a, const T& b){ return a + b; };
  static constexpr T identify(){ return T(0); };
};

template<typename U = ll>
struct RMQ{
  using T = U;
  static T op(const T& a, const T& b){ return min<T>(a, b); };
  static constexpr T identify(){ return numeric_limits<T>::max(); };
};

int main() {
  int n, q; cin >> n >> q;
  SegmentTree<RMQ<int>> tree(n);

  while(q--){
    int c, x, y;
    cin >> c >> x >> y;

    switch(c){
      case 0:
        tree.modify(x, y);
        break;
      case 1:
        cout << tree.query(x, y+1) << endl;
        break;
    }

  }
  return 0;
}

Range Minimum Query (RMQ)

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

find(s, t): report the minimum element in as, as+1, . . . ,at.

update(i, x): change ai to x.

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

Input

n q
com0 x0 y0
com1 x1 y1
...
comq−1 xq−1 yq−1

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes update(xi, yi) and '1' denotes find(xi, yi).

Output

For each find operation, print the minimum element.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

If comi is 0, then 0 ≤ xi < n, 0 ≤ yi < 231-1.

If comi is 1, then 0 ≤ xi < n, 0 ≤ yi < n.

Sample Input 1

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

Sample Output 1

1
2

Sample Input 2

1 3
1 0 0
0 0 5
1 0 0

Sample Output 2

2147483647
5


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

int tree[100010];
int n;
//BIT
int sum(int k){
    int s=0;
    while(k<=n){
        s+=tree[k];
        k+=(k&-k);
    }
    return s;
}

void add(int k, int x){
    while(k>0){
        tree[k]+=x;
        k-=(k&-k);
    }
}

int main(void){
    int q, a, s, t, x;
    cin >> n >> q;
    while(q--){
        cin >> a;
        if(a==0){
            cin >> s >> t >> x;
            add(t, x);
            add(s-1, -x);
        }else{
            cin >> s;
            cout << sum(s) << "\n";
        }
    }
    return 0;

}

Range Add Query (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.

get(i): output the value of ai.

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 t

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

Output

For each get operation, print the value.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

1 ≤ s ≤ t ≤ n

1 ≤ i ≤ n

0 ≤ x ≤ 1000

Sample Input 1

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

Sample Output 1

3
5

Sample Input 2

4 3
1 2
0 1 4 1
1 2

Sample Output 2

0
1


//#pragma GCC optimize ("-O3")
#include <bits/stdc++.h>
using namespace std;
//@起動時
struct initon {
    initon() {
        cin.tie(0);
        ios::sync_with_stdio(false);
        cout.setf(ios::fixed);
        cout.precision(16);
        srand((unsigned) clock() + (unsigned) time(NULL));
    };
} __initon;
//衝突対策
#define ws ___ws
struct T {
    int f, s, t;
    T() { f = -1, s = -1, t = -1; }
    T(int f, int s, int t) : f(f), s(s), t(t) {}
    bool operator<(const T &r) const {
        return f != r.f ? f < r.f : s != r.s ? s < r.s : t < r.t;
        //return f != r.f ? f > r.f : s != r.s ? s > r.s : t > r.t; 大きい順
    }
    bool operator>(const T &r) const {
        return f != r.f ? f > r.f : s != r.s ? s > r.s : t > r.t;
        //return f != r.f ? f > r.f : s != r.s ? s > r.s : t > r.t; 小さい順
    }
    bool operator==(const T &r) const {
        return f == r.f && s == r.s && t == r.t;
    }
    bool operator!=(const T &r) const {
        return f != r.f || s != r.s || t != r.t;
    }
    int operator[](int i) {
        assert(i < 3);
        return i == 0 ? f : i == 1 ? s : t;
    }
};
#define int long long
#define ll long long
#define double long double
#define ull unsigned long long
using dou = double;
using itn = int;
using str = string;
using bo= bool;
#define au auto
using P = pair<ll, ll>;

#define fi first
#define se second
#define vec vector
#define beg begin
#define rbeg rbegin
#define con continue
#define bre break
#define brk break
#define is ==

//マクロ省略系 コンテナ

using vi = vector<int>;
#define _overloadvvi(_1, _2, _3, _4, name, ...) name
#define vvi0() vec<vi>
#define vvi1(a) vec<vi> a
#define vvi2(a, b) vec<vi> a(b)
#define vvi3(a, b, c) vec<vi> a(b,vi(c))
#define vvi4(a, b, c, d) vec<vi> a(b,vi(c,d))
#define vvi(...) _overloadvvi(__VA_ARGS__,vvi4,vvi3,vvi2 ,vvi1,vvi0)(__VA_ARGS__)

using vl = vector<ll>;
#define _overloadvvl(_1, _2, _3, _4, name, ...) name
#define vvl1(a) vec<vl> a
#define vvl2(a, b) vec<vl> a(b)
#define vvl3(a, b, c) vec<vl> a(b,vl(c))
#define vvl4(a, b, c, d) vec<vl> a(b,vl(c,d))
#define vvl(...) _overloadvvl(__VA_ARGS__,vvl4,vvl3,vvl2 ,vvl1)(__VA_ARGS__)

using vb = vector<bool>;
#define _overloadvvb(_1, _2, _3, _4, name, ...) name
#define vvb1(a) vec<vb> a
#define vvb2(a, b) vec<vb> a(b)
#define vvb3(a, b, c) vec<vb> a(b,vb(c))
#define vvb4(a, b, c, d) vec<vb> a(b,vb(c,d))
#define vvb(...) _overloadvvb(__VA_ARGS__,vvb4,vvb3,vvb2 ,vvb1)(__VA_ARGS__)

using vs = vector<string>;
#define _overloadvvs(_1, _2, _3, _4, name, ...) name
#define vvs1(a) vec<vs> a
#define vvs2(a, b) vec<vs> a(b)
#define vvs3(a, b, c) vec<vs> a(b,vs(c))
#define vvs4(a, b, c, d) vec<vs> a(b,vs(c,d))
#define vvs(...) _overloadvvs(__VA_ARGS__,vvs4,vvs3,vvs2 ,vvs1)(__VA_ARGS__)

using vd = vector<double>;
#define _overloadvvd(_1, _2, _3, _4, name, ...) name
#define vvd1(a) vec<vd> a
#define vvd2(a, b) vec<vd> a(b)
#define vvd3(a, b, c) vec<vd> a(b,vd(c))
#define vvd4(a, b, c, d) vec<vd> a(b,vd(c,d))
#define vvd(...) _overloadvvd(__VA_ARGS__,vvd4,vvd3,vvd2 ,vvd1)(__VA_ARGS__)

using vc=vector<char>;
#define _overloadvvc(_1, _2, _3, _4, name, ...) name
#define vvc1(a) vec<vc> a
#define vvc2(a, b) vec<vc> a(b)
#define vvc3(a, b, c) vec<vc> a(b,vc(c))
#define vvc4(a, b, c, d) vec<vc> a(b,vc(c,d))
#define vvc(...) _overloadvvc(__VA_ARGS__,vvc4,vvc3,vvc2 ,vvc1)(__VA_ARGS__)

using vp = vector<P>;
#define _overloadvvp(_1, _2, _3, _4, name, ...) name
#define vvp1(a) vec<vp> a
#define vvp2(a, b) vec<vp> a(b)
#define vvp3(a, b, c) vec<vp> a(b,vp(c))
#define vvp4(a, b, c, d) vec<vp> a(b,vp(c,d))

using vt = vector<T>;
#define _overloadvvt(_1, _2, _3, _4, name, ...) name
#define vvt1(a) vec<vt> a
#define vvt2(a, b) vec<vt> a(b)
#define vvt3(a, b, c) vec<vt> a(b,vt(c))
#define vvt4(a, b, c, d) vec<vt> a(b,vt(c,d))

#define v3i(a, b, c, d) vector<vector<vi>> a(b, vector<vi>(c, vi(d)))
#define v3d(a, b, c, d) vector<vector<vd>> a(b, vector<vd>(c, vd(d)))
#define v3m(a, b, c, d) vector<vector<vm>> a(b, vector<vm>(c, vm(d)))

#define _vvi vector<vi>
#define _vvl vector<vl>
#define _vvb vector<vb>
#define _vvs vector<vs>
#define _vvd vector<vd>
#define _vvc vector<vc>
#define _vvp vector<vp>

#define PQ priority_queue<ll, vector<ll>, greater<ll> >
#define tos to_string
using mapi = map<int, int>;
using mapd = map<dou, int>;
using mapc = map<char, int>;
using maps = map<str, int>;
using seti = set<int>;
using setd = set<dou>;
using setc = set<char>;
using sets = set<str>;
using qui = queue<int>;
#define bset bitset
#define uset unordered_set
#define mset multiset
#define umap unordered_map
#define umapi unordered_map<int,int>
#define umapp unordered_map<P,int>
#define mmap multimap

//マクロ 繰り返し
#define _overloadrep(_1, _2, _3, _4, name, ...) name
# define _rep(i, n) for(int i = 0,_lim=n; i < _lim ; i++)
#define repi(i, m, n) for(int i = m,_lim=n; i < _lim ; i++)
#define repadd(i, m, n, ad) for(int i = m,_lim=n; i < _lim ; i+= ad)
#define rep(...) _overloadrep(__VA_ARGS__,repadd,repi,_rep,)(__VA_ARGS__)
#define _rer(i, n) for(int i = n; i >= 0 ; i--)
#define reri(i, m, n) for(int i = m,_lim=n; i >= _lim ; i--)
#define rerdec(i, m, n, dec) for(int i = m,_lim=n; i >= _lim ; i-=dec)
#define rer(...) _overloadrep(__VA_ARGS__,rerdec,reri,_rer,)(__VA_ARGS__)
#define fora(a, b) for(auto&& a : b)
#define forg(gi, ve) for (int gi = 0, f, t, c; gi < ve.size() && (f = ve[gi].f, t = ve[gi].t, c = ve[gi].c, true); gi++)
#define fort(gi, ve) for (int gi = 0, f, t, c; gi < ve.size() && (f = ve[gi].f, t = ve[gi].t, c = ve[gi].c, true); gi++)if(t!=p)
//#define fort(gi, ve) for (int gi = 0, f, t, c;gi<ve.size()&& (gi+= (ve[gi].t==p))< ve.size() && (f = ve[gi].f,t=ve[gi].t, c = ve[gi].c,true); gi++)

//マクロ 定数
#define k3 1010
#define k4 10101
#define k5 101010
#define k6 1010101
#define k7 10101010
const int inf = (int) 1e9 + 100;
const ll linf = (ll) 1e18 + 100;
const double eps = 1e-9;
const double PI = 3.1415926535897932384626433832795029L;
ll ma = numeric_limits<ll>::min();
ll mi = numeric_limits<ll>::max();
const int y4[] = {-1, 1, 0, 0};
const int x4[] = {0, 0, -1, 1};
const int y8[] = {0, 1, 0, -1, -1, 1, 1, -1};
const int x8[] = {1, 0, -1, 0, 1, -1, 1, -1};

//マクロ省略形 関数等
#define arsz(a) (sizeof(a)/sizeof(a[0]))
#define sz(a) ((int)(a).size())
#define rs resize
#define mp make_pair
#define pb push_back
#define pf push_front
#define eb emplace_back
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()

inline void sort(string &a) { sort(a.begin(), a.end()); }
template<class T> inline void sort(vector<T> &a) { sort(a.begin(), a.end()); };
template<class T> inline void sort(vector<T> &a, int len) { sort(a.begin(), a.begin() + len); };
template<class T, class F> inline void sort(vector<T> &a, F f) { sort(a.begin(), a.end(), [&](T l, T r) { return f(l) < f(r); }); };
enum ___pcomparator {
    fisi, fisd, fdsi, fdsd, sifi, sifd, sdfi, sdfd
};
inline void sort(vector<P> &a, ___pcomparator type) {
    switch (type) {
        case fisi:
            sort(all(a), [&](P l, P r) { return l.fi != r.fi ? l.fi < r.fi : l.se < r.se; });
            break;
        case fisd:
            sort(all(a), [&](P l, P r) { return l.fi != r.fi ? l.fi < r.fi : l.se > r.se; });
            break;
        case fdsi:
            sort(all(a), [&](P l, P r) { return l.fi != r.fi ? l.fi > r.fi : l.se < r.se; });
            break;
        case fdsd:
            sort(all(a), [&](P l, P r) { return l.fi != r.fi ? l.fi > r.fi : l.se > r.se; });
            break;
        case sifi:
            sort(all(a), [&](P l, P r) { return l.se != r.se ? l.se < r.se : l.fi < r.fi; });
            break;
        case sifd:
            sort(all(a), [&](P l, P r) { return l.se != r.se ? l.se < r.se : l.fi > r.fi; });
            break;
        case sdfi:
            sort(all(a), [&](P l, P r) { return l.se != r.se ? l.se > r.se : l.fi < r.fi; });
            break;
        case sdfd:
            sort(all(a), [&](P l, P r) { return l.se != r.se ? l.se > r.se : l.fi > r.fi; });
            break;
    }
};
inline void sort(vector<T> &a, ___pcomparator type) {
    switch (type) {
        case fisi:
            sort(all(a), [&](T l, T r) { return l.f != r.f ? l.f < r.f : l.s < r.s; });
            break;
        case
            fisd:
            sort(all(a), [&](T l, T r) { return l.f != r.f ? l.f < r.f : l.s > r.s; });
            break;
        case
            fdsi:
            sort(all(a), [&](T l, T r) { return l.f != r.f ? l.f > r.f : l.s < r.s; });
            break;
        case
            fdsd:
            sort(all(a), [&](T l, T r) { return l.f != r.f ? l.f > r.f : l.s > r.s; });
            break;
        case
            sifi:
            sort(all(a), [&](T l, T r) { return l.s != r.s ? l.s < r.s : l.f < r.f; });
            break;
        case
            sifd:
            sort(all(a), [&](T l, T r) { return l.s != r.s ? l.s < r.s : l.f > r.f; });
            break;
        case
            sdfi:
            sort(all(a), [&](T l, T r) { return l.s != r.s ? l.s > r.s : l.f < r.f; });
            break;
        case
            sdfd:
            sort(all(a), [&](T l, T r) { return l.s != r.s ? l.s > r.s : l.f > r.f; });
            break;
    }
};
template<class T> inline void rsort(vector<T> &a) { sort(a.begin(), a.end(), greater<T>()); };
template<class T> inline void rsort(vector<T> &a, int len) { sort(a.begin(), a.begin() + len, greater<T>()); };
template<class U, class F> inline void rsort(vector<U> &a, F f) { sort(a.begin(), a.end(), [&](U l, U r) { return f(l) > f(r); }); };
template<class U> inline void sortp(vector<U> &a, vector<U> &b) {
    vp c;
    int n = sz(a);
    assert(n == sz(b));
    rep(i, n)c.eb(a[i], b[i]);
    sort(c);
    rep(i, n) {
        a[i] = c[i].first;
        b[i] = c[i].second;;
    }
};
//F = T<T>
//例えばreturn p.fi + p.se;
template<class U, class F> inline void sortp(vector<U> &a, vector<U> &b, F f) {
    vp c;
    int n = sz(a);
    assert(n == sz(b));
    rep(i, n)c.eb(a[i], b[i]);
    sort(c, f);
    rep(i, n) {
        a[i] = c[i].first;
        b[i] = c[i].second;
    }
};
template<class U, class F> inline void sortp(vector<U> &a, vector<U> &b, char type) {
    vp c;
    int n = sz(a);
    assert(n == sz(b));
    rep(i, n)c.eb(a[i], b[i]);
    sort(c, type);
    rep(i, n) {
        a[i] = c[i].first;
        b[i] = c[i].second;
    }
};
template<class U> inline void rsortp(vector<U> &a, vector<U> &b) {
    vp c;
    int n = sz(a);
    assert(n == sz(b));
    rep(i, n)c.eb(a[i], b[i]);
    rsort(c);
    rep(i, n) {
        a[i] = c[i].first;
        b[i] = c[i].second;
    }
};
template<class U, class F> inline void rsortp(vector<U> &a, vector<U> &b, F f) {
    vp c;
    int n = sz(a);
    assert(n == sz(b));
    rep(i, n)c.eb(a[i], b[i]);
    rsort(c, f);
    rep(i, n) {
        a[i] = c[i].first;
        b[i] = c[i].second;
    }
};
template<class U> inline void sortt(vector<U> &a, vector<U> &b, vector<U> &c) {
    vt r;
    int n = sz(a);
    assert(n == sz(b));
    assert(n == sz(c));
    rep(i, n)r.eb(a[i], b[i], c[i]);
    sort(r);
    rep(i, n) {
        a[i] = r[i].f;
        b[i] = r[i].s;
        c[i] = r[i].t;
    }
};
template<class U, class F> inline void sortt(vector<U> &a, vector<U> &b, vector<U> &c, F f) {
    vt r;
    int n = sz(a);
    assert(n == sz(b));
    assert(n == sz(c));
    rep(i, n)r.eb(a[i], b[i], c[i]);
    sort(r, f);
    rep(i, n) {
        a[i] = r[i].f;
        b[i] = r[i].s;
        c[i] = r[i].t;
    }
};
template<class U, class F> inline void rsortt(vector<U> &a, vector<U> &b, vector<U> &c, F f) {
    vt r;
    int n = sz(a);
    assert(n == sz(b));
    assert(n == sz(c));
    rep(i, n)r.eb(a[i], b[i], c[i]);
    rsort(r, f);
    rep(i, n) {
        a[i] = r[i].f;
        b[i] = r[i].s;
        c[i] = r[i].t;
    }
};
template<class T> inline void sort2(vector<vector<T>> &a) { for (int i = 0, n = a.size(); i < n; i++)sort(a[i]); }
template<class T> inline void rsort2(vector<vector<T>> &a) { for (int i = 0, n = a.size(); i < n; i++)rsort(a[i]); }
template<typename A, size_t N, typename T> void fill(A (&a)[N], const T &v) { rep(i, N)a[i] = v; }
template<typename A, size_t N, size_t O, typename T> void fill(A (&a)[N][O], const T &v) { rep(i, N)rep(j, O)a[i][j] = v; }
template<typename A, size_t N, size_t O, size_t P, typename T> void fill(A (&a)[N][O][P], const T &v) { rep(i, N)rep(j, O)rep(k, P)a[i][j][k] = v; }
template<typename A, size_t N, size_t O, size_t P, size_t Q, typename T> void fill(A (&a)[N][O][P][Q], const T &v) { rep(i, N)rep(j, O)rep(k, P)rep(l, Q)a[i][j][k][l] = v; }
template<typename A, size_t N, size_t O, size_t P, size_t Q, size_t R, typename T> void fill(A (&a)[N][O][P][Q][R], const T &v) { rep(i, N)rep(j, O)rep(k, P)rep(l, Q)rep(m, R)a[i][j][k][l][m] = v; }
template<typename A, size_t N, size_t O, size_t P, size_t Q, size_t R, size_t S, typename T> void fill(A (&a)[N][O][P][Q][R][S], const T &v) { rep(i, N)rep(j, O)rep(k, P)rep(l, Q)rep(m, R)rep(n, S)a[i][j][k][l][m][n] = v; }

template<typename V, typename T>
void fill(V &xx, const T vall) {
    xx = vall;
}
template<typename V, typename T>
void fill(vector<V> &vecc, const T vall) {
    for (auto &&vx: vecc) fill(vx, vall);
}

//@汎用便利関数 入力
template<typename T = int> T _in() {
    T x;
    cin >> x;
    return (x);
}
#define _overloadin(_1, _2, _3, _4, name, ...) name
#define in0() _in()
#define in1(a) cin>>a
#define in2(a, b) cin>>a>>b
#define in3(a, b, c) cin>>a>>b>>c
#define in4(a, b, c, d) cin>>a>>b>>c>>d
#define in(...) _overloadin(__VA_ARGS__,in4,in3,in2 ,in1,in0)(__VA_ARGS__)

#define _overloaddin(_1, _2, _3, _4, name, ...) name
#define din1(a) int a;cin>>a
#define din2(a, b) int a,b;cin>>a>>b
#define din3(a, b, c) int a,b,c;cin>>a>>b>>c
#define din4(a, b, c, d) int a,b,c,d;cin>>a>>b>>c>>d
#define din(...) _overloadin(__VA_ARGS__,din4,din3,din2 ,din1)(__VA_ARGS__)

#define _overloaddind(_1, _2, _3, _4, name, ...) name
#define din1d(a) int a;cin>>a;a--
#define din2d(a, b) int a,b;cin>>a>>b;a--,b--
#define din3d(a, b, c) int a,b,c;cin>>a>>b>>c;a--,b--,c--
#define din4d(a, b, c, d) int a,b,c,d;cin>>a>>b>>c>>d;;a--,b--,c--,d--
#define dind(...) _overloaddind(__VA_ARGS__,din4d,din3d,din2d ,din1d)(__VA_ARGS__)

string sin() { return _in<string>(); }
ll lin() { return _in<ll>(); }
#define na(a, n) a.resize(n); rep(i,n) cin >> a[i];
#define nao(a, n) a.resize(n+1); rep(i,n) cin >> a[i+1];
#define nad(a, n) a.resize(n); rep(i,n){ cin >> a[i]; a[i]--;}
#define na2(a, b, n) a.resize(n),b.resize(n);rep(i, n)cin >> a[i] >> b[i];
#define na2d(a, b, n) a.resize(n),b.resize(n);rep(i, n){cin >> a[i] >> b[i];a[i]--,b[i]--;}
#define na3(a, b, c, n) a.resize(n),b.resize(n),c.resize(n);   rep(i, n)cin >> a[i] >> b[i] >> c[i];
#define na3d(a, b, c, n) a.resize(n),b.resize(n),c.resize(n);   rep(i, n){cin >> a[i] >> b[i] >> c[i];a[i]--,b[i]--,c[i]--;}
#define nt(a, h, w) resize(a,h,w);rep(hi,h)rep(wi,w) cin >> a[hi][wi];
#define ntd(a, h, w) rs(a,h,w);rep(hi,h)rep(wi,w) cin >> a[hi][wi], a[hi][wi]--;
#define ntp(a, h, w) fill(a,'#');rep(hi,1,h+1)rep(wi,1,w+1) cin >> a[hi][wi];

//デバッグ
#define sp << " " <<

#define debugName(VariableName) # VariableName

#define _deb1(x) cerr <<  debugName(x)<<" = "<<x << endl
#define _deb2(x, y) cerr <<  debugName(x)<<" = "<<x<<", "<< debugName(y)<<" = "<<y<< endl
#define _deb3(x, y, z) cerr <<  debugName(x)<<" = "<<x  << ", " <<  debugName(y)<<" = "<<y <<", " debugName(z)<<" = "<<z <<endl
#define _deb4(x, y, z, a) cerr <<  debugName(x)<<" = "<<x <<", " <<   debugName(y)<<" = "<<y <<", " <<  debugName(z)<<" = "<<z <<", " <<  debugName(a)<<" = "<<a<<endl
#define _deb5(x, y, z, a, b) cerr <<  debugName(x)<<" = "<<x <<", " <<   debugName(y)<<" = "<<y <<", " <<  debugName(z)<<" = "<<z <<", " <<  debugName(a)<<" = "<<a<<", " <<  debugName(b)<<" = "<<b<<endl

#define _overloadebug(_1, _2, _3, _4, _5, name, ...) name
#define debug(...) _overloadebug(__VA_ARGS__,_deb5,_deb4,_deb3,_deb2,_deb1)(__VA_ARGS__)
#define deb(...) _overloadebug(__VA_ARGS__,_deb5,_deb4,_deb3,_deb2,_deb1)(__VA_ARGS__)
#define debugline(x) cerr << x << " " << "(L:" << __LINE__ << ")" << '\n'
void ole() {
#ifdef _DEBUG
    debugline("ole");
    exit(0);
#endif
    string a = "a";
    rep(i, 30)a += a;
    rep(i, 1 << 17)cout << a << endl;
    cout << "OLE 出力長制限超過" << endl;
    exit(0);
}
void tle() { while (inf)cout << inf << endl; }
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll gcd(vi b) {
    ll res = b[0];
    for (auto &&v :b)res = gcd(v, res);
    return res;
}
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
ll rev(ll a) {
    ll res = 0;
    while (a) {
        res *= 10;
        res += a % 10;
        a /= 10;
    }
    return res;
}
template<class T> void rev(vector<T> &a) {
    reverse(all(a));
}
void rev(string &a) {
    reverse(all(a));
}
ll ceil(ll a, ll b) {
    if (b == 0) {
        debugline("ceil");
        deb(a, b);
        ole();
        return -1;
    } else return (a + b - 1) / b;
}
ll sqrt(ll a) {
    if (a < 0) {
        debugline("sqrt");
        deb(a);
        ole();
    }
    ll res = (ll) std::sqrt(a);
    while (res * res < a)res++;
    return res;
}
double log(double e, double x) { return log(x) / log(e); }
ll sig(ll t) { return (1 + t) * t / 2; }
ll sig(ll s, ll t) { return (s + t) * (t - s + 1) / 2; }

vi divisors(int v) {
    vi res;
    double lim = std::sqrt(v);
    for (int i = 1; i <= lim; ++i) {
        if (v % i == 0) {
            res.pb(i);
            if (i != v / i)res.pb(v / i);
        }
    }
    return res;
}

vb isPrime;
vi primes;

void setPrime() {
    int len = 4010101;
    isPrime.resize(4010101);
    fill(isPrime, true);
    isPrime[0] = isPrime[1] = false;
    for (int i = 2; i <= sqrt(len) + 5; ++i) {
        if (!isPrime[i])continue;
        for (int j = 2; i * j < len; ++j) {
            isPrime[i * j] = false;
        }
    }
    rep(i, len)if (isPrime[i])primes.pb(i);
}

vi factorization(int v) {
    int tv = v;
    vi res;
    if (isPrime.size() == 0)setPrime();
    for (auto &&p :primes) {
        if (v % p == 0)res.push_back(p);
        while (v % p == 0) {
            v /= p;
        }
        if (v == 1 || p * p > tv)break;
    }
    if (v > 1)res.pb(v);
    return res;
}
inline bool inside(int h, int w, int H, int W) { return h >= 0 && w >= 0 && h < H && w < W; }
inline bool inside(int v, int l, int r) { return l <= v && v < r; }
#define ins inside
ll u(ll a) { return a < 0 ? 0 : a; }
template<class T> vector<T> u(const vector<T> &a) {
    vector<T> ret = a;
    fora(v, ret)v = u(v);
    return ret;
}
#define MIN(a) numeric_limits<a>::min()
#define MAX(a) numeric_limits<a>::max()

int n, m, k, d, H, W, x, y, z, q;
int cou;
vi a, b, c;
vvi (s, 0, 0);
vvc (ba, 0, 0);
vp p;

#define segmin(M) [](M a, M b){return a < b ? a : b;}, [](int len, M x){return x;}, MAX(M),MIN(M)
#define segmax(M) [](M a, M b){return a > b ? a : b;}, [](int len, M x){return x;}, MIN(M),MAX(M)
#define segsum(M) [](M a, M b){return a+b;} , [](int len, M x){return len * x;}, 0,MIN(M)
#define segxor(M) [](M a, M b){return a^b;} , [](int len, M x){return (len&1) ? x : 0;},MIN(M)

template<typename T>
struct segmentLazyUpdate {
    using F = function<T(T, T)>;
    using G = function<T(int, T)>;
//    using H = function<T(T, T)>;
    int n, height;
    F fvv;//(v, v)
    G fvl;//(v, l, len)
//    H fll;//(l, l)
    T ve; //演算における単位元
    T le; //作用素に対しての単位元
    vector<T> dat;
    vector<T> laz;
    vi len;
    segmentLazyUpdate(vector<T> a, F fvv, G g, T ve, T le) : fvv(fvv), fvl(g), ve(ve), le(le) {
        n = 1;
        int n_ = a.size();
        height = 0;
        while (n <= n_) n <<= 1, height++;
        dat.assign(n << 1, ve);
        laz.assign(n << 1, le);
        len.assign(n << 1, 0);
        int l = 1, v = n;
        rep(i, 1, n << 1) {
            if ((l << 1) == i) {
                l <<= 1;
                v >>= 1;
            }
            len[i] = v;
        }

        for (int i = 0; i < n_; i++) dat[n + i] = a[i];
        for (int i = n - 1; i; i--)
            dat[i] = fvv(dat[(i << 1) | 0], dat[(i << 1) | 1]);
    }

    //おそらく1-indexed
    T reflect(int k) {
        return laz[k] == le ? dat[k] : fvl(len[k], laz[k]);
    }
    void eval(int k) {
        if (laz[k] == le) return;
        laz[(k << 1)] = laz[k];
        laz[(k << 1) | 1] = laz[k];
        dat[k] = reflect(k);
        laz[k] = le;
    }
    void thrust(int k) {
        for (int i = height; i; i--) eval(k >> i);
    }
    void recalc(int k) {
        while (k >>= 1)dat[k] = fvv(reflect((k << 1) | 0), reflect((k << 1) | 1));
    }
    void update(int a, int b, T x) {
        thrust(a += n);
        thrust(b += n - 1);
        for (int l = a, r = b + 1; l < r; l >>= 1, r >>= 1) {
            if (l & 1) laz[l] = x, l++;
            if (r & 1) --r, laz[r] = x;
        }
        recalc(a);
        recalc(b);
    }
    void set_val(int a, T x) {
        thrust(a += n);
        dat[a] = x;
        laz[a] = le;
        recalc(a);
    }
    T get(int a, int b) {
        thrust(a += n);
        thrust(b += n - 1);
        T vl = ve, vr = ve;
        for (int l = a, r = b + 1; l < r; l >>= 1, r >>= 1) {
            if (l & 1) vl = fvv(vl, reflect(l++));
            if (r & 1) vr = fvv(reflect(--r), vr);
        }
        return fvv(vl, vr);
    }
    void debu() {
        rep(i, min(n, 10ll)) {
            cout << get(i, i + 1) << " ";
        }
        cout << "" << endl;
    }
};
#define seg segmentLazyUpdate
#define ruq segmentLazyUpdate
//seg<int> st(vi(k5),segmin(int));
signed main() {
    cin >> n>>q;
    seg<int> st(vi(k5,(1ll<<31)-1),segmin(int));
    rep(i,q){
        int c,s,t,x;
        cin>>c>>s>>t;
        if(c==0){
            cin>>x;
            st.update(s,t+1,x);
        }else{
            cout << st.get(s,t+1) << endl;
        }
    }

    return 0;
}

RMQ and RUQ

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

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

find(s, t): report the minimum element in as, as+1, ..., at.

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

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 update(s, t, x) and '1' denotes find(s, t).

Output

For each find operation, print the minimum value.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

0 ≤ s ≤ t < n

0 ≤ x < 231−1

Sample Input 1

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

Sample Output 1

1
2

Sample Input 2

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

Sample Output 2

2147483647
5


#include <bits/stdc++.h>
#define loop(n) for (int ngtkana_is_genius = 0; ngtkana_is_genius < int(n); ngtkana_is_genius++)
#define rep(i, begin, end) for(int i = int(begin); i < int(end); i++)
#define all(v) v.begin(), v.end()
#define rand(l, r) std::uniform_int_distribution<>(l, r)(mt)
using lint = long long;
auto mt = std::mt19937_64(std::random_device{}());
auto cmn = [](auto& a, auto b){if (a > b) {a = b; return true;} return false;};
auto cmx = [](auto& a, auto b){if (a < b) {a = b; return true;} return false;};
void debug_impl() { std::cerr << std::endl; }
template <typename Head, typename... Tail>
void debug_impl(Head head, Tail... tail){
  std::cerr << " " << head;
  debug_impl(tail...);
}
#ifdef STOPIT
#define debug(...) 0
#else
#define debug(...)\
do {\
  std::cerr << std::boolalpha << "[" << #__VA_ARGS__ << "]:";\
  debug_impl(__VA_ARGS__);\
  std::cerr << std::noboolalpha;\
} while (false)
#endif

template < typename Container, typename Value = typename Container::value_type, std::enable_if_t<!std::is_same< Container, std::string >::value, std::nullptr_t> = nullptr>
std::istream& operator>> (std::istream& is, Container& v)
  { for (auto & x : v) { is >> x; } return is; }

template < typename Container, typename Value = typename Container::value_type, std::enable_if_t<!std::is_same< Container, std::string >::value, std::nullptr_t> = nullptr >
std::ostream& operator<< (std::ostream& os, Container const& v) {
 os << "{";
  for (auto it = v.begin(); it != v.end(); it++)
    {os << (it != v.begin() ? "," : "") << *it;}
  return os << "}";
}

int main() {
  std::cin.tie(0); std::cin.sync_with_stdio(false);
  lint n, q; std::cin >> n >> q;
  std::vector<int>a(n); std::cin>>a;
  loop(q){
    lint X; std::cin >> X;
    lint ans = 0, sum = 0;
    for(lint l=0,r=0;l<n;l++) {
      while(r<n && sum+a[r]<=X){
        sum+=a[r];
        r++;
      }
      // debug(sum,std::vector<int>(a.begin()+l,a.begin()+r));
      ans+=r-l;
      sum-=a[l];
    }
    std::cout << ans << std::endl;
  }
  return 0;
}

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

The Number of Windows

For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and $Q$ integers $x_i$ as queries, for each query, print the number of combinations of two integers $(l, r)$ which satisfies the condition: $1 \leq l \leq r \leq N$ and $a_l + a_{l+1} + ... + a_{r-1} + a_r \leq x_i$.

Constraints

$1 \leq N \leq 10^5$

$1 \leq Q \leq 500$

$1 \leq a_i \leq 10^9$

$1 \leq x_i \leq 10^{14}$

Input

The input is given in the following format.

$N$ $Q$

$a_1$ $a_2$ ... $a_N$

$x_1$ $x_2$ ... $x_Q$

Output

For each query, print the number of combinations in a line.

Sample Input 1

6 5
1 2 3 4 5 6
6 9 12 21 15

Sample Output 1

9
12
15
21
18


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

int main(){
    int n, q;
    cin >> n >> q;
    vector<ll> a(n);
    for(int i = 0; i < n; i++)  cin >> a[i];
    while(q-- > 0){
        ll x;
        cin >> x;
        int l = 0, r = 0;
        ll sum = 0, ans = 0;
        while(l < n){
            while(r < n && sum + a[r] <= x) sum += a[r++];
            ans += r-l;
            if(l == r)  l = ++r;
            else        sum -= a[l++];
        }
        cout << ans << endl;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
int N,T;

vector< P > t;

int main(){
  cin>>N>>T;
  for(int i=0;i<N;i++){
    int l,r;
    cin>>l>>r;
    t.push_back( P(l,1) );
    t.push_back( P(r,-1) );
  }
  sort(t.begin(),t.end());
  int sum=0;
  int ans=0;
  for(int i=0;i<N+N;i++){
    sum+=t[i].second;
    ans=max(ans,sum);
  }
  cout<<ans<<endl;
  return 0;
}

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

The Maximum Number of Customers

$N$ persons visited a restaurant. The restaurant is open from 0 to $T$. The $i$-th person entered the restaurant at $l_i$ and left at $r_i$. Find the maximum number of persons during the business hours.

Constraints

$ 1 \leq N \leq 10^5 $

$ 1 \leq T \leq 10^5 $

$ 0 \leq l_i < r_i \leq T $

Input

The input is given in the following format.

$N$ $T$

$l_1$ $r_1$

$l_2$ $r_2$

:

$l_N$ $r_N$

Output

Print the maximum number of persons in a line.

Sample Input 1

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

Sample Output 1

4

Sample Input 2

2 2
0 1
1 2

Sample Output 2

1


#include <iostream>
#include <vector>
#include <unordered_set>
#include <set>

using namespace std;

const int Inf = 10000 * 100000 + 100;

// ????¢?????????????????????§, ????????????????°??????????????????¢??¢?´¢??????
inline int linear_search(const set<int>& st, const vector<int>& cost){
  int ans = *st.begin();
  int min_cost = Inf;
  for(const auto u: st){
    if(cost[u] < min_cost){
      ans = u;
      min_cost = cost[u];
    }
  }
  return ans;
}

int main(){
  ios::sync_with_stdio(false);
  cin.tie(0);
  int V,E,R;
  cin >> V >> E >> R;
  vector<int> s(E),t(E),d(E);
  vector<vector<int> > edge(V);
  for(int i = 0; i < E; ++i){
    cin >> s[i] >> t[i] >> d[i];
    edge[s[i]].emplace_back(i);
  }
  vector<int> cost(V, Inf);
  cost[R] = 0;

  set<int> q;
  for(int i = 0; i < V; ++i){
    q.emplace(i);
  }

  while(!q.empty()){
    // ?¢?????????????????????? u ??¨??????
    int u = linear_search(q, cost);
    q.erase(u);

    for(auto i : edge[u]){
      // u ????§??????§?¢????????????§???????????????????????????????????????
      // ????????? v ??¨??????.
      int v = t[i];
      if(q.find(v) != q.end()){
        // ????????§?????????????????????
        if(cost[u] + d[i] < cost[v]){
          cost[v] = cost[u] + d[i];
        }
      }
    }
  }

  for(int i = 0; i < V; ++i){
    if(cost[i] == Inf)
      cout << "INF";
    else
      cout << cost[i];

    cout << endl;
  }
}

Single Source Shortest Path

For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).

Input

An edge-weighted graph G (V, E) and the source r.

|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1

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

si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.

Output

Print the costs of SSSP in the following format.

c0
c1
:
c|V|-1

The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.

Constraints

1 ≤ |V| ≤ 100000

0 ≤ di ≤ 10000

0 ≤ |E| ≤ 500000

There are no parallel edges

There are no self-loops

Sample Input 1

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

Sample Output 1

0
1
3
4

Sample Input 2

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

Sample Output 2

3
0
2
INF


/**
*	created: 26.09.2020 21:02:56
**/
#include <bits/stdc++.h>
// #include <boost/multiprecision/cpp_int.hpp>
// using bint = boost::multiprecision::cpp_int;
using namespace std;
// #define endl '\n'
#define int long long
#define rep(i,n) for (int i = 0; i < (int)(n); i++)
#define rrep(i,n) for (int i = (int)(n - 1); i >= 0; i--)
#define rep2(i,s,n) for (int i = (s); i < (int)(n); i++)
#define len(x) ll(x.size())
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define pcnt(bit) __builtin_popcountll(bit)
using ll = long long;
using P = pair<int,int>;
const long double pi = acos(-1.0);
const int MAX = 1000010;
const int INF = 1ll << 60;
const int MOD = 1000000007;
// const int MOD = 998244353;
template<typename T> inline bool chmax(T &a, T b) {if (a < b) {a = b; return 1;} return 0;}
template<typename T> inline bool chmin(T &a, T b) {if (b < a) {a = b; return 1;} return 0;}
inline void print(P a) {cout << a.first << " " << a.second << endl;}
template<typename T> T bpow(T a, ll n) {T r(1); while(n) {if (n & 1) r *= a; a *= a; n >>= 1;} return r;}
struct faster_io {faster_io() {cin.tie(0); ios_base::sync_with_stdio(false);}} faster_io_;

// UnionFind
struct UnionFind {
    vector<int> par;
    UnionFind(int n) : par(n,-1) {}
    int root(int x) {
        if (par[x] < 0) return x;
        return par[x] = root(par[x]);
    }
    bool merge(int x, int y) {
        x = root(x); y = root(y);
        if (x == y) return false;
        if (par[x] > par[y]) swap(x,y);
        par[x] += par[y]; par[y] = x;
        return true;
    }
    bool issame(int x, int y) {return root(x) == root(y);}
    int size(int x) {return -par[root(x)];}
};

signed main() {
    int n, m; cin >> n >> m;
    UnionFind uf(n);
    rep(i,m) {
        int a, b; cin >> a >> b;
        a--; b--;
        uf.merge(a,b);
    }
    set<int> st;
    rep(i,n) {
        st.insert(uf.root(i));
    }
    cout << st.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).


#include <bits/stdc++.h>
#include <atcoder/all>
#define rep(i, n) for(long long int i = 0; i < n; i++)
#define _rep(i, m, n) for(long long int i = m; i < n; i++)
using namespace std;
using namespace atcoder;
typedef long long ll;
typedef pair<int, int> P;
const ll mod = 1000000007;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
string Yes[2] = {"Yes", "No"};

using Graph = vector<vector<int>>;
Graph G;

/*------------------------------------------------------------------*/
template<class Monoid> struct SegTree {
    using Func = function<Monoid(Monoid, Monoid)>;
    const Func F;
    const Monoid UNITY;
    int SIZE_R;
    vector<Monoid> dat;

    SegTree(int n, const Func f, const Monoid &unity): F(f), UNITY(unity) { init(n); }
    void init(int n) {
        SIZE_R = 1;
        while (SIZE_R < n) SIZE_R *= 2;
        dat.assign(SIZE_R * 2, UNITY);
    }

    /* set, a is 0-indexed */
    void set(int a, const Monoid &v) { dat[a + SIZE_R] = v; }
    void build() {
        for (int k = SIZE_R - 1; k > 0; --k)
            dat[k] = F(dat[k*2], dat[k*2+1]);
    }

    /* update a, a is 0-indexed */
    void update(int a, const Monoid &v) {
        int k = a + SIZE_R;
        dat[k] = v;
        while (k >>= 1) dat[k] = F(dat[k*2], dat[k*2+1]);
    }

    /* get [a, b), a and b are 0-indexed */
    Monoid get(int a, int b) {
        Monoid vleft = UNITY, vright = UNITY;
        for (int left = a + SIZE_R, right = b + SIZE_R; left < right; left >>= 1, right >>= 1) {
            if (left & 1) vleft = F(vleft, dat[left++]);
            if (right & 1) vright = F(dat[--right], vright);
        }
        return F(vleft, vright);
    }
    inline Monoid operator [] (int a) { return dat[a + SIZE_R]; }

    /* debug */
    void print() {
        for (int i = 0; i < SIZE_R; ++i) {
            cout << (*this)[i];
            if (i != SIZE_R-1) cout << ",";
        }
        cout << endl;
    }
};

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

    int n, k; cin >> n >> k;
    vector<ll> a(n), aa(n);
    rep(i, n){
        cin >> a[i];
        aa[i] = a[i];
    }
    sort(aa.begin(), aa.end());
    aa.erase(unique(aa.begin(), aa.end()), aa.end());
    SegTree<int> dp(n + 1,
                    [](int a, int b) { return max(a, b); },
                    0);

    ll ans = 0;
    rep(i, n){
        ll left = lower_bound(aa.begin(), aa.end(), a[i] - k) - aa.begin() + 1;
        ll pos = lower_bound(aa.begin(), aa.end(), a[i]) - aa.begin() + 1;
        ll right =lower_bound(aa.begin(), aa.end(), a[i] + k) - aa.begin() + 1;

        ll x = dp.get(left - 1, right);
        if(dp.get(left - 1, right + 1) < x + 1){
            dp.update(pos, x + 1);
            ans = max(ans, x + 1);
        }
    }
    cout << ans << endl;
}

Score : 400 points

Problem Statement

You are given a sequence A_1, A_2, ..., A_N and an integer K.

Print the maximum possible length of a sequence B that satisfies the following conditions:

B is a (not necessarily continuous) subsequence of A.

For each pair of adjacents elements of B, the absolute difference of the elements is at most K.

Constraints

1 \leq N \leq 300,000

0 \leq A_i \leq 300,000

0 \leq K \leq 300,000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1
A_2
:
A_N

Output

Print the answer.

Sample Input 1

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

Sample Output 1

7

For example, B = (1, 4, 3, 6, 9, 7, 4) satisfies the conditions.

It is a subsequence of A = (1, 5, 4, 3, 8, 6, 9, 7, 2, 4).

All of the absolute differences between two adjacent elements (|1-4|, |4-3|, |3-6|, |6-9|, |9-7|, |7-4|) are at most K = 3.


#include <iostream>
#include <vector>

#define _GLIBCXX_DEBUG

using namespace std;
int main() {
	int n = 0,c=0,d=0,f=0;
	bool flag=false;

	cin >> n;
	vector<int>a(n);
	vector<int>b(n);

	for (int i = 0; i < n; i++) {
		cin >> a.at(i) >>b.at(i);
	}

	for (int i = 0; i < n; i++) {
		if (a.at(i)==b.at(i)) {
			f++;
			if (f == 3)
				flag = true;
		}
		else
			f = 0;
		c = a.at(i);
		d = b.at(i);
	}

	if (flag == true)
		cout << "Yes";
	else
		cout << "No";
}

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


#include <iostream>
using namespace std;
int main()
{
	long long tc, a, b, m = 0, k = 0;
	cin >> tc;
	while (tc--)
	{
		cin >> a >> b;
		if (a == b)
			k++;
		else
		{
			if (k == 3)
			{
				m = 1;
			}
			k = 0;
		}
	}
	if (m)
		cout << "Yes";
	else
		cout << "No";
}


#include<bits/stdc++.h>
using namespace std;
#define ld long double
#define pb push_back
#define mp make_pair
#define fi(i,start,end) for(int i=start; i < end ; ++i)
#define Fastio ios_base::sync_with_stdio(false); cin.tie(NULL);
//#define mod 1000000007

using namespace std;

int main()
{
	int n;
	cin>>n;
	int a,b;
	int count=0;
	int flag=0;
	while(n--)
    {
        cin>>a>>b;
        if(a==b){count++;}
        if(a!=b){count=0;}
        if(count ==3){flag=1;}
    }
    if(flag)
        cout<<"Yes";
    else
        cout<<"No";
}


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef pair<ll,ll> P;
typedef string str;
typedef vector<P> vp;
typedef vector<string> vs;
typedef vector<bool> vb;

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

#define rep(i,m,n) for(ll i=m;i<n;i++)
#define repr(i,m,n) for(ll i=m-1;i>=n;i--)
#define fi first
#define se second
#define chmax(x,y) x=max(x,y)
#define chmin(x,y) x=min(x,y)
#define eb(x) emplace_back(x)
#define pb(x) pop_back(x)
#define all(x) x.begin(),x.end()
#define allr(x) x.rbegin(),x.rend()
#define sum(x) accumulate(all(x),0)
#define lb(x,a) lower_bound(all(x),a)
#define ub(x,a) upper_bound(all(x),a)
#define pc(x) __builtin_popcount(x)
#define gll greater<ll>()

void solve(){
 ll n;
  cin >> n;
  ll now=0;
  rep(i,0,n) {
   ll a,b;
    cin >> a >> b;
    if(a==b) now++;
    else now=0;
   if(now>=3) {
     cout << "Yes" << endl;
     return;
   }
  }

  cout << "No" << endl;
}
int main(){
   cin.tie(nullptr);
  ios::sync_with_stdio(false);
  solve();
}


#pragma GCC optimize ("Ofast")
#pragma GCC target ("sse4")

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

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

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;

typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define pf push_front
#define lb lower_bound
#define ub upper_bound
#define all(x) begin(x), end(x)
#define sz(x) (int) x.size()

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353;
const int MX = 2e5+5;
const ll INF = 1e18;
const ld PI = acos((ld)-1);
const ld EPS = 1e-6;
const int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1};
const char nl = '\n';

template <typename T> inline T gcd(T a, T b) { return b ? gcd(b, a % b) : a; }
template <typename T> inline T lcm(T a, T b) { return a / gcd(a, b) * b; }
template <class T> void ckmin(T& a, T b) { a = min(a, b); }
template <class T> void ckmax(T& a, T b) { a = max(a, b); }

// (Integer/Long).bitCount(x)
int pct(int x) { return __builtin_popcount(x); }
int pctll(ll x) { return __builtin_popcountll(x); }

void setIn(string s) { freopen(s.c_str(),"r",stdin); }
void setOut(string s) { freopen(s.c_str(),"w",stdout); }
void unsyncIO() { ios_base::sync_with_stdio(0); cin.tie(0); }
void setIO(string s = "") {
	unsyncIO();
	if (sz(s)) { setIn(s+".in"), setOut(s+".out"); }
}

// Binary Exponentiation
ll pow(ll b, ll e, ll m = 0LL, ll ans = 1LL) { while (e) { if (e & 1LL) { ans *= b; if (m) ans %= m; } b *= b, e >>= 1LL; if (m) b %= m; } return ans; }

void solve(int tcn) {
	int n;
	cin >> n;
	ll ans = 0LL;
	for (ll i = 1; i <= n; ++i) {
		if (i * i < n) {
			++ans;
		}
		for (ll j = i + 1; i * j < n; ++j) {
			ans += 2;
		}
	}
	cout << ans << nl;
}

int main() {
    setIO();

    int t = 1; //cin >> t;
	for (int i = 1; i <= t; ++i) {
		//cout << "Case #" << i << ": ";
		solve(i);
	}
	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>
#define ll long long
#define vi vector<int>
#define vll vector<ll>
#define F first
#define S second
#define pb push_back
#define f(i,s,n) for(int i=(int)s;i<=(int)n;++i)
#define Fast ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
void solve()
{
	ll n;cin>>n;
	ll k=n;
	ll ans=0;
	for(int i=1;i<n;i++){
		k=n-i;
		int cnt=0;
		for(ll J=1;J*J<=k;J++){
			if(k%J==0){
				if(J!=k/J){
					cnt+=2;
				}
				else
					++cnt;
			}
		}
		ans+=(cnt);
	}
	cout<<ans<<'\n';
}
int main()
{	Fast;
//	int t;cin>>t;
//	while(t--)
	solve();
}


#include <iostream>
#include <vector>
#include <string>
#include <list>
#include <queue>
#include <algorithm>
#define rep(i, n) for(i = 0; i < (n); i++)
#define chmax(x, y) x = max(x, y)
#define chmin(x, y) x = min(x, y)
#define MOD 998244353
#define PI 3.14159265358979323846
#define INF 1 << 30

using namespace std;
typedef long long ll;
typedef pair<int, int> pp;
typedef struct {
	int l, r;
} area;

int main(void) {
	int num, i, j, k;
	cin >> num >> k;
	vector<ll> dp(num + 2, 0);
	vector<area> a(k);
	rep(i, k)
		cin >> a[i].l >> a[i].r;
	dp[1] = 1;
	dp[2] = -1;
	for (i = 1; i < num; i++) {
		rep(j, k) {
			dp[min(i + a[j].l, num + 1)] += dp[i];
			dp[min(i + a[j].r + 1, num + 1)] -= dp[i];
		}
		dp[i + 1] += dp[i];
		dp[i + 1] %= MOD;
	}
	if (dp[num] < 0)
		dp[num] += MOD;
	cout << dp[num] << "\n";
	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 <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define y_n(ans) cout<<(ans?"Yes":"No")<<endl;

const long long mod = 998244353;
const long long check_m = 1e9 + 7;
const int MAX_N = 5 * 1e5 + 100;
const int MAX_n = 3 * 1e5;

int main() {
    long long n, k;
    cin >> n >> k;
    vector<long long> l(k), r(k);
    for (int i = 0; i < k; ++i) {
        cin >> l[i] >> r[i];
        r[i]++;
    }
    vector<long long> num(MAX_N, 0), chnum(MAX_N, 0);
    num[1] = 1;
    num[2] = -1;
    chnum[1] = 1;
    chnum[2] = -1;
    vector<long long> ans(MAX_n, 0), check(MAX_n, 0);
    ans[1] = num[1];
    check[1] = num[1];
    vector<long long> mod_times(MAX_N, 0);
    for (int i = 1; i < MAX_n; ++i) {
        if (i != 1) {
            ans[i] = ans[i-1] + num[i];
            ans[i] %= mod;
            while (ans[i] < 0) ans[i] += mod;

            check[i] = check[i-1] + chnum[i];
            check[i] %= check_m;
            while (check[i] < 0) check[i] += check_m;
        }

        if (ans[i] == 0 && check[i] == 0) {
            continue;
        }
        for (int j = 0; j < k; ++j) {
            num[i + l[j]] += ans[i];
            num[i + r[j]] -= ans[i];
            chnum[i + l[j]] += check[i];
            chnum[i + r[j]] -= check[i];
        }
    }
    cout << ans[n] << endl;
}


#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;
#include <fstream>
#include<string.h>
#include <algorithm>
#include<math.h>
#include<vector>
#include <queue>
#include <deque>
#define ll long long
#define M 1000000007
#define MM 998244353
#define INF 4e18
using namespace std;

typedef tree<ll, null_type, less<int>, rb_tree_tag,
             tree_order_statistics_node_update>
    ordered_set;
typedef tree<ll, null_type, less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> indexed_multiset;

int main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    /*freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);*/
    /*ll t,tcitr;
    cin>>t;
    tcitr=0;
    while(tcitr<t)
    {*/
        ll n,i,j,k;
        cin>>n>>k;
        ll pre[n+2]={};
        for(i=0;i<n;i++)
        {
            cin>>j>>k;
            pre[j]++;
            pre[k+1]--;
        }
        ll cnt=0;
        vector<ll> v;
        for(i=0;i<=n;i++)
        {
            cnt+=pre[i];
            if(cnt>0)v.push_back(i);
        }
        ll dp[n+1]={};
        dp[1]=1;
        for(i=1;i<=n;i++)
        {
            for(j=0;j<v.size();j++)
            {
                if(v[j]>i)break;
                dp[i]+=dp[i-v[j]];
                if(dp[i]>=MM)dp[i]-=MM;
            }
        }
        cout<<dp[n]<<"\n";
        /*tcitr++;
    }*/
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
typedef long long ll;
const ll INF = 1LL<<60;
/////////////////////////////////
int main(){
    int x;
    cin >> x;
    if(x==1)
        cout << 0 << endl;
    else
        cout << 1 << endl;
}

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<bits/stdc++.h>
using namespace std;
#define ll long long int
#define pii pair<long long int,long long int>
#define vi vector<long long int >
#define vvi vector<vector< long long int>>
#define MP make_pair
#define PB push_back
#define pb pop_back
#define PF push_front
#define pf pop_front
#define MOD 1000000007
#define MT make_tuple

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	ll n;
	cin>>n;
	if(n==0)
		cout<<1<<endl;
	else
		cout<<0<<endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i =0;i<n;i++)
typedef long long int ll;
#define ALL(a) a.begin(),a.end()
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
const int inf = 1<<31 - 1;
int main() {
   string s;int n,m;
  cin >>n;
  cout << (n+1) %2 << endl;
}


#include <iostream>

using namespace std;

int main(){
    long long int a, b, c, d;

    cin >> a >> b >> c >> d;

    long long int multi[4];

    multi[0] = a * c;
    multi[1] = a * d;
    multi[2] = b * c;
    multi[3] = b * d;

    long long int max = multi[0];
    for (int i= 1; i < 4; i++){
        if (max < multi[i]){
            max = multi[i];
        }
    }

    cout << max << endl;

return 0;
}

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;

#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define per(i, a, b) for(int i = a; i >= (b); --i)
#define trav(a, x) for(auto &a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
using ll = long long;
using pii = pair<int, int>;
using vi = vector<int>;

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL); cout.tie(NULL);
  ll a, b, c, d; cin >> a >> b >> c >> d;

  ll res = max(a * c, a * d);
  res = max(b * c, res);
  res = max(b * d, res);
  cout << res;
}


#include<stdio.h>
#define mod 1000000007
#define ll long long
ll sp(ll a,ll b)
{
  ll c=1;
  while(a)
  {
    if(a&1){c*=b;c%=mod;}
    b*=b;
    b%=mod;
    a>>=1;
  }
  return c;
}
int main()
{
  ll n,ans;
  scanf("%lld",&n);
  if(n==1)ans=0;
  else if(n==2)ans=2;
  else {
    ans=(sp(n,10)-2*sp(n,9)+mod)%mod;
      ans+=sp(n,8)%mod;
  }
  printf("%lld\n",ans%mod);
}

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;
#ifdef __DEBUG__
    void debug_out() { cerr << endl; }
    template <typename Head, typename... Tail>
    void debug_out(Head H, Tail... T) {cerr << " " << H; debug_out(T...);}
    #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
    #define debug(...)
#endif

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

int dx[]={1, 0, -1, 0, 1,-1, 1,-1};
int dy[]={0, 1, 0, -1, 1, 1,-1,-1};
const int INT_INF = (int)(2e9);
const ll  LL_INF = (ll)(2e18);

inline void fast_io() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); };
template<typename T, typename S> inline ostream& operator<<(ostream& os, const pair<T, S> p) { cout << "[" << p.first << ";" << p.second << "]"; return os; }
template<typename T, typename S> inline ostream& operator<<(ostream& os, const map<T, S> p) { for (auto el : p) cout << "[" << el.first << ";" << el.second << "]"; return os; }
template<typename T> inline ostream& operator<<(ostream& os, const vector<T>& v) { for (auto el : v) cout << el << " "; return os; }
template<typename T> inline ostream& operator<<(ostream& os, const deque<T>& v) { for (auto el : v) cout << el << " "; return os; }
template<typename T> inline ostream& operator<<(ostream& os, const set<T>& v) { for (auto el : v) cout << el << " "; return os; }
template<typename T> inline vector<T> fetch_vec(int sz) { vector<T> ret(sz); for (auto& elem : ret) cin >> elem; return ret; }

int N;
vector<pll> P;
inline void input(){
    fast_io();
    cin >> N;
    for (int i = 0; i < N; i++)
    {
        ll x,y; cin >> x >> y;
        P.emplace_back(x+y,x-y);
    }
}

void chmax(ll &a, ll b){if(a<b) a=b;};

inline int solve(){
    ll ans = 0;
    sort(P.begin(),P.end());
    chmax(ans, abs(P[0].first - P[N-1].first));
    auto cmp_sec = [](pll a, pll b){return a.second < b.second;};
    sort(P.begin(),P.end(),cmp_sec);
    chmax(ans, abs(P[0].second - P[N-1].second));
    cout << ans << endl;
    return 0;
}

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

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


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

#define pb push_back
#define eb emplace_back
#define mk make_pair
#define fi first
#define se second
#define mset(a, b) memset(a, b, sizeof(a))
#define DBG(x) cout << "[" << #x << "]: " << x << endl
using ll = long long;
using pii = pair<int, int>;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#ifdef _WIN32
#define getchar_unlocked _getchar_nolock
#endif

template<class Ty> Ty randint(Ty a, Ty b) { return uniform_int_distribution<Ty>(a, b)(rng); }
template<class num> inline void rd(num& x) {
	char c, neg = 0; while(isspace(c = getchar_unlocked()));
	if(!isdigit(c)) neg = (c == '-'), x = 0;
	else x = c - '0';
	while(isdigit(c = getchar_unlocked())) x = (x << 3) + (x << 1) + c - '0';
	x = neg ? -x : x; }
template <class... Args> inline void rd(Args&... args) { (rd(args), ...); }

const int MAXN = 2e5 + 5, INF = 0x3f3f3f3f;

int cntA[MAXN];
int cntB[MAXN];
clock_t ck;

struct CMP {
	bool operator() (pii const& a, pii const& b) const {
		return mk(a.se + cntA[a.fi], a.fi) > mk(b.se + cntA[b.fi], b.fi);
	}
};

inline void gogo(vector<int> const& a, vector<int> b, int n) {

	while(double(clock() - ck) / CLOCKS_PER_SEC <= 1) {
		shuffle(b.begin(), b.end(), rng);

		bool ok = true;
		for (int i = 0; i < n; i++) {
			if (a[i] == b[i]) {
				ok = false;
				break;
			}
		}
		if (ok) {
			puts("Yes");
			for (int i : b) printf("%d ", i);
			exit(0);
		}
	}

	puts("No");
	exit(0);
}

int main() {
	ck = clock();

	int n; rd(n);
	vector<int> a(n);
	for (int& i : a) rd(i);
	vector<int> b(n);
	for (int& i : b) rd(i);

	set<pii, CMP> B;
	vector<pii> A;
	for (int i : a) cntA[i]++;
	for (int i : b) cntB[i]++;
	for (int i = 1; i <= n; i++) if (cntA[i]) A.emplace_back(i, cntA[i]);
	for (int i = 1; i <= n; i++) if (cntB[i]) B.emplace(i, cntB[i]);

	sort(A.begin(), A.end(), [](pii const& a, pii const& b) {
		return mk(a.se, a.fi) > mk(b.se, b.fi);
	});

	vector<vector<int>> edges(n+1);
	bool ok = true;
	for (auto& pa : A) if (ok) {
		int el = pa.fi, cn = pa.se;
		for (int i = 0; i < cn; i++) {
			auto it = prev(B.end());
			if(it != B.begin() && it->fi == el) it = prev(it);

			if (it->fi == el) {
				ok = false;
				break;
			}

			edges[el].push_back(it->fi);
			pii newValue = *it;
			B.erase(it);
			if (newValue.second > 1) {
				newValue.second--;
				B.insert(newValue);
			}
		}
	}

	for (int i = 0; i <= n; i++) {
		ok &= (int) edges[i].size() == cntA[i];
	}

	if (!ok) {
		gogo(a, b, n);
		puts("No");
	} else {
		puts("Yes");
		for (int i = 0; i <= n; i++) {
			for (int j = 0; j < cntA[i]; j++) {
				printf("%d ", edges[i][j]);
			}
		}
		puts("");
	}

}

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


//https://codeforces.com/contest/1368/problem/A
//Author: BrownieTK

//#pragma GCC optimize("Ofast")

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

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

//========================Debug======================================

void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char *x) { cerr << '\"' << x << '\"'; }
void __print(const string &x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }

template <typename T, typename V>
void __print(const pair<T, V> &x)
{
    cerr << '{';
    __print(x.first);
    cerr << ',';
    __print(x.second);
    cerr << '}';
}
template <typename T>
void __print(const T &x)
{
    int f = 0;
    cerr << '{';
    for (auto &i : x)
        cerr << (f++ ? "," : ""), __print(i);
    cerr << "}";
}
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v)
{
    __print(t);
    if (sizeof...(v))
        cerr << ", ";
    _print(v...);
}
#ifdef local
#define debug(x...)               \
    cerr << "[" << #x << "] = ["; \
    _print(x)
#else
#define debug(x...)
#endif

//========================TypeDefs===================================

typedef long long int lli;
typedef unsigned long long int ulli;
typedef long double ldb;

typedef pair<lli, lli> pll;
typedef pair<int, int> pii;
typedef pair<int, lli> pil;

//=========================MACROS====================================

#define pb push_back
#define popb pop_back()
#define pf push_front
#define popf pop_front()
#define si size()
#define be begin()
#define en end()
#define all(v) v.be, v.en
#define mp make_pair
#define mt make_tuple
#define acc(v) accumulate(all(v), 0)
#define F first
#define S second

#define forz(i, n) for (int i = 0; i < n; i++)
#define fore(i, m, n) for (int i = m; i <= n; i++)
#define rforz(i, n) for (int i = n - 1; i >= 0; i--)
#define rfore(i, m, n) for (int i = n; i >= m; i--)

#define deci(n) fixed << setprecision(n)
#define high(n) __builtin_popcount(n)
#define highll(n) __builtin_popcountll(n)
#define parity(n) __builtin_parity(n)
#define clz(n) __builtin_clz(n)
#define clzll(n) __builtin_clzll(n)
#define ctz(n) __builtin_ctz(n)

#define bset(a, p) ((a) | (1ll << (p)))
#define bchk(a, p) ((a) & (1ll << (p)))
#define bxor(a, p) ((a) ^ (1ll << (p)));
#define brem(a, p) (bchk(a, p) ? (bxor(a, p)) : (a))

#define lb lower_bound
#define ub upper_bound
#define er equal_range

#define findnot find_first_not_of

#define maxe *max_element
#define mine *min_element

#define mod 1000000007
#define mod2 998244353
#define PI 3.1415926535897932384
#define INF LLONG_MAX

#define gcd __gcd
#define kira ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)

//#define endl "\n"
#define p0(a) cout << a << " "
#define p1(a) cout << a << endl
#define p2(a, b) cout << a << " " << b << endl
#define p3(a, b, c) cout << a << " " << b << " " << c << endl
#define p4(a, b, c, d) cout << a << " " << b << " " << c << " " << d << endl

#define oset tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
#define osetlli tree<lli, null_type, less<lli>, rb_tree_tag, tree_order_statistics_node_update>

#define ofk order_of_key
#define fbo find_by_order
//member functions :
//1. order_of_key(k) : number of elements sbtriectly lesser than k
//2. find_by_order(k) : k-th element in the set

//==============================FUNCTIONS===========================================

auto clk = clock();
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
void run_time()
{
#ifdef local
    cout << endl;
    cout << "Time elapsed: " << (double)(clock() - clk) / CLOCKS_PER_SEC << endl;
#endif
    return;
}

inline lli power(lli x, lli y, lli p = mod)
{
    lli res = 1;
    x = x % p;
    while (y > 0)
    {
        if (y & 1)
            res = (res * x) % p;
        y = y >> 1;
        x = (x * x) % p;
    }
    return res;
}

inline lli modadd(lli a, lli b, lli m = mod)
{
    a += b;
    if (a >= m)
        a -= m;
    return a;
}

inline lli modmul(lli a, lli b, lli m = mod)
{
    return ((a % m) * (b % m)) % m;
}

inline lli modi(lli a, lli m = mod) { return power(a, m - 2, m); }

//================================CODE=============================================
const int N = 1e4 + 5;
lli fac[N], invfac[N];
void fact()
{
    invfac[0] = fac[0] = 1;
    for (int i = 1; i < N; i++)
    {
        fac[i] = (fac[i - 1] * i) % mod;
        invfac[i] = modi(fac[i]);
    }
    return;
}

lli ncr(lli a, lli b)
{
    if (a < b || a < 0 || b < 0)
        return 0;
    return ((fac[a] * invfac[b]) % mod * invfac[a - b]) % mod;
}
int main()
{
    kira;

    lli n;
    cin >> n;
    map<lli, lli> m, mm;
    vector<lli> a(n), b(n);
    vector<bool> vis(n + 1);
    priority_queue<pll> pq;

    forz(i, n)
    {
        cin >> a[i];
        vis[a[i]] = true;
        mm[a[i]]++;
    }

    forz(i, n)
    {
        cin >> b[i];
        m[b[i]]++;
    }

    lli maxi = 0;
    lli id = -1;
    for (auto x : m)
    {
        maxi = max({maxi, x.S, mm[x.F]});
        pq.push({x.F, x.S});
    }

    int f = 0;
    for (int i = 0; i <= n; i++)
    {
        if (vis[i])
        {
            if (mm[i] + m[i] > n)
                f = 1;
        }
    }

    if (f)
    {
        p1("No");
        return 0;
    }

    p1("Yes");
    for (int i = 0; i < n; i++)
    {
        pll s = pq.top();
        if (a[i] == s.F)
        {
            pq.pop();
            pll st = pq.top();
            pq.pop();
            p0(st.F);
            if (st.S > 1)
                pq.push({st.F, st.S - 1});
            pq.push(s);
        }
        else
        {
            pq.pop();
            p0(s.F);
            if (s.S > 1)
                pq.push({s.F, s.S - 1});
        }
    }
    run_time();
    return 0;
}


#include "atcoder/all"
#include <algorithm>
#include <bitset>
#include <cmath>
#include <complex>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <regex>
#include <set>
#include <stack>
#include <string>
#include <vector>

const int MOD = 1e9 + 7;
const int iINF = 2147483647 / 2;
const long long int llINF = 9223372036854775807 / 2;

using namespace std;
using namespace atcoder;
using ll = long long int;
using vl = vector<ll>;
using vvl = vector<vector<ll>>;
using vvvl = vector<vector<vector<ll>>>;

typedef pair<ll, ll> pll;
bool paircomp(const pll &a, const pll &b) {
  if (a.first == b.first)
    return a.second < b.second;
  return a.first < b.first;
}

#define REP(i, n) for (ll i = 0; i < (n); i++)
#define RREP(i, n) for (ll i = (n)-1; i >= 0; i--)
#define FOR(i, a, b) for (ll i = (a); i < (b); i++)
#define AUTO(i, m) for (auto &i : m)
#define ALL(a) (a).begin(), (a).end()
#define MAX(vec) *std::max_element(vec.begin(), vec.end())
#define MIN(vec) *std::min_element(vec.begin(), vec.end())
#define ARGMAX(vec)                                                            \
  std::distance(vec.begin(), std::max_element(vec.begin(), vec.end()))
#define ARGMIN(vec)                                                            \
  std::distance(vec.begin(), std::min_element(vec.begin(), vec.end()))
#define REV(T) greater<T>()
#define PQ(T) priority_queue<T, vector<T>, greater<T>>
#define VVL(a, b, c) vector<vector<ll>>(a, vector<ll>(b, c))
#define VV(T, a, b, c) vector<vector<T>>(a, vector<T>(b, c))
#define VVVL(a, b, c, d)                                                       \
  vector<vector<vector<ll>>>(a, vector<vector<ll>>(b, vector<ll>(c, d)))
#define VVV(T, a, b, c, d)                                                     \
  vector<vector<vector<T>>>(a, vector<vector<T>>(b, vector<T>(c, d)))
#define SP(a) fixed << setprecision(a)
#define SQRT(a) sqrt((long double)(a))
#define DPOW(a, b) pow((long double)(a), (long double)(b))
#define UNIQUE(vec)                                                            \
  do {                                                                         \
    sort(ALL((vec)));                                                          \
    (vec).erase(std::unique(ALL((vec))), (vec).end());                         \
  } while (0)

ll POW(ll n, ll m) {
  if (m == 0) {
    return 1;
  } else if (m % 2 == 0) {
    ll tmp = POW(n, m / 2);
    return (tmp * tmp);
  } else {
    return (n * POW(n, m - 1));
  }
}

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

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  ll N, M;
  cin >> N >> M;
  vector<string> S(N);
  REP(i, N) cin >> S[i];

  mf_graph<ll> graph(N * M + 10);

  REP(i, N) REP(j, M) {
    if (S[i][j] == '#')
      continue;
    if ((i + j) % 2 == 0)
      graph.add_edge(N * M, i * M + j, 1);
    else
      graph.add_edge(i * M + j, N * M + 1, 1);
  }

  REP(i, N) {
    REP(j, M) {
      if ((i + j) % 2 == 1 && S[i][j] == '#')
        continue;
      if (i - 1 >= 0 && S[i - 1][j] == '.')
        graph.add_edge(i * M + j, i * M - M + j, 1);
      if (j - 1 >= 0 && S[i][j - 1] == '.')
        graph.add_edge(i * M + j, i * M + j - 1, 1);
      if (i + 1 < N && S[i + 1][j] == '.')
        graph.add_edge(i * M + j, i * M + M + j, 1);
      if (j + 1 < M && S[i][j + 1] == '.')
        graph.add_edge(i * M + j, i * M + j + 1, 1);
    }
  }
  cout << graph.flow(N * M, N * M + 1) << endl;

  AUTO(e, graph.edges()) {
    if (e.from == N * M || e.to == N * M + 1 || e.flow == 0)
      continue;
    ll i0 = e.from / M, j0 = e.from % M;
    ll i1 = e.to / M, j1 = e.to % M;

    if (i0 == i1 + 1) {
      S[i1][j1] = 'v';
      S[i0][j0] = '^';
    } else if (j0 == j1 + 1) {
      S[i1][j1] = '>';
      S[i0][j0] = '<';
    } else if (i0 == i1 - 1) {
      S[i0][j0] = 'v';
      S[i1][j1] = '^';
    } else {
      S[i0][j0] = '>';
      S[i1][j1] = '<';
    }
  }
  REP(i, N) cout << S[i] << endl;

  return 0;
}

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).
Some of the squares contain an object. All the remaining squares are empty.
The state of the grid is represented by strings S_1,S_2,\cdots,S_N. The square (i,j) contains an object if S_{i,j}= # and is empty if S_{i,j}= ..

Consider placing 1 \times 2 tiles on the grid. Tiles can be placed vertically or horizontally to cover two adjacent empty squares.
Tiles must not stick out of the grid, and no two different tiles may intersect. Tiles cannot occupy the square with an object.

Calculate the maximum number of tiles that can be placed and any configulation that acheives the maximum.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

S_i is a string with length M consists of # and ..

Input

Input is given from Standard Input in the following format:

N M
S_1
S_2
\vdots
S_N

Output

On the first line, print the maximum number of tiles that can be placed.

On the next N lines, print a configulation that achieves the maximum.
Precisely, output the strings t_1,t_2,\cdots,t_N constructed by the following way.

t_i is initialized to S_i.

For each (i,j), if there is a tile that occupies (i,j) and (i+1,j), change t_{i,j}:=v, t_{i+1,j}:=^.

For each (i,j), if there is a tile that occupies (i,j) and (i,j+1), change t_{i,j}:=>, t_{i,j+1}:=<.

See samples for further information.

You may print any configulation that maximizes the number of tiles.

Sample Input 1

3 3
#..
..#
...

Sample Output 1

3
#><
vv#
^^.

The following output is also treated as a correct answer.

3
#><
v.#
^><


#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
#include <map>
#include <queue>
#include <iomanip>
#include <set>
#include <tuple>
#define mkp make_pair
#define mkt make_tuple
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define all(v) v.begin(),v.end()
using namespace std;
typedef long long ll;
const ll MOD=998244353;
template<class T> void chmin(T &a,const T &b){if(a>b) a=b;}
template<class T> void chmax(T &a,const T &b){if(a<b) a=b;}

#include <functional>

template< typename T, typename S >
struct LazySegmentTree{
    int n;
    vector<T> data;
    vector<S> lazy;
    T te;
    S se;

    inline void merge_functions(S& lazy,S& val){
        //lazy+=val;
        //lazy=val;
        ll a=lazy.first;ll b=lazy.second;
        ll c=val.first;ll d=val.second;
        lazy.first=a*c%MOD;
        lazy.second=(c*b%MOD+d%MOD)%MOD;
    }
    inline void operate(T& data,S& val,int len){
        //data+=val*len;
        //data=val*len;
        //data+=val;
        //data=val;
        ll a=val.first;ll b=val.second;
        data=(a*data%MOD+b*len%MOD)%MOD;
    }
    inline T merge_values(T& x,T& y){
        return (x+y)%MOD;
        //return min(x,y);
        //return max(x,y);
    }

    LazySegmentTree(){}
    LazySegmentTree(int sz,T te,S se):te(te),se(se){
        n=1;
        while(n<sz) n*=2;
        data.resize(2*n-1,te);
        lazy.resize(2*n-1,se);
    }

    void build(const vector<T> &A){
        for(int k=0;k<int(A.size());k++) data[k+n-1]=A[k];
        for(int k=n-2;k>=0;k--) data[k]=merge_values(data[2*k+1],data[2*k+2]);
    }

    void eval(int k,int l,int r){
        if(lazy[k]==se) return;
        operate(data[k],lazy[k],r-l);
        if(r-l>1){
            merge_functions(lazy[2*k+1],lazy[k]);
            merge_functions(lazy[2*k+2],lazy[k]);
        }
        lazy[k]=se;
    }

    void update(int a,int b,S val,int k=0,int l=0,int r=-1){
        if(r<0) r=n;
        eval(k,l,r);
        if(b<=l||r<=a) return;
        if(a<=l&&r<=b){
            merge_functions(lazy[k],val);
            eval(k,l,r);
        }else{
            update(a,b,val,2*k+1,l,(l+r)/2);
            update(a,b,val,2*k+2,(l+r)/2,r);
            data[k]=merge_values(data[2*k+1],data[2*k+2]);
        }
    }

    T query(int a,int b,int k=0,int l=0,int r=-1){
        if(r<0) r=n;
        eval(k,l,r);
        if(b<=l||r<=a) return te;
        if(a<=l&&r<=b) return data[k];

        T vl=query(a,b,2*k+1,l,(l+r)/2);
        T vr=query(a,b,2*k+2,(l+r)/2,r);
        return merge_values(vl,vr);
    }

    T get(int p){
        return query(p,p+1);
    }
};

/*
  LazySegmentTree<ll,ll> seg(N,te,se);
  vector<ll> init(N,0);
  seg.build(init);
*/

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

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

  LazySegmentTree<ll,pair<ll,ll>> seg(N,0,mkp(1,0));
  seg.build(A);
  rep(q,Q){
      int T;cin>>T;
      if(T==0){
          int L,R;ll A,B;
          cin>>L>>R>>A>>B;
          seg.update(L,R,mkp(A,B));
      }else{
          int L,R;
          cin>>L>>R;
          ll ans=seg.query(L,R);
          cout<<ans<<"\n";
      }
  }

  return 0;
}

Score : 100 points

Problem Statement

You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.

0 l r b c: For each i = l, l+1, \dots, {r - 1}, set a_i \gets b \times a_i + c.

1 l r: Print \sum_{i = l}^{r - 1} a_i \bmod 998244353.

Constraints

1 \leq N, Q \leq 500000

0 \leq a_i, c < 998244353

1 \leq b < 998244353

0 \leq l < r \leq N

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N Q
a_0 a_1 ... a_{N - 1}
\textrm{Query}_0
\textrm{Query}_1
:
\textrm{Query}_{Q - 1}

Output

For each query of the latter type, print the answer.

Sample Input 1

5 7
1 2 3 4 5
1 0 5
0 2 4 100 101
1 0 3
0 1 3 102 103
1 2 5
0 2 5 104 105
1 0 5

Sample Output 1

15
404
41511
4317767


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define sz(a) int((a).size())

int main()
{
    ll d,t,s;
    cin>>d>>t>>s;
    ll  val = d/s;
    if(d%s) val++;
    if(val<=t) cout<<"Yes\n";
    else cout<<"No\n";
}

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 <bits/stdc++.h>
using namespace std;

int main() {
  string S,T;
  int num,count=0,count_2=0;

  cin >> S;
  cin >> T;

  num = int(S.size()) - int(T.size()) + 1;

  for(int i=0;i<num;i++){
    count_2 = 0;
  	for(int j=0;j<int(T.size());j++){
      if(T.at(j) != S.at(i+j)){
        count_2 += 1;
      }
    }
    if(i==0){
      count = count_2;
    }
    if((i != 0) and (count_2 < count)){
      count = count_2;
    }
  }

  cout << count << 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 <algorithm>
#include <cmath>
#include <cstring>
#include <deque>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <regex>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

typedef long long ll;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
constexpr double PI = 3.141592653589793;
constexpr int INF = 1e9 + 10;
constexpr ll INFL = 1e18 + 10;

template <class T>
bool chmax(T &a, const T &b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
bool chmin(T &a, const T &b) {
  if (b < a) {
    a = b;
    return 1;
  }
  return 0;
}

using namespace std;
//    cout << setprecision(20) << ans << "\n";

class DisjointSet {
 private:
  std::vector<int> parent;

 public:
  DisjointSet(int n) : parent(n, -1) {}

  bool unite(int x, int y) {
    x = root(x);
    y = root(y);

    if (x != y) {
      if (x > y) {
        std::swap(x, y);
      }
      parent[x] += parent[y];
      parent[y] = x;
    }

    return x != y;
  }

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

  int numOfGroups() {
    int c =
        count_if(parent.begin(), parent.end(), [](int x) { return x < -1; });
    return c;
  }

  vector<int> roots() {
    vector<int> ret;
    for (size_t i = 0; i < parent.size(); ++i) {
      if (parent[i] < 0) ret.emplace_back(i);
    }
    return ret;
  }

  vector<int> members(int x) {
    int xRoot = root(x);
    vector<int> ret;
    for (size_t i = 0; i < parent.size(); ++i) {
      if (root(i) == xRoot) ret.emplace_back(i);
    }
    return ret;
  }

  map<int, vector<int>> allGroups() {
    map<int, vector<int>> ret;
    auto allRoots = roots();
    for (auto e : allRoots) {
      ret.insert({e, members(e)});
    }
    return ret;
  }

  vector<int> get() { return parent; }

 private:
  int root(int x) { return parent[x] < 0 ? x : parent[x] = root(parent[x]); }
};

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

  int n, m;
  cin >> n >> m;
  DisjointSet uf(n);
  for (int i = 0; i < m; i++) {
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    uf.unite(a, b);
  }

  auto allMembers = uf.allGroups();
  //   for (auto e : allMembers) {
  //     cout << e.first << "\n";
  //     for (auto es : e.second) {
  //       cout << es << " ";
  //     }
  //     cout << "\n";
  //   }
  //   cout << "\n";
  int ans = -1;
  for (auto &e : allMembers) {
    int len = e.second.size();
    if (ans < len) {
      ans = e.second.size();
    }
  }
  cout << ans << "\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