E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

namespace atcoder {

namespace internal {

// @param n `0 <= n`

// @return minimum non-negative `x` s.t. `n <= 2**x`

int ceil_pow2(int n) {

  int x = 0;

  while ((1U << x) < (unsigned int)(n))

    x++;

  return x;

}

// @param n `1 <= n`

// @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`

constexpr int bsf_constexpr(unsigned int n) {

  int x = 0;

  while (!(n & (1 << x)))

    x++;

  return x;

}

// @param n `1 <= n`

// @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`

int bsf(unsigned int n) {

#ifdef _MSC_VER

  unsigned long index;

  _BitScanForward(&index, n);

  return index;

#else

  return __builtin_ctz(n);

#endif

}

} // namespace internal

template <class S, S (*op)(S, S), S (*e)(), class F, S (*mapping)(F, S),

          F (*composition)(F, F), F (*id)()>

struct lazy_segtree {

public:

  lazy_segtree() : lazy_segtree(0) {}

  explicit lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}

  explicit lazy_segtree(const std::vector<S> &v) : _n(int(v.size())) {

    log = internal::ceil_pow2(_n);

    size = 1 << log;

    d = std::vector<S>(2 * size, e());

    lz = std::vector<F>(size, id());

    for (int i = 0; i < _n; i++)

      d[size + i] = v[i];

    for (int i = size - 1; i >= 1; i--) {

      update(i);

    }

  }

  void set(int p, S x) {

    assert(0 <= p && p < _n);

    p += size;

    for (int i = log; i >= 1; i--)

      push(p >> i);

    d[p] = x;

    for (int i = 1; i <= log; i++)

      update(p >> i);

  }

  S get(int p) {

    assert(0 <= p && p < _n);

    p += size;

    for (int i = log; i >= 1; i--)

      push(p >> i);

    return d[p];

  }

  S prod(int l, int r) {

    assert(0 <= l && l <= r && r <= _n);

    if (l == r)

      return e();

    l += size;

    r += size;

    for (int i = log; i >= 1; i--) {

      if (((l >> i) << i) != l)

        push(l >> i);

      if (((r >> i) << i) != r)

        push((r - 1) >> i);

    }

    S sml = e(), smr = e();

    while (l < r) {

      if (l & 1)

        sml = op(sml, d[l++]);

      if (r & 1)

        smr = op(d[--r], smr);

      l >>= 1;

      r >>= 1;

    }

    return op(sml, smr);

  }

  S all_prod() { return d[1]; }

  void apply(int p, F f) {

    assert(0 <= p && p < _n);

    p += size;

    for (int i = log; i >= 1; i--)

      push(p >> i);

    d[p] = mapping(f, d[p]);

    for (int i = 1; i <= log; i++)

      update(p >> i);

  }

  void apply(int l, int r, F f) {

    assert(0 <= l && l <= r && r <= _n);

    if (l == r)

      return;

    l += size;

    r += size;

    for (int i = log; i >= 1; i--) {

      if (((l >> i) << i) != l)

        push(l >> i);

      if (((r >> i) << i) != r)

        push((r - 1) >> i);

    }

    {

      int l2 = l, r2 = r;

      while (l < r) {

        if (l & 1)

          all_apply(l++, f);

        if (r & 1)

          all_apply(--r, f);

        l >>= 1;

        r >>= 1;

      }

      l = l2;

      r = r2;

    }

    for (int i = 1; i <= log; i++) {

      if (((l >> i) << i) != l)

        update(l >> i);

      if (((r >> i) << i) != r)

        update((r - 1) >> i);

    }

  }

  template <bool (*g)(S)> int max_right(int l) {

    return max_right(l, [](S x) { return g(x); });

  }

  template <class G> int max_right(int l, G g) {

    assert(0 <= l && l <= _n);

    assert(g(e()));

    if (l == _n)

      return _n;

    l += size;

    for (int i = log; i >= 1; i--)

      push(l >> i);

    S sm = e();

    do {

      while (l % 2 == 0)

        l >>= 1;

      if (!g(op(sm, d[l]))) {

        while (l < size) {

          push(l);

          l = (2 * l);

          if (g(op(sm, d[l]))) {

            sm = op(sm, d[l]);

            l++;

          }

        }

        return l - size;

      }

      sm = op(sm, d[l]);

      l++;

    } while ((l & -l) != l);

    return _n;

  }

  template <bool (*g)(S)> int min_left(int r) {

    return min_left(r, [](S x) { return g(x); });

  }

  template <class G> int min_left(int r, G g) {

    assert(0 <= r && r <= _n);

    assert(g(e()));

    if (r == 0)

      return 0;

    r += size;

    for (int i = log; i >= 1; i--)

      push((r - 1) >> i);

    S sm = e();

    do {

      r--;

      while (r > 1 && (r % 2))

        r >>= 1;

      if (!g(op(d[r], sm))) {

        while (r < size) {

          push(r);

          r = (2 * r + 1);

          if (g(op(d[r], sm))) {

            sm = op(d[r], sm);

            r--;

          }

        }

        return r + 1 - size;

      }

      sm = op(d[r], sm);

    } while ((r & -r) != r);

    return 0;

  }

private:

  int _n, size, log;

  std::vector<S> d;

  std::vector<F> lz;

  void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }

  void all_apply(int k, F f) {

    d[k] = mapping(f, d[k]);

    if (k < size)

      lz[k] = composition(f, lz[k]);

  }

  void push(int k) {

    all_apply(2 * k, lz[k]);

    all_apply(2 * k + 1, lz[k]);

    lz[k] = id();

  }

};

} // namespace atcoder

using namespace atcoder;

struct node {

  ll sum;

  ll len;

};

constexpr ll inf = 1e16;

node op(node l, node r) { return node{min(l.sum, r.sum), l.len + r.len}; }

node e() { return node{inf, 0}; }

struct F {

  ll add;

};

node mapping(F f, node x) { return node{x.sum + f.add, x.len}; }

F composition(F f, F g) {

  // f(g())

  return F{f.add + g.add};

}

F id() { return F{0}; }

auto solve() {

  int n;

  cin >> n;

  vector<ll> p(n), a(n);

  for (auto &i : p) {

    cin >> i;

    i--;

  }

  for (auto &i : a) {

    cin >> i;

  }

  lazy_segtree<node, op, e, F, mapping, composition, id> seg(n);

  ll sum = a[0];

  vector<int> pos(n);

  vector<ll> val(n);

  pos[p[0]] = 0;

  val[p[0]] = a[0];

  for(int i = 1 ; i < n ;++i){

    seg.set(i, {sum, 1});

    sum += a[i];

    pos[p[i]] = i;

    val[p[i]] = a[i];

  }

  ll ans = inf;

  for (int i = 0; i < n; ++i) {

    // l: i, r: n-i

    ans = min(ans, seg.prod(0, n).sum);

    // for (int j = 1; j < n; ++j) {

    //   cout<<seg.get(j).sum<<" ";

    // }

    // cout << "\n";

    seg.apply(pos[i] + 1, n, F{-val[i]});

    seg.apply(1, pos[i] + 1, F{val[i]});

    // cout << "OP:" << pos[i] + 1 << " " << val[i] << "\n";

  }

  // for (int j = 1; j < n; ++j) {

  //   cout << seg.get(j).sum << " ";

  // }

  // cout << "\n";

  ans = min(ans, seg.prod(0, n).sum);

  cout << ans << "\n";

}

auto main() -> int {

  ios::sync_with_stdio(false);

  cin.tie(nullptr), cout.tie(nullptr);

  int _ = 1;

  // cin >> _;

  while (_--) {

    solve();

  }

}


C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.

#include<bits/stdc++.h>

#define ll long long

#define flot(n) cout << setprecision(n) << setiosflags(ios::fixed) << setiosflags(ios::showpoint)

#define all(a) (a).begin() , (a).end()

#define pb push_back

#define mp make_pair

#define pii pair<int,int>

#define pll pair<ll,ll>

#define piii pair<pii,int>

#define plll pair<pll,ll>

#define R return

#define B break

#define C continue

#define SET(n , i) memset(n , i , sizeof(n))

#define SD ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)

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

#define repn(i , j , n) for(int i = j ; i < n ; i++)

#define repr(i,n,j) for(int i=n;i>=j;i--)

#define positive(x) ((x%mod+mod)%mod)

#define YES(f)cout<<((f)?"YES":"NO")<<endl

#define F first

#define S second

#define endl '\n'

#define vi vector<int>

//#define int ll

using namespace std;

void readFromFile(string input = "input.txt",string output="output.txt") {

    #ifndef ONLINE_JUDGE

        freopen(input.c_str(),"r",stdin);

        freopen(output.c_str(),"w",stdout);

    #endif

}

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

ll rnd(ll x, ll y) {

    return uniform_int_distribution<ll>(x, y)(rng);

}

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

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

const int INF = 0x3f3f3f3f;

const ll INFLL = 0x3f3f3f3f3f3f3f3f;

const long double EPS = 1e-3;

const long double pi =  acos(-1.0);

const int mod = 1e9+9;

const int N =5e5+3;

ll Mul(ll x,ll y,ll mod=mod){R((x%mod)*(y%mod))%mod;}

ll Add(ll x,ll y,ll mod=mod){R((x%mod)+(y%mod)+2ll*mod)%mod;}

int n,a[N],nxt[N],prv[N],dub[N];

ll pre[N],suf[N];

void pr() {

    rep(i,n)prv[i]=-1;

    rep(i,n)nxt[i]=n;

    stack<int> st;

    rep(i,n) {

        while(!st.empty() && a[st.top()] > a[i]) {

            nxt[st.top()] = i;

            st.pop();

        }

        st.push(i);

    }

    while(!st.empty())st.pop();

    repr(i,n-1,0) {

        while(!st.empty() && a[st.top()] > a[i]) {

            prv[st.top()] = i;

            st.pop();

        }

        st.push(i);

    }

}

/**

2 3 6 2 8 4

2 2 2 2 4 4

0:2+2+2+2+2+2 = 12

1:2+2+2+3+3+2 = 14

2:2+2+2+6+2+3 = 17

3:2+2+2+2+2+2 = 12

4:4+8+2+2+2+2 = 20

5:4+2+2+2+2+4 = 16

*/

void solve() {

    cin >> n;

    rep(i,n)cin>>a[i];

    pr();

    rep(i,n)dub[i]=1;

    rep(i,n) {

        int z = nxt[i];

        pre[i] += 1ll*dub[i]*a[i];

        pre[z] -= 1ll*dub[i]*a[i];

        dub[z] += dub[i];

        if(i)pre[i] += pre[i-1];

    }

    rep(i,n)dub[i]=1;

    repr(i,n-1,0) {

        int z = prv[i];

        suf[i] += 1ll*dub[i]*a[i];

        if(z>=0) {

            suf[z] -= 1ll*dub[i]*a[i];

            dub[z] += dub[i];

        }

        if(i<n-1) suf[i] += suf[i+1];

    }

    ll z=0;

    rep(i,n) Max(z,pre[i] += suf[i]-a[i]);

    vector<int> ans(n);

    rep(i,n) {

        if(pre[i] == z) {

            int mn = a[i];

            repr(j,i,0) {

                Min(mn,a[j]);

                ans[j] = mn;

            }

            mn = a[i];

            repn(j,i,n) {

                Min(mn,a[j]);

                ans[j] = mn;

            }

            for(auto it:ans)cout<<it<<" ";cout<<endl;

            R;

        }

    }

}

int32_t main() {

    readFromFile();

    SD;

    int t = 1;

//    cin >> t;

//    scanf("%d",&t);

    rep(i,t) {

        solve();

    }

}


G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n×mn×m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1≤t≤1001≤t≤100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2≤n,m≤202≤n,m≤20), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace):   O: A free cell.  X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t≥2t≥2 is satisfied, then the size of the grid will satisfy n≤10,m≤10n≤10,m≤10. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n−1)×(2m−1)(2n−1)×(2m−1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base.  For all 1≤i≤n,1≤j≤m1≤i≤n,1≤j≤m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i−1,2j−1)(2i−1,2j−1). Otherwise, print 'X' in the cell (2i−1,2j−1)(2i−1,2j−1).  For all 1≤i≤n,1≤j≤m−11≤i≤n,1≤j≤m−1, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i−1,2j)(2i−1,2j). Otherwise, print any printable character except spaces in the cell (2i−1,2j)(2i−1,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters.  For all 1≤i≤n−1,1≤j≤m1≤i≤n−1,1≤j≤m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print ' ' in the cell (2i,2j−1)(2i,2j−1). Otherwise, print any printable character except spaces in the cell (2i,2j−1)(2i,2j−1)  For all 1≤i≤n−1,1≤j≤m−11≤i≤n−1,1≤j≤m−1, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m−12m−1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OutputCopyYES
OOO
  O
OOO
NO
YES
OOOOO X
  O O
X O O X
  O
OOO X O
O O   O
O OOOOO
YES
OOOOOOOOOOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO

#include <bits/stdc++.h>

using namespace std;

const int maxn = 810;

int T, n, m, fa[maxn], d[maxn], pre[maxn], lim[maxn], eid[22][22][2];

bool bad[maxn], mark[maxn], vis[maxn], in1[maxn], in2[maxn], ban[maxn];

vector<int> G[maxn];

char str[22][22], ans[42][42];

int id(int x, int y) {

    return (x - 1) * m + y;

}

int find(int x) {

    while (x ^ fa[x]) x = fa[x] = fa[fa[x]];

    return x;

}

int main() {

    scanf("%d", &T);

    while (T--) {

        scanf("%d %d", &n, &m);

        for (int i = 1; i <= n; i++) {

            scanf("%s", str[i] + 1);

            for (int j = 1; j <= m; j++) ban[id(i, j)] = str[i][j] == 'X';

        }

        memset(mark, 0, sizeof(mark));

        memset(eid, -1, sizeof(eid));

        memset(lim, 0, sizeof(lim));

        memset(bad, 0, sizeof(bad));

        int cnt = 0;

        vector<array<int, 2>> E;

        for (int i = 1; i <= n; i++) {

            for (int j = 1; j <= m; j++) if (str[i][j] == 'O') {

                cnt++, bad[id(i, j)] = (i + j + 1) % 2 && (i > 1 || j > 1);

                if (i < n && str[i + 1][j] == 'O') {

                    eid[i][j][0] = E.size(), E.push_back({id(i, j), id(i + 1, j)});

                    lim[id(i, j)]++, lim[id(i + 1, j)]++;

                }

                if (j < m && str[i][j + 1] == 'O') {

                    eid[i][j][1] = E.size(), E.push_back({id(i, j), id(i, j + 1)});

                    lim[id(i, j)]++, lim[id(i, j + 1)]++;

                }

            }

        }

        bool ok = 1;

        for (int i = 1; i <= n * m; i++) {

            if (bad[i] && (lim[i] -= 2) < 0) { ok = 0; break; }

        }

        if (!ok) { puts("NO"); continue; }

        while (count(mark, mark + E.size(), 0) >= cnt) {

            for (int i = 0; i < E.size(); i++) {

                G[i].clear();

            }

            for (int i = 0; i < E.size(); i++) if (mark[i]) {

                fill(d + 1, d + n * m + 1, 0);

                for (int j = 0; j < E.size(); j++) {

                    if (i ^ j && mark[j]) d[E[j][0]]++, d[E[j][1]]++;

                }

                for (int j = 0; j < E.size(); j++) if (!mark[j]) {

                    if (d[E[j][0]] < lim[E[j][0]] && d[E[j][1]] < lim[E[j][1]]) G[j].push_back(i);

                }

            }

            for (int i = 0; i < E.size(); i++) if (!mark[i]) {

                iota(fa + 1, fa + n * m + 1, 1);

                for (int j = 0; j < E.size(); j++) {

                    if (i ^ j && !mark[j]) fa[find(E[j][0])] = find(E[j][1]);

                }

                int num = 0;

                for (int j = 1; j <= n * m; j++) {

                    if (!ban[j] && j == find(j)) num++;

                }

                for (int j = 0; j < E.size(); j++) if (mark[j]) {

                    if (num == 1 || num == 2 && find(E[j][0]) ^ find(E[j][1])) G[j].push_back(i);

                }

            }

            fill(in1, in1 + E.size(), 0);

            fill(in2, in2 + E.size(), 0);

            for (int i = 0; i < E.size(); i++) if (!mark[i]) {

                iota(fa + 1, fa + n * m + 1, 1);

                fill(d + 1, d + n * m + 1, 0);

                bool flag = 0;

                for (int j = 0; j < E.size(); j++) {

                    if (i ^ j && !mark[j]) fa[find(E[j][0])] = find(E[j][1]);

                    else if (++d[E[j][0]] > lim[E[j][0]] || ++d[E[j][1]] > lim[E[j][1]]) flag = 1;

                }

                int num = 0;

                for (int j = 1; j <= n * m; j++) {

                    if (!ban[j] && j == find(j)) num++;

                }

                in1[i] = num == 1, in2[i] = !flag;

            }

            fill(vis, vis + E.size(), 0);

            queue<int> Q;

            for (int i = 0; i < E.size(); i++) {

                if (in1[i]) Q.push(i), vis[i] = 1;

            }

            bool flag = 0;

            while (!Q.empty()) {

                int u = Q.front(); Q.pop();

                if (in2[u]) {

                    while (1) {

                        mark[u] ^= 1;

                        if (in1[u]) break;

                        u = pre[u];

                    }

                    flag = 1; break;

                }

                for (int v : G[u]) if (!vis[v]) {

                    Q.push(v), vis[v] = 1, pre[v] = u;

                }

            }

            if (!flag) break;

        }

        if (count(mark, mark + E.size(), 0) >= cnt) {

            puts("NO"); continue;

        }

        for (int i = 1; i <= n; i++) {

            for (int j = 1; j <= m; j++) {

                ans[2 * i - 1][2 * j - 1] = str[i][j];

                ans[2 * i][2 * j - 1] = ~eid[i][j][0] && mark[eid[i][j][0]] ? ' ' : 'O';

                ans[2 * i - 1][2 * j] = ~eid[i][j][1] && mark[eid[i][j][1]] ? ' ' : 'O';

                ans[2 * i][2 * j] = ' ';

            }

        }

        puts("YES");

        for (int i = 1; i < 2 * n; i++) {

            for (int j = 1; j < 2 * m; j++) putchar(ans[i][j]);

            putchar('\n');

        }

    }

    return 0;

}


A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
int jinzhi(int n,int i)
{
	int k=n,temp=0,sum=0;
	while(k>0)
	{
		sum=sum+k%i;
		k=k/i;
	}
	return sum;
}
int gys(int n,int m)
{
	if(n%m==0) return m;
	return gys(m,n%m);
}
int main()
{
	int i,j,k,n,m,sum=0,p;
	cin>>n;
	for(i=2;i<=n-1;i++) sum=sum+jinzhi(n,i);
	n=n-2;
	if(sum<n) swap(sum,n);
	p=gys(sum,n);
	sum=sum/p;
	n=n/p;
	cout<<sum<<"/"<<n;
	return 0;
}


C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold:  Every label is an integer between 00 and n−2n−2 inclusive.  All the written labels are distinct.  The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3
1 2
1 3
OutputCopy0
1
InputCopy6
1 2
1 3
2 4
2 5
5 6
OutputCopy0
3
2
4
1NoteThe tree from the second sample:

#define _CRT_SECURE_NO_WARNINGS

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

typedef long double ld;

typedef vector<int> vi;

typedef vector<ll> vl;

typedef pair<int, int>pi;

typedef pair<ll, ll>pl;

typedef vector<pi>vpi;

typedef vector<pl>vpl;

typedef vector<vi> vvi;

typedef vector<vl> vvl;

typedef vector<string> vs;

typedef vector<bool> vb;

typedef priority_queue<int> pqi;

typedef priority_queue<int, vi, greater<int>> pqI;

typedef priority_queue<ll> pql;

typedef priority_queue<ll, vl, greater<ll>> pqL;

const long double PI = acos(-1);

const int oo = 1e9 + 7;

const int MOD = 1e9 + 7;

const int N = 1e5 + 7;

#define endl '\n'

#define all(v) (v).begin(),(v).end()

#define rall(v) (v).rbegin(),(v).rend()

#define read(v) for (auto& it : v) scanf("%d", &it);

#define readL(v) for (auto& it : v) scanf("%lld", &it);

#define print(v) for (auto it : v) printf("%d ", it); puts("");

#define printL(v) for (auto it : v) printf("%lld ", it); puts("");

void solve() {

	int n;

	scanf("%d", &n);

	if (n == 2) {

		puts("0");

		return;

	}

	vvi g(n + 1);

	map<pi, int>idx;

	vi ans(n - 1, -1);

	for (int i = 0, u, v; i < n - 1; i++) {

		scanf("%d %d", &u, &v);

		g[u].push_back(v);

		g[v].push_back(u);

		idx[{u, v}] = idx[{v, u}] = i;

	}

	int cur = 0;

	for (int i = 1; i <= n && cur <= 2; i++)

		if (g[i].size() == 1)

			ans[idx[{i, g[i][0]}]] = cur++;

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

		if (ans[i] == -1)

			ans[i] = cur++;

	for (auto& it : ans)

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

}

int t = 1;

int main() {

#ifndef ONLINE_JUDGE

	freopen("input.txt", "r", stdin);

#endif

	//scanf("%d", &t);

	while (t--) solve();

}


E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can:  choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive;  take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously.  Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this:  In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.

#include<bits/stdc++.h>

#define ll long long

#define pb push_back

#define pf push_front

#define pob pop_back

#define pof pop_front

#define ff first

#define ss second

#define PLL pair<ll,ll>

#define pii pair<int,int>

#define SetBit(x, k) (x |= (1LL << k))

#define ClearBit(x, k) (x &= ~(1LL << k))

#define CheckBit(x, k) (x & (1LL << k))

#define scn(n) scanf("%d",&n)

#define scnll(n) scanf("%lld",&n)

#define nl cout<<"\n"

#define YES cout<<"YES\n"

#define Yes cout<<"Yes\n"

#define yes cout<<"yes\n"

#define NO cout<<"NO\n"

#define No cout<<"No\n"

#define no cout<<"no\n"

#define mod 1000000007LL

#define mod1 1000000007LL

#define mod2 1000000009LL

#define inf 1000000000000000LL

#define N 200000

#define fastio std::ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);

using namespace std;

int main()

{

    fastio;

    int n,m;cin>>n>>m;

    int a[n+2][m+2];

    map<int,int> cnt[m+2];

    for(int i=0;i<n;i++){

        for(int j=1;j<=m;j++){

            cin>>a[i][j];

            if(a[i][j]%m==j){

                int x=a[i][j]/m;

                if(x>=n) continue;

                x=i-x;

                if(x<0){

                    x+=n;

                }

                cnt[j][x]++;

            }

            if(j==m&&(a[i][j]%m==0)){

                int x=a[i][j]/m;

                x--;

                if(x>=n) continue;

                x=i-x;

                if(x<0){

                    x+=n;

                }

                cnt[j][x]++;

            }

        }

    }

    int ans=0;

    for(int j=1;j<=m;j++){

        int res=n;

        for(auto x:cnt[j]){

            ///cout<<x.ff<<" "<<x.ss<<"\n";

            int r=n-x.ss+x.ff;

            res=min(res,r);

        }

        ///nl;nl;

        ans+=res;

    }

    cout<<ans<<"\n";

}


D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.

#include <bits/stdc++.h>

using namespace std;

using LL = long long;

#define endl '\n'

using db = double;

template <class T>

using max_heap = priority_queue<T>;

template <class T>

using min_heap = priority_queue<T, vector<T>, greater<>>;

void solve()

{

    int n;

    cin >> n;

    string s;

    cin >> s;

    auto work = [&](string s) -> vector<int>

    {

        s += '>';

        vector<int> a;

        for (int i = 0, last = -1; i < n; ++i)

        {

            if (s[i] == '>')

            {

                for (int j = n - i; j <= n - last - 1; ++j)

                    a.push_back(j);

                last = i;

            }

        }

        return a;

    };

    auto ans = work(s);

    for (auto x : ans)

        cout << x << " ";

    cout << endl;

    for (int i = 0; i < s.size(); ++i)

        s[i] = '>' + '<' - s[i];

    ans = work(s);

    for (auto x : ans)

        cout << n - x + 1 << " ";

    cout << endl;

}

int main()

{

    ios::sync_with_stdio(false);

    cin.tie(nullptr);

    int T;

    cin >> T;

    while (T--)

        solve();

    return 0;

}


C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that:  the length of both arrays is equal to mm;  each element of each array is an integer between 11 and nn (inclusive);  ai≤biai≤bi for any index ii from 11 to mm;  array aa is sorted in non-descending order;  array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2
OutputCopy5
InputCopy10 1
OutputCopy55
InputCopy723 9
OutputCopy157557417
NoteIn the first test there are 55 suitable arrays:   a=[1,1],b=[2,2]a=[1,1],b=[2,2];  a=[1,2],b=[2,2]a=[1,2],b=[2,2];  a=[2,2],b=[2,2]a=[2,2],b=[2,2];  a=[1,1],b=[2,1]a=[1,1],b=[2,1];  a=[1,1],b=[1,1]a=[1,1],b=[1,1].

#include <bits/stdc++.h>

using namespace std;

// #include <ext/pb_ds/assoc_container.hpp>   // everything related to pbds

// #include <ext/pb_ds/tree_policy.hpp>

// using namespace __gnu_pbds;

// typedef int node; // change type here

// typedef tree<node, null_type, less<node>,

//              rb_tree_tag, tree_order_statistics_node_update> // this is push_backds

//     ordered_set;

using ll = long long;

using vi = vector<long long>;

using vpi = vector<pair<ll, ll>>;

typedef long double ld;

#define all(x) (x).begin(), (x).end()

#define rall(a) (a).rbegin(), (a).rend()

#define lb lower_bound

#define ps(x, y) fixed << setprecision(y) << x

#define int long long

ll INF = 1e18;

ll MOD = 1000000007;

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

int dy[] = {-1, 1, 0, 0}; // useful when dealing with points

ll maxx(vi &a)

{

    return (*max_element(a.begin(), a.end()));

}

ll minn(vi &a)

{

    return (*min_element(a.begin(), a.end()));

}

long long gcd(ll a, ll b)

{

    if (b == 0)

        return a;

    return gcd(b, a % b);

}

// Function to return LCM of two numbers

long long lcm(ll a, ll b)

{

    return (a / gcd(a, b)) * b;

}

bool isPrime(ll n)

{

    for (ll i = 2; i * i <= n; i++)

    {

        if (n % i == 0)

        {

            return false;

        }

    }

    return true;

}

long long mod(long long x)

{

    return ((x % MOD + MOD) % MOD);

}

long long add(long long a, long long b)

{

    return mod(mod(a) + mod(b));

}

long long mul(long long a, long long b)

{

    return mod(mod(a) * mod(b));

}

void input(vi &a)

{

    int n = a.size();

    for (int i = 0; i < n; i++)

    {

        cin >> a[i];

    }

}

void print(vi &a)

{

    for (auto x : a)

    {

        cout << x << " ";

    }

    cout << endl;

}

int stringToInt(string s)

{

    stringstream geek(s);

    int x = 0;

    geek >> x;

    return x;

}

bool isPowerOfTwo(ll n)

{

    if (n == 0)

        return false;

    return (ceil(log2(n)) == floor(log2(n)));

}

bool isPalindrome(string s)

{

    int n = s.size();

    for (int i = 0; i < n; i++)

    {

        if (s[i] != s[n - i - 1])

        {

            return false;

        }

    }

    return true;

}

string binaryTransformation(long long x)

{

    if (x == 0)

        return "";

    else

    {

        string s = binaryTransformation(x / 2);

        s.push_back(char('0' + x % 2));

        return s;

    }

}

ll power(ll a, ll b, ll mod)

{

    if (b == 0)

    {

        return 1;

    }

    ll ans = power(a, b / 2, mod);

    ans *= ans;

    ans %= mod;

    if (b % 2)

    {

        ans *= a;

    }

    return ans % mod;

}

double power(double a, int b)

{

    if (b == 0)

    {

        return 1;

    }

    double t = power(a, b / 2);

    if (b & 1)

    {

        return t * t * a;

    }

    else

    {

        return t * t;

    }

}

int modularInverse(int number, int mod)

{

    return power(number, mod - 2, mod);

}

// it should be 1LL and not 1

// write more tests

// google if stuck

// take a walk if stuck

// precompute first

const int N = 2000;

int fact[N], invfact[N];

int pow(int a, int b, int m)

{

    int ans = 1;

    while (b)

    {

        if (b & 1)

            ans = (ans * a) % m;

        b /= 2;

        a = (a * a) % m;

    }

    return ans;

}

int modinv(int k)

{

    return pow(k, MOD - 2, MOD);

}

void precompute()

{

    fact[0] = fact[1] = 1;

    for (int i = 2; i < N; i++)

    {

        fact[i] = fact[i - 1] * i;

        fact[i] %= MOD;

    }

    invfact[N - 1] = modinv(fact[N - 1]);

    for (int i = N - 2; i >= 0; i--)

    {

        invfact[i] = invfact[i + 1] * (i + 1);

        invfact[i] %= MOD;

    }

}

int nCr(int x, int y)

{

    if (y > x)

        return 0;

    int num = fact[x];

    num *= invfact[y];

    num %= MOD;

    num *= invfact[x - y];

    num %= MOD;

    return num;

}

void solve()

{

    // learned a lot from this problem ,lol

    // relearned stars and bars

    // basically we have 2*m positions and n candidates for each position

    // this can be rewritten as x1 + x2+x3+...xn= 2*m, here xi>=0

    // so when we place a bar it means that many positions for that number

    int n, m;

    cin >> n >> m;

    cout << nCr(2 * m + n - 1, n - 1) << endl;

}

// you should look down sometimes

// https://github.com/Manjunath0408/CPSnippets

int32_t main()

{

    // freopen("pump.in", "r", stdin);

    // freopen("pump.out", "w", stdout);

    /* stuff you should look for

     * int overflow, array bounds

     * special cases (n==1?)

     * do smth instead of nothing and stay organized

     * WRITE STUFF DOWN

     * DON'T GET STUCK ON ONE APPROACH

     * IF STUCK ON A QUESTION, MOVE TO THE NEXT ONE

     */

    ios_base::sync_with_stdio(false);

    cin.tie(NULL);

    int t = 1;

    precompute();

    // cin >> t;

    for (int i = 1; i <= t; i++)

    {

        solve();

    }

    return 0;

}


D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.

/*

        ফেরা হলো না ঘরে, নাহি ফিরলো ঘর দিকে আমার,

        এসে পথেরই মাঝে,

        পেছনে তাকিয়ে ফিরে আবার

        হেঁটে যাই আমি খুঁজতে কিছু, আমি আজও জানিনা কিসেরি পিছু!

*/

#include <bits/stdc++.h>

using namespace std;

#ifdef ONLINE_JUDGE

#define fast ios_base::sync_with_stdio(0); cin.tie(0);  // fast IO! but only when online_judge

#define debug 0

#else

#define fast ;

#define debug 1

#endif

// some typedefs for my convenience

#define int long long int

#define pii pair<int, int>

#define vi vector<int>

#define si set<int>

#define mi map<int, int>

// some speedup macros

#define gap ' '

#define endl '\n'

#define print(str) cout << str << endl

#define YES print("YES")

#define NO print("NO")

#define loop(i, begin, end) for(__typeof(end)i=begin-(begin>end); i!=end-(begin>end); i+=1-2*(begin>end))

#define all(v) v.begin(), v.end()

void solve(int cases);

int32_t main()

{

    fast

    int total_cases = 1;

    // cin >> total_cases;

    loop(cases, 1, total_cases+1) solve(cases);

    return 0;

}

// SOLVE STARTS HERE

int dc(vi &v, int bit, int cases)

{

    if (bit == -1) return 0;

    vi ones, zeros;

    int ocount = 0, zcount = 0, out = 0;

    for (auto x: v){

        if ((x>>bit) & 1) ocount++, ones.push_back(x);

        else zcount++, zeros.push_back(x);

    }

    if (ocount && zcount){

        out = 1 << bit;

        out |= min(dc(zeros, bit-1, cases), dc(ones, bit-1, cases));

    }

    else if (ocount) out = dc(ones, bit-1, cases);

    else if (zcount) out = dc(zeros, bit-1, cases);

    return out;

}

void solve(int cases)

{

    int n, q, out=0, sum=0, flag=0, maxi=LLONG_MIN, mini=LLONG_MAX;

    int in;

    cin >> n;

    vi v(n);

    #define printp(p) cout << '(' << p.F << ',' << gap << p.S << ')' << endl;

    #define printx(array) { for (auto x : array) cout << x << gap; cout << endl; }

    #define scanx(array) { for (auto &x: array) cin >> x; }

    #define printxp(array) { for (auto x : array) cout << '(' << x.first << ',' << gap << x.second << ')' << gap; cout << endl; }

    scanx(v);

    print(dc(v, 31 - __builtin_clz(*max_element(all(v))), n));

END:;

}

/*

        Fihad arRahman

        hellofihad@gmail.com

        18-02-2023 20:32

*/


E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times:   choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|;  erase the chosen subsequence from ss (ss can become empty);  concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4
ababcd
abcba
a
b
defi
fed
xyz
x
OutputCopyYES
NO
NO
YES

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using ld = long double;

constexpr int N = int(4e2) + 5;

constexpr int inf = 0x7f7f7f7f;

constexpr int MOD = int(1e9) + 7;

short dp[N][N][N];

string s, t;

void solve(){

    cin >> s >> t;

    for(short i = 0; i <= s.size(); i++){

        for(short j = 0; j <= t.size(); j++){

            for(short k = 0; k < t.size(); k++){

                dp[i][j][k] = 0;

            }

            dp[s.size()][j][t.size()] = j;

        }

    }

    for(short i = s.size() - 1; ~i; i--){

        for(short j = t.size(); ~j; j--){

            for(short k = t.size(); ~k; k--){

                auto& r = dp[i][j][k] = dp[i + 1][j][k];

                if(s[i] == t[j]) r = max(r, dp[i + 1][j + 1][k]);

                if(s[i] == t[k]) r = max(r, dp[i + 1][j][k + 1]);

            }

        }

    }

    for(int i = 0; i < t.size(); i++){

        if(dp[0][0][i + 1] > i){

            cout << "YES\n";

            return;

        }

    }

    cout << "NO\n";

}

int main() {

    ios::sync_with_stdio(0);

    cin.tie(0);

    int t = 1;

    cin >> t;

    while(t--){

        solve();

    }

}


G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions:  if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second;  use autocompletion. When you try to autocomplete the current string tt, a list of all strings s∈Ss∈S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1≤n≤1061≤n≤106).Then nn lines follow, the ii-th line contains one integer pipi (0≤pi<i0≤pi<i) and one lowercase Latin character cici. These lines form some set of strings such that SS is its subset as follows: there are n+1n+1 strings, numbered from 00 to nn; the 00-th string is an empty string, and the ii-th string (i≥1i≥1) is the result of appending the character cici to the string pipi. It is guaranteed that all these strings are distinct.The next line contains one integer kk (1≤k≤n1≤k≤n) — the number of strings in SS.The last line contains kk integers a1a1, a2a2, ..., akak (1≤ai≤n1≤ai≤n, all aiai are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set SS — formally, if we denote the ii-th generated string as sisi, then S=sa1,sa2,…,sakS=sa1,sa2,…,sak.OutputPrint kk integers, the ii-th of them should be equal to the minimum number of seconds required to type the string saisai.ExamplesInputCopy10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
OutputCopy2 4 1 3 3
InputCopy8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
OutputCopy1 2 2 4 4
NoteIn the first example; SS consists of the following strings: ieh, iqgp, i, iqge, ier.

#include<bits/stdc++.h>

#define endl '\n'

#define iloveds std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);

#define all(a) a.begin(),a.end()

using namespace std;

typedef long long ll ;

const int N = 1e6 + 100;

int n, ch[N][26], k, a[N], b[N], dfn[N], ans[N], f[N];

int tot, dp[N], val;

void dfs(int x){

	if(f[x]) {

		dfn[x] = ++ tot;

	}

	for(int i = 0 ; i < 26; i ++){

		if(ch[x][i]){

			dfs(ch[x][i]);

			dfn[x] = min(dfn[x], dfn[ch[x][i]]);

		}

	}

}

void dfs2(int x){

	for(int i = 0 ; i < 26; i ++){

		int tmp = val;

		if(ch[x][i]) {

			if(f[ch[x][i]]){

				dp[ch[x][i]] = min(dp[x] + 1, dfn[ch[x][i]] + val);

			}else{

				dp[ch[x][i]] = dp[x] + 1;

			}

			val = min(val, dp[ch[x][i]] - dfn[ch[x][i]] + 1);

			dfs2(ch[x][i]);

		}

		val = tmp;

	}

}

// dp[fa] - dfn[fa] + 1 + dfn[x];

int main(){

	iloveds;

	cin >> n;

	for(int i = 1; i <= n ; i ++){

		int x;

		char c;

		cin >> x >> c;

		ch[x][c - 'a'] = i;

	}

	cin >> k;

	for(int i = 1; i <= k ; i ++){

		cin >> a[i];

		f[a[i]] = 1;

	}

	for(int i = 1; i <= n ; i ++) {

		dp[i] = 0x3f3f3f3f;

		dfn[i] = 0x3f3f3f3f;

	}

	dfs(0);

	val = 0;

	dfs2(0);

	for(int i = 1; i <= k ; i ++) cout << dp[a[i]] << " ";

}


#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

#define ALL(x) (x).begin(), (x).end()

#define SZ(x) ((int)(x).size())

#define st first

#define nd second

using namespace __gnu_pbds;

using namespace std;

template <typename T>

using ordered_set =

	tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define sim template <class c

#define ris return *this

#define dor > debug &operator<<

#define eni(x)                                                                    \

	sim > typename enable_if<sizeof dud<c>(0) x 1, debug &>::type operator<<(c i) \

	{

sim > struct rge

{

	c b, e;

};

sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }

sim > auto dud(c *x) -> decltype(cerr << *x, 0);

sim > char dud(...);

#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "

#define shandom_ruffle random_shuffle

#define PB push_back

#define MP make_pair

#define LL long long

// #define int LL

#define VI vector<int>

#define PII pair<int, int>

#define LD long double

#define st first

#define nd second

#define ALL(x) (x).begin(), (x).end()

#define SZ(x) ((int)(x).size())

using ll = long long;

using pii = pair<int, int>;

using pll = pair<ll, ll>;

using vi = vector<int>;

using vll = vector<ll>;

struct Matroid

{

	int n;

	Matroid(int size) : n(size) {}

	virtual ~Matroid() {}

	// Returns any circuit as the subset of [X]. Returns an empty vector

	// if [X] is independent.

	virtual VI FindCircuit(const vector<int> &)

	{

		throw nullptr;

	}

	bool IsIndependent(const vector<int> &X)

	{

		return FindCircuit(X).empty();

	}

};

int H, W;

string board[30];

vector<pii> verts;

vector<pii> edges;

int ids[30][30];

vector<pii> adj[1000];

int num_edges, nverts;

bool is_in[1000];

int out_bound[1000];

vector<pair<vi, int>> bounds;

int bound_mapping[1000];

struct FU

{

	vi pnt;

	FU(int n) : pnt(n)

	{

		iota(ALL(pnt), 0);

	}

	int Find(int v)

	{

		if (pnt[v] == v)

		{

			return v;

		}

		return pnt[v] = Find(pnt[v]);

	}

};

struct CographicMatroid : public Matroid

{

	CographicMatroid() : Matroid(num_edges) {}

	virtual ~CographicMatroid() {}

	VI FindCircuit(const vector<int> &X) override

	{

		memset(is_in, 0, sizeof(bool) * num_edges);

		for (int v : X)

		{

			is_in[v] = true;

		}

		FU fu(nverts);

		int ncomp = nverts;

		for (int i = 0; i < num_edges; ++i)

		{

			if (!is_in[i])

			{

				int a = fu.Find(edges[i].st);

				int b = fu.Find(edges[i].nd);

				if (a != b)

				{

					fu.pnt[a] = b;

					--ncomp;

				}

			}

		}

		if (ncomp == 1)

		{

			return {};

		}

		vi indep;

		for (int v : X)

		{

			int a = fu.Find(edges[v].st);

			int b = fu.Find(edges[v].nd);

			if (a != b && ncomp == 2)

			{

				indep.push_back(v);

				continue;

			}

			if (a != b)

			{

				fu.pnt[a] = b;

				--ncomp;

			}

		}

		return indep;

	}

};

struct MaxChoiceMatroid : public Matroid

{

	MaxChoiceMatroid() : Matroid(num_edges) {}

	virtual ~MaxChoiceMatroid() {}

	VI FindCircuit(const vector<int> &X) override

	{

		vector<vi> lists(SZ(bounds));

		for (int v : X)

		{

			const int where = bound_mapping[v];

			if (where == -1)

			{

				continue;

			}

			lists[where].push_back(v);

			if (SZ(lists[where]) > bounds[where].nd)

			{

				return lists[where];

			}

		}

		return {};

	}

};

VI IntersectMatroids(Matroid *A, Matroid *B)

{

	assert(A->n == B->n);

	const int n = A->n;

	vector<VI> graph;

	VI X;

	while (true)

	{

		for (int i = 0; i < n; ++i)

		{

			if (count(ALL(X), i))

			{

				continue;

			}

			auto Y = X;

			Y.PB(i);

			if (A->IsIndependent(Y) && B->IsIndependent(Y))

			{

				X = Y;

			}

		}

		//~ debug(X);

		vector<bool> is_x(n), is_a(n), is_b(n);

		for (int x : X)

		{

			is_x[x] = true;

		}

		graph.clear();

		graph.resize(2 * n);

		queue<int> Q;

		VI dist(2 * n, 1e9), prv(2 * n, -1);

		for (int y = 0; y < n; ++y)

		{

			if (is_x[y])

			{

				continue;

			}

			auto Y = X;

			Y.PB(y);

			auto circ_a = A->FindCircuit(Y);

			if (circ_a.empty())

			{

				is_a[y] = true;

				Q.push(y + n);

				dist[y + n] = 0;

			}

			else

			{

				for (int x : circ_a)

				{

					graph[x].PB(y + n);

				}

			}

			auto circ_b = B->FindCircuit(Y);

			if (circ_b.empty())

			{

				is_b[y] = true;

			}

			else

			{

				for (int x : circ_b)

				{

					graph[y + n].PB(x);

				}

			}

			//~ debug(y, circ_a, circ_b);

		}

		int dest = -1;

		while (!Q.empty())

		{

			int v = Q.front();

			Q.pop();

			if (v >= n && is_b[v - n])

			{

				dest = v;

				break;

			}

			for (int s : graph[v])

			{

				if (dist[s] > dist[v] + 1)

				{

					dist[s] = dist[v] + 1;

					prv[s] = v;

					Q.push(s);

				}

			}

		}

		if (dest == -1)

		{

			break;

		}

		while (dest != -1)

		{

			const int p = dest % n;

			//~ debug(p);

			is_x[p] = !is_x[p];

			dest = prv[dest];

		}

		assert(count(ALL(is_x), true) == SZ(X) + 1);

		X.clear();

		for (int i = 0; i < n; ++i)

		{

			if (is_x[i])

			{

				X.PB(i);

			}

		}

	}

	return X;

}

void Test()

{

	cin >> H >> W;

	int cnt = 0;

	verts.clear();

	for (int i = 0; i < H; ++i)

	{

		cin >> board[i];

		for (int j = 0; j < W; ++j)

		{

			ids[i][j] = -1;

			if (board[i][j] == 'O')

			{

				verts.emplace_back(i, j);

				ids[i][j] = cnt;

				++cnt;

			}

		}

	}

	edges.clear();

	for (int i = 0; i < cnt; ++i)

	{

		adj[i].clear();

	}

	int eid = 0;

	for (int i = 0; i < H; ++i)

	{

		for (int j = 0; j < W; ++j)

		{

			if (j < W - 1 && board[i][j] == 'O' && board[i][j + 1] == 'O')

			{

				int a = ids[i][j];

				int b = ids[i][j + 1];

				adj[a].emplace_back(b, eid);

				adj[b].emplace_back(a, eid);

				edges.emplace_back(a, b);

				eid++;

			}

			if (i < H - 1 && board[i][j] == 'O' && board[i + 1][j] == 'O')

			{

				int a = ids[i][j];

				int b = ids[i + 1][j];

				adj[a].emplace_back(b, eid);

				adj[b].emplace_back(a, eid);

				edges.emplace_back(a, b);

				eid++;

			}

		}

	}

	num_edges = SZ(edges);

	nverts = cnt;

	bounds.clear();

	for (int i = 0; i < num_edges; ++i)

	{

		bound_mapping[i] = -1;

	}

	for (int i = 0; i < H; ++i)

	{

		for (int j = 0; j < W; ++j)

		{

			if (i == 0 && j == 0)

			{

				continue;

			}

			if (board[i][j] == 'O')

			{

				const int v = ids[i][j];

				out_bound[v] = SZ(adj[v]) - 1;

				if ((i + j) % 2 == 0)

				{

					--out_bound[v];

				}

				if (out_bound[v] < 0)

				{

					cout << "NO\n";

					return;

				}

				if ((i + j) % 2 == 0)

				{

					vi eids;

					for (auto &e : adj[v])

					{

						eids.push_back(e.nd);

						bound_mapping[e.nd] = SZ(bounds);

					}

					bounds.emplace_back(eids, out_bound[v]);

				}

			}

		}

	}

	Matroid *cographic = new CographicMatroid();

	Matroid *max_choice = new MaxChoiceMatroid();

	auto inter = IntersectMatroids(cographic, max_choice);

	const int num_blocked = SZ(inter);

	const int need_blocked = num_edges - (nverts - 1);

	if (num_blocked < need_blocked)

	{

		delete cographic;

		delete max_choice;

		cout << "NO\n";

		return;

	}

	vector<string> ans(2 * H - 1, string(2 * W - 1, ' '));

	for (int i = 0; i < H; ++i)

	{

		for (int j = 0; j < W; ++j)

		{

			ans[2 * i][2 * j] = board[i][j];

		}

	}

	for (auto &E : edges)

	{

		int a = E.st;

		int b = E.nd;

		auto [r1, c1] = verts[a];

		auto [r2, c2] = verts[b];

		if (r1 == r2)

		{

			ans[2 * r1][2 * min(c1, c2) + 1] = 'O';

		}

		else

		{

			ans[2 * min(r1, r2) + 1][2 * c1] = 'O';

		}

	}

	for (int v : inter)

	{

		int a = edges[v].st;

		int b = edges[v].nd;

		auto [r1, c1] = verts[a];

		auto [r2, c2] = verts[b];

		if (r1 == r2)

		{

			ans[2 * r1][2 * min(c1, c2) + 1] = ' ';

		}

		else

		{

			ans[2 * min(r1, r2) + 1][2 * c1] = ' ';

		}

	}

	cout << "YES\n";

	for (auto s : ans)

	{

		cout << s << "\n";

	}

	delete cographic;

	delete max_choice;

}

int main()

{

	ios_base::sync_with_stdio(0);

	cin.tie(0);

	cout << fixed << setprecision(11);

	cerr << fixed << setprecision(6);

	int t;

	cin >> t;

	while (t--)

	{

		Test();

	}

}


C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries:   ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.  ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use:   fflush(stdout) or cout.flush() in C++;  System.out.flush() in Java;  flush(output) in Pascal;  stdout.flush() in Python;  see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4

a
aa
a

cb
b
c

cOutputCopy? 1 2

? 3 4

? 4 4

! aabc

#include "bits/stdc++.h"

using namespace std;

#define all(x) begin(x),end(x)

template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }

template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { string sep; for (const T &x : v) os << sep << x, sep = " "; return os; }

#define debug(a) cerr << "(" << #a << ": " << a << ")\n";

typedef long long ll;

typedef vector<int> vi;

typedef vector<vi> vvi;

typedef pair<int,int> pi;

const int mxN = 1e5+1, oo = 1e9;

string str;

vector<array<int,3>> es;

string hidden = "xasdungo";

void query(int l, int r) {

    cout << "? " << l+1 << ' ' << r+1 << endl;

    int len = r-l+1;

    vector<int> v(len+1);

    for(int i=0;i<len*(len+1)/2;++i) {

        string s; cin >> s;

        auto& w = v[s.size()];

        for(auto c : s) w+=c;

    }

    // for(int i=l;i<=r;++i) for(int j=i;j<=r;++j) {

    //     string s = hidden.substr(i,j-i+1);

    //     auto& w = v[s.size()];

    //     for(auto c : s) w+=c;

    // }

    // take biggest string, do it times two, subtract out those two?

    vi res = {};

    for(int i=0;i<(len+1)/2;i++) {

        int ans=-v[len-i-1];

        for(int j=0;j<i;++j) {

            ans+=res[j]*(j+1 - (i+2));

        }

        ans += v[len]*(i+2);

        res.push_back(ans);

    }

    for(int i=0;i<len/2;++i) {

        es.push_back({l+i,r-i,res[i]});

    }

    if(len%2==1) {

        str[(l+r)/2]=res.back()/2;

    }

}

int main() {

    int n; cin >> n;

    str.resize(n,'?');

    if(n==1) {

        query(0,0);

    } else if(n==2) {

        query(0,0);

        query(0,1);

    } else {

        query(0,(n+1)/2 -1);

        query(0,(n+1)/2 -2);

        query(0,n-1);

    }

    vector<vector<pi>> adj(n);

    for(auto& [u,v,w] : es) adj[u].push_back({v,w}),adj[v].push_back({u,w});

    for(int i=0;i<n;++i) if(str[i]!='?') {

        auto dfs = [&](auto&& self, int at) -> void {

            for(auto [to,w] : adj[at]) if(str[to]=='?') {

                str[to]=w-str[at];

                self(self,to);

            }

        };

        dfs(dfs,i);

        break;

    }

    cout << "! " << str << endl;

}


C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4
3 0
5 1 2
7 3 5
10 -1 0
2 12
5 7 10
10 16 20
3 -100
100 0 0
100 -50 50
200 100 100
1 100
99 -100 0
OutputCopyYES
NO
YES
NO
NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way:  At 00-th minute, change the state to heating (the temperature is 0).  At 22-nd minute, change the state to off (the temperature is 2).  At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied).  At 66-th minute, change the state to off (the temperature is 3).  At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied).  At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.

#include<bits/stdc++.h>

using namespace std;

#define int long long

#define pb push_back

#define F first

#define S second

#define endl "\n"

const int N=1e2+2 , inf=2e9;

pair<int,int> dp[N];

bool solve (int num , int cur)

{

	bool c=true;

	int time[N];

	dp[0]={cur,cur};

	time[0]=0;

	for (int i=1 ; i<=num ; i++)

	{

		int l,r;

		cin >> time[i] >> l >> r;

		int dif=time[i]-time[i-1];

		int a,b;

		a=dp[i-1].F-dif;

		b=dp[i-1].S+dif;

		if (a>r || b<l)	c=false;

		dp[i].F = max (a,l);

		dp[i].S = min (b,r);

	}

	return c;

}

int32_t main()

{

	ios_base::sync_with_stdio(0);

	cin.tie(NULL);

	cout.tie(NULL);

	int test;	cin >> test;

	while (test--)

	{

		int num;	cin >> num;

		int cur;		cin >> cur;

		if (solve (num,cur))	cout << "YES" << endl;

		else cout << "NO" << endl;

	}

	return 0;

}


// Problem: C2. Skyscrapers (hard version)

// Contest: Codeforces - Codeforces Round #622 (Div. 2)

// URL: https://codeforces.com/problemset/problem/1313/C2

// Memory Limit: 512 MB

// Time Limit: 3000 ms

// User: milan0027

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

#define pb push_back

#define int long long

#define lld long double

#define fi first

#define se second

#define vi vector<int>

#define vb vector<bool>

#define vs vector<string>

#define vvi vector<vector<int>>

#define vpii vector<pair<int,int>>

#define vvpii vector<vector<pair<int,int>>>

#define mii map<int,int>

#define pii pair<int,int>

#define pq priority_queue

#define setbits(a) __builtin_popcountll(a)

#define ctz(a) __builtin_ctzll(a)

#define clz(a) __builtin_clzll(a)

#define loop(n) for(int i=0;i<n;i++)

#define fo(i,s,e) for(int i=s;i<e;i++)

#define inn(a,n) int n; cin>>n; vector<int> a(n); for(int i=0;i<n;i++) cin>>a[i];

#define ink(a,n,k) int n,k; cin>>n>>k; vector<int> a(n); for(int i=0;i<n;i++) cin>>a[i];

#define out(a) for(auto x9: a) cout<<x9<<" "; cout<<"\n";

#define test int _; cin>>_; for(int tt=1;tt<=_;tt++)

#define en "\n"

#define sz(a) (int)a.size()

#define sortf(a) sort(a.begin(),a.end())

#define sortr(a) sort(a.rbegin(),a.rend())

#define all(a) a.begin(),a.end()

#define gsum(a) accumulate(a.begin(),a.end(),0LL)

#define gmax(a) *max_element(a.begin(),a.end())

#define gmin(a) *min_element(a.begin(),a.end())

#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)

const int mod = 1000000007;

//const int mod = 998244353;

const int inf = 2100000000;

const lld pi = 3.1415926535897932;

const long long INF = 1e18+5;

//typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;

// ans val flag temp fin fish eye kill stat tic tac time cnt cost

void yesno(bool xxx)

{

    if(xxx)

    cout<<"YES\n";

    else

    cout<<"NO\n";

}

void NGE(vi &arr,vi &ans)

{

    int n=sz(arr);

    stack<int> s;

    s.push(arr[0]);

    // iterate for rest of the elements

    for (int i = 1; i < n; i++) {

        if (s.empty()) {

            s.push(arr[i]);

            continue;

        }

        while (s.empty() == false && arr[s.top()] > arr[i]) {

            ans[s.top()]=i;

            s.pop();

        }

        s.push(i);

    }

    while (s.empty() == false) {

        ans[s.top()]=0;

        s.pop();

    }

}

int32_t main()

{

   fastio;

   //code goes here

   int n;

   cin>>n;

   vi a(n+2,0);

   fo(i,1,n+1)

   cin>>a[i];

   vi fans(n+2,0),bans(n+2,0);

   NGE(a,fans);

   vi b=a;

   reverse(all(b));

   NGE(b,bans);

   reverse(all(bans));

   vi fdp(n+2,0),bdp(n+2,0);

  // out(fans)

   for(int i=n;i>=1;i--)

   {

       fdp[i]=(fans[i]-i)*a[i]+fdp[fans[i]];

       bans[i]=n-bans[i]+1;

   }

   //out(bans)

   for(int i=1;i<=n;i++)

   {

       bdp[i]=(i-bans[i])*a[i]+bdp[bans[i]];

   }

   int note=1;

   int ans=0;

   for(int i=1;i<=n;i++)

   {

       int val = bdp[i]+fdp[i+1];

       if(val > ans)

       {

           if(a[i]>a[i+1])

           note=i;

           else

           note=i+1;

           ans=val;

       }

   }

   vi fin(n+2,0);

   fin[note]=a[note];

   int r=note;

   while(r<=n)

   {

       int p=r;

       int to=fans[p];

       while(p<to)

       {

           fin[p]=a[r];

           p++;

       }

       r=to;

   }

   int l=note;

   while(l>=1)

   {

       int p=l;

       int to=bans[p];

       while(p>to)

       {

           fin[p]=a[l];

           p--;

       }

       l=to;

   }

   for(int i=1;i<=n;i++)

   cout<<fin[i]<<" ";

}

/*

*/


F. New Year and Social Networktime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDonghyun's new social network service (SNS) contains nn users numbered 1,2,…,n1,2,…,n. Internally, their network is a tree graph, so there are n−1n−1 direct connections between each user. Each user can reach every other users by using some sequence of direct connections. From now on, we will denote this primary network as T1T1.To prevent a possible server breakdown, Donghyun created a backup network T2T2, which also connects the same nn users via a tree graph. If a system breaks down, exactly one edge e∈T1e∈T1 becomes unusable. In this case, Donghyun will protect the edge ee by picking another edge f∈T2f∈T2, and add it to the existing network. This new edge should make the network be connected again. Donghyun wants to assign a replacement edge f∈T2f∈T2 for as many edges e∈T1e∈T1 as possible. However, since the backup network T2T2 is fragile, f∈T2f∈T2 can be assigned as the replacement edge for at most one edge in T1T1. With this restriction, Donghyun wants to protect as many edges in T1T1 as possible.Formally, let E(T)E(T) be an edge set of the tree TT. We consider a bipartite graph with two parts E(T1)E(T1) and E(T2)E(T2). For e∈E(T1),f∈E(T2)e∈E(T1),f∈E(T2), there is an edge connecting {e,f}{e,f} if and only if graph T1−{e}+{f}T1−{e}+{f} is a tree. You should find a maximum matching in this bipartite graph.InputThe first line contains an integer nn (2≤n≤2500002≤n≤250000), the number of users. In the next n−1n−1 lines, two integers aiai, bibi (1≤ai,bi≤n1≤ai,bi≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T1T1.In the next n−1n−1 lines, two integers cici, didi (1≤ci,di≤n1≤ci,di≤n) are given. Those two numbers denote the indices of the vertices connected by the corresponding edge in T2T2. It is guaranteed that both edge sets form a tree of size nn.OutputIn the first line, print the number mm (0≤m<n0≤m<n), the maximum number of edges that can be protected.In the next mm lines, print four integers ai,bi,ci,diai,bi,ci,di. Those four numbers denote that the edge (ai,bi)(ai,bi) in T1T1 is will be replaced with an edge (ci,di)(ci,di) in T2T2.All printed edges should belong to their respective network, and they should link to distinct edges in their respective network. If one removes an edge (ai,bi)(ai,bi) from T1T1 and adds edge (ci,di)(ci,di) from T2T2, the network should remain connected. The order of printing the edges or the order of vertices in each edge does not matter.If there are several solutions, you can print any.ExamplesInputCopy4
1 2
2 3
4 3
1 3
2 4
1 4
OutputCopy3
3 2 4 2
2 1 1 3
4 3 1 4
InputCopy5
1 2
2 4
3 4
4 5
1 2
1 3
1 4
1 5
OutputCopy4
2 1 1 2
3 4 1 3
4 2 1 4
5 4 1 5
InputCopy9
7 9
2 8
2 1
7 5
4 7
2 4
9 6
3 9
1 8
4 8
2 9
9 5
7 6
1 3
4 6
5 3
OutputCopy8
4 2 9 2
9 7 6 7
5 7 5 9
6 9 4 6
8 2 8 4
3 9 3 5
2 1 1 8
7 4 1 3

#include<bits/stdc++.h>

const int N = 2e6 + 101;

int n, m;

int dep[N], f[N][25], du[N], belong[N], vis[N];

std::vector<int> e[N], t[N];

std::queue<int> q;

void dfs(int u, int fa) {
	dep[u] = dep[fa] + 1;
	f[u][0] = fa;
	for (int i = 0; i <= 22; ++i) f[u][i + 1] = f[f[u][i]][i];
	for (auto v : e[u]) {
		if (v == fa) continue;
		dfs(v, u);
	}
}

int lca(int x, int y) {
	if (dep[x] < dep[y]) std::swap(x, y);
	for (int i = 22; i >= 0; --i) {
		if (dep[f[x][i]] >= dep[y]) x = f[x][i];
		if (x == y) return x;
	}
	for (int i = 22; i >= 0; --i) {
		if (f[x][i] != f[y][i]) {
			x = f[x][i];
			y = f[y][i];
		}
	}
	return f[x][0];
}

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

signed main() {

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

	std::cin >> n;
	for (int i = 1; i <= n; ++i) belong[i] = i;
	for (int i = 1; i < n; ++i) {
		int u, v;
		std::cin >> u >> v;
		e[u].push_back(v), e[v].push_back(u);
	}
	for (int i = 1; i < n; ++i) {
		int u, v;
		std::cin >> u >> v;
		t[u].push_back(v), t[v].push_back(u);
		++du[u], ++du[v];
	}
	dfs(1, 0);
	for (int i = 1; i <= n; ++i) {
		if (du[i] == 1) q.push(i);
	}
	//for (int i = 1; i <= n; ++i) std::cout << dep[i] << '\n';
	std::cout << n - 1 << '\n';
	while (q.size() >= 2) {
		int u = q.front(), v;
		q.pop();
		vis[u] = 1;
		for (auto to : t[u]) {
			if (vis[to] == 1) continue;
			v = to;
			--du[v];
			if (du[v] == 1) q.push(v);
			break;
		}
		int k = lca(u, v);
		int a = find(u), b;
		//std::cout << "a: " << a << " u: " << u << " v: " << v << " k: " << k << '\n';
		if (dep[a] > dep[k]) {
			b = f[a][0];
			std::cout << a << " " << b << " " << u << " " << v << '\n';
			belong[a] = find(b);
		}
		else {
			b = v;
			for (int i = 22; i >= 0; --i) {
				//std::cout << "b: " << b << '\n';
				if (dep[f[b][i]] > dep[k] && find(f[b][i]) != a) b = f[b][i];
			}
			std::cout << b << " " << f[b][0] << " " << u << " " << v << '\n';
			belong[b] = a;
		}
	}

	return 0;
}


D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
OutputCopy2
InputCopy7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
OutputCopy1
InputCopy4 4
1 2 27
1 3 1
1 4 1
3 4 0
OutputCopy6NoteThe pictures below represent the graphs from examples.  In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11.  In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges.  In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept.

#include <bits/stdc++.h>

using namespace std;

const int D = 5;

const int S = 374;

int transition[S][1<<D];

int combination[S][S];

struct linear_space {

  uint32_t x;

  linear_space(): x(1) {};

  linear_space(uint32_t _x): x(_x) {};

  bool has(int k) {

    return (x>>k)&1;

  }

  bool operator == (const linear_space& other) {

    return x == other.x;

  }

  bool operator < (const linear_space& other) {

    return x < other.x;

  }

  linear_space operator + (int k) {

    uint32_t res = x;

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

      if ((x>>i)&1) res |= 1<<(k^i);

    }

    return linear_space(res);

  }

  linear_space operator + (const linear_space& other) {

    uint32_t res = 0;

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

      for (int j = 0; j < (1<<D); j++) {

        if ((x>>i)&1 && (other.x>>j)&1) res |= 1<<(i^j);

      }

    }

    return linear_space(res);

  }

  friend ostream& operator << (ostream& os, const linear_space& l) {

    return os << bitset<32>(l.x);

  }

};

vector<linear_space> spaces(1);

int get_index(linear_space x) {

  return lower_bound(spaces.begin(), spaces.end(), x)-spaces.begin();

}

void precompute() {

  for (int i = 0; i < (int)spaces.size(); i++) {

    for (int j = 0; j < (1<<D); j++) {

      if (spaces[i].has(j)) continue;

      linear_space y = spaces[i]+j;

      if (find(spaces.begin(), spaces.end(), y) == spaces.end()) {

        spaces.push_back(y);

      }

    }

  }

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

  assert(spaces.size() == S);

  for (int i = 0; i < S; i++) {

    for (int j = 0; j < (1<<D); j++) {

      transition[i][j] = (spaces[i].has(j) ? -1 : get_index(spaces[i]+j));

    }

  }

  for (int i = 0; i < S; i++) {

    for (int j = 0; j < S; j++) {

      combination[i][j] =

        ((spaces[i].x&spaces[j].x) == 1 ? get_index(spaces[i]+spaces[j]) : -1);

    }

  }

}

const int MOD = 1e9+7;

void add(int& x, int y) {

  x += y;

  if (x >= MOD) x -= MOD;

}

const int N = 1e5+5;

vector<pair<int, int>> G[N];

int wt[N], tree_space[N], dep[N];

bool inner[N], vis[N];

vector<tuple<int, int, int>> special_edges;

void dfs(int v) {

  for (auto& [u, w]: G[v]) {

    if (inner[u] && inner[v]) {

      if (u < v) special_edges.emplace_back(u, v, w);

      continue;

    }

    if (dep[u] < dep[v] && (dep[u] > 0 || u == 1)) continue;

    if (dep[u] > dep[v]+1) {

      if (tree_space[v] != -1) {

        tree_space[v] = transition[tree_space[v]][wt[u]^wt[v]^w];

      }

      continue;

    }

    dep[u] = dep[v]+1;

    wt[u] = wt[v]^w;

    dfs(u);

    if (v != 1 && tree_space[v] != -1) {

      if (tree_space[u] == -1) tree_space[v] = -1;

      else tree_space[v] = combination[tree_space[v]][tree_space[u]];

    }

  }

}

void increment(array<int, S>& a, array<int, S>& b, int c) {

  for (int i = 0; i < S; i++) {

    int j = combination[i][c];

    if (j != -1) add(b[j], a[i]);

  }

}

int main () {

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

  precompute();

  int n, m;

  cin >> n >> m;

  for (int i = 0; i < m; i++) {

    int u, v, w;

    cin >> u >> v >> w;

    G[u].emplace_back(v, w);

    G[v].emplace_back(u, w);

  }

  for (auto& [v, _]: G[1]) inner[v] = 1;

  dfs(1);

  fill(vis, vis+N, 0);

  array<int, S> dp({});

  dp[0] = 1;

  for (auto& [u, v, w]: special_edges) {

    vis[u] = vis[v] = 1;

    array<int, S> _dp = dp;

    if (tree_space[u] != -1 && tree_space[v] != -1) {

      int k = combination[tree_space[u]][tree_space[v]];

      if (k != -1) {

        increment(dp, _dp, k);

        increment(dp, _dp, k);

        int l = transition[k][wt[u]^wt[v]^w];

        if (l != -1) increment(dp, _dp, l);

      }

    }

    swap(dp, _dp);

  }

  for (auto& [v, _]: G[1]) {

    if (vis[v]) continue;

    if (tree_space[v] != -1) {

      array<int, S> _dp = dp;

      increment(dp, _dp, tree_space[v]);

      swap(dp, _dp);

    }

  }

  int ans = 0;

  for (int x: dp) add(ans, x);

  cout << ans << '\n';

}


D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.

#include<bits/stdc++.h>

using namespace std;

#define taskname ""

struct line{

int l,r;

bool operator < (const line &p)const{

return l<p.l;

}

};

struct suzy{

int id,pos;

};

line a[100009];

int vis[8];

int dp[200009][1<<8];

int dp2[200009][1<<8];

int main()

{

    ios_base::sync_with_stdio(false);

    cin.tie(0);

    //freopen(taskname".INP","r",stdin);

    //freopen(taskname".OUT","w",stdout);

    int n,m,k;

    cin>>n>>m>>k;

    vector<int>pos;

    map<int,int>dm;

    pos.push_back(m);

    dm[m]=1;

    for (int i=1;i<=n;i++){

        cin>>a[i].l>>a[i].r;

        if (dm[a[i].l]==0){

            pos.push_back(a[i].l);

            dm[a[i].l]=1;

        }

        if (dm[a[i].r+1]==0){

            dm[a[i].r+1]=1;

            pos.push_back(a[i].r+1);

        }

    }

    if (dm[m+1]==0)pos.push_back(m+1);

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

    sort(a+1,a+1+n);

    int p=0;

    int mask=0;

    vector<suzy>last;

    int ans=0;

    for (int i=0;i<(int)pos.size()-1;i++){

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

            vis[j]=0;

        }

        mask=0;

        for (auto v:last){

            if (a[v.id].r<pos[i])continue;

            vis[v.pos]=v.id;

            //cout<<i<<" "<<v.pos<<'\n';

            mask+=(1<<v.pos);

        }

        vector<int>newline;

        for (int j=p+1;j<=n;j++){

            if (a[j].l==pos[i]){

                p=j;

                newline.push_back(j);

            }

            else break;

        }

        //cout<<newline.size()<<'\n';

        last.clear();

        int newmask=0,nmask=0;;

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

            if (vis[j]==0){

                if (newline.empty())continue;

                vis[j]=newline.back();

                newline.pop_back();

                last.push_back({vis[j],j});

                if (a[vis[j]].r>=pos[i+1])newmask+=(1<<j);

                nmask|=(1<<j);

            }

            else {

                last.push_back({vis[j],j});

                if (a[vis[j]].r>=pos[i+1])newmask+=(1<<j);

                nmask|=(1<<j);

                //cout<<i<<" "<<j<<'\n';

            }

        }

        //cout<<pos[i]<<" "<<last.size()<<'\n';

        //cout<<pos[i]<<" "<<nmask<<'\n';

        for (int j=0;j<(1<<k);j++){

            //beforemask

            if ((j&nmask)!=j)continue;

            int huhu=(j&mask);

            int sum=0;

            if (i>0)sum=dp2[i-1][huhu];

            if (__builtin_popcount(j)%2==1){

                sum+=(pos[i+1]-pos[i]);

            }

            dp[i][j]=sum;

            ans=max(ans,sum);

            //cout<<pos[i]<<" "<<j<<" "<<sum<<'\n';

        }

        //cout<<mask<<" "<<pos[i]<<'\n';

        //cout<<pos[i]<<" "<<newmask<<'\n';

        for (int j=0;j<(1<<k);j++){

            dp2[i][(j&newmask)]=max(dp2[i][(j&newmask)],dp[i][j]);

        }

        //cout<<i<<" "<<last.size()<<'\n';

    }

    cout<<ans;

}


F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way:   On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days.  On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days.  If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2
0 2 1 1 0
0 0 3 1 2
1 0 4 3 1
3 3 0 0 4
OutputCopy25
InputCopy3 3 1
1 2 3
4 5 6
7 8 9
OutputCopy31
InputCopy3 3 2
1 2 3
4 5 6
7 8 9
OutputCopy44
InputCopy3 3 3
1 2 3
4 5 6
7 8 9
OutputCopy45
NoteThe optimal way to observe animals in the four examples are as follows:Example 1:   Example 2:   Example 3:   Example 4:

/// Author : Nguyễn Thái Sơn - Ti20 - THPT chuyên Lương Thế Vinh

/// Training VOI 2023

#include<bits/stdc++.h>

//#include <ext/pb_ds/assoc_container.hpp>

//#include <ext/pb_ds/trie_policy.hpp>

//#include <ext/rope>

//#pragma GCC optimize("Ofast")

//#pragma GCC optimization("unroll-loops, no-stack-protector")

//#pragma GCC target("avx,avx2,fma")

//using namespace std;

//using namespace __gnu_pbds;

//using namespace __gnu_cxx;

#define fi first

#define se second

#define TASK "test"

#define pb push_back

#define EL cout << endl

#define Ti20_ntson int main()

#define in(x) cout << x << endl

#define all(x) (x).begin(),(x).end()

#define getbit(x, i) (((x) >> (i)) & 1)

#define cntbit(x) __builtin_popcount(x)

#define FOR(i,l,r) for (int i = l; i <= r; i++)

#define FORD(i,l,r) for (int i = l; i >= r; i--)

#define Debug(a,n) for (int i = 1; i <= n; i++) cout << a[i] << " "; cout << endl

using namespace std;

typedef long long ll;

typedef vector<int> vi;

typedef pair<int,int> vii;

typedef unsigned long long ull;

typedef vector<vector<int>> vvi;

int fastMax(int x, int y) { return (((y-x)>>(32-1))&(x^y))^y; }

const int N = 2e4 + 5;

const int oo = INT_MAX;

const int mod = 1e9 + 7;

const int d4x[4] = {-1, 0, 1, 0} , d4y[4] = {0, 1, 0, -1};

const int d8x[8] = {-1, -1, 0, 1, 1, 1, 0, -1}, d8y[8] = {0, 1, 1, 1, 0, -1, -1, -1};

int n, a[55][N], m, k;

ll dp[55][N];

inline void Read_Input() {

    cin >> n >> m >> k;

    FOR(i, 1, n)

        FOR(j, 1, m) {

            cin >> a[i][j];

            a[i][j] = a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1] + a[i][j];

        }

}

int Get(int x, int y, int xx, int yy) {

    return a[xx][yy] - a[x - 1][yy] - a[xx][y - 1] + a[x - 1][y - 1];

}

struct Segment_Tree {

    ll st[4 * N + 5], lz[4 * N + 5];

    void build(int id, int l, int r, int cur) {

        lz[id] = 0;

        if (l == r) {

            st[id] = dp[cur][l];

            return;

        }

        int mid = (l + r) >> 1;

        build(id * 2, l, mid, cur);

        build(id * 2 + 1, mid + 1, r, cur);

        st[id] = max(st[id * 2], st[id * 2 + 1]);

    }

    void Down(int id) {

        if (lz[id] == 0)

            return;

        lz[id * 2] += lz[id];

        lz[id * 2 + 1] += lz[id];

        st[id * 2] += lz[id];

        st[id * 2 + 1] += lz[id];

        lz[id] = 0;

    }

    void update(int id, int l, int r, int u, int v, int val) {

        if (l > v || r < u)

            return;

        if (l >= u && r <= v) {

            st[id] += val;

            lz[id] += val;

            return;

        }

        int mid = (l + r) >> 1;

        Down(id);

        update(id * 2, l, mid, u, v, val);

        update(id * 2 + 1, mid + 1, r, u, v, val);

        st[id] = max(st[id * 2], st[id * 2 + 1]);

    }

    ll Get(int id, int l, int r, int u, int v) {

        if (l > v || r < u)

            return 0;

        if (l >= u && r <= v)

            return st[id];

        Down(id);

        int mid = (l + r) >> 1;

        return max(Get(id * 2, l, mid, u, v), Get(id * 2 + 1, mid + 1, r, u, v));

    }

}it;

inline void Solve() {

    const int mx = m - k + 1;

    ll Ans = 0;

    FOR(i, 1, mx)

        dp[1][i] = Get(1, i, 1, i + k - 1);

    if (n > 1)

        FOR(i, 1, mx)

            dp[1][i] += Get(2, i, 2, i + k - 1);

    FOR(i, 2, n) {

        it.build(1, 1, mx, i - 1);

        int val = Get(i, 1, i, k);

        FOR(j, 1, k) {

            it.update(1, 1, mx, j, j, -val),

            val -= Get(i, j, i, j);

        }

        FOR(j, 1, mx) {

            dp[i][j] = it.st[1] + Get(i, j, i, j + k - 1);

            if (i != n)

                dp[i][j] += Get(i + 1, j, i + 1, j + k - 1);

            if (j != mx) {

//                cout << "CHECK " << j << endl;

                int l = max(1, j - k + 1);

//                cout << "UPDATE " << l << " " << j << " " << Get(i, j, i, j) << endl;

                it.update(1, 1, mx, l, j, Get(i, j, i, j));

                int cur = j + k;

                cur = Get(i, cur, i, cur);

                int r = min(mx, j + k);

                it.update(1, 1, mx, j + 1, r, -cur);

//                cout << "UPDATE " << j + 1 << " " << r << " " << -cur << endl;

//                FOR(k, 1, mx)

//                    cout << it.Get(1, 1, mx, k, k) << " "; cout << endl;

            }

        }

//        FOR(j, 1, mx)

//            cout << dp[i][j] << " \n"[j == mx];

    }

    cout << *max_element(dp[n] + 1, dp[n] + mx + 1);

}

Ti20_ntson {

//    freopen(TASK".INP","r",stdin);

//    freopen(TASK".OUT","w",stdout);

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

    int T = 1;

//    cin >> T;

    while (T -- ) {

        Read_Input();

        Solve();

    }

}


A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2
2
14
OutputCopy1 1
6 4
NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int t, x;

void Solve() {
    for (int i=1; i<=t; i++) {
        cin >> x;
        cout << 1 << ' ' << x - 1 << '\n';
    }
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> t;
    Solve();
    return 0;
}