七影蝶
Description
给定序列
Limitations
Solution
视
- 若
A<2^k ,那么(2^k-A)\le X<(2^{k+1}-A) 。 - 若
A\ge 2^k ,那么X<(2^{k+1}-A) 或X\ge (2^{k+1}+2^k-A) 。
建一个
接着和上一层合并,设上一层的下标为
一边做一边基数排序,则每层都可以
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
using ui64 = unsigned long long;
using i128 = __int128;
using ui128 = unsigned __int128;
using f4 = float;
using f8 = double;
using f16 = long double;
template<class T>
bool chmax(T &a, const T &b){
if(a < b){ a = b; return true; }
return false;
}
template<class T>
bool chmin(T &a, const T &b){
if(a > b){ a = b; return true; }
return false;
}
struct Node {
i64 x; int val, tag;
bool operator < (const Node &o) const {
return x < o.x;
}
};
struct Query {
i64 l, r; int id;
bool operator < (const Query &o) const {
return r < o.r;
}
};
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int n, q;
cin >> n >> q;
vector<i64> a(n); i64 mx = 0;
for (int i = 0; i < n; i++) {
cin >> a[i], chmax(mx, a[i]);
}
vector<Query> qry(q); vector<i64> ind;
for (int i = 0; i < q; i++) {
i64 l, r; cin >> l >> r;
ind.push_back(l);
ind.push_back(r + 1);
chmax(mx, r + 1);
qry[i] = {l, r, i};
}
vector<Node> seg;
seg.push_back({0});
seg.push_back({1});
const int B = __lg(mx) + 2;
for (int k = 0; k < B; k++) {
auto lseg = seg;
if (k) {
for (auto i : lseg) i.x |= 1ll << k, seg.push_back(i);
for (auto &i : seg) i.val = i.tag = 0;
stable_partition(a.begin(), a.end(), [&](i64 x) {
return !(x >> (k - 1) & 1);
});
}
stable_partition(ind.begin(), ind.end(), [&](i64 x) {
return !(x >> k & 1);
});
auto it1 = seg.begin();
for (int i = 0; i < ind.size(); i++) {
while (it1->x != (ind[i] & ((1ll << k + 1) - 1))) it1++;
it1->val = 1;
}
it1 = seg.end(); auto it2 = seg.end();
for (int i = 0; i < n; i++) {
i64 key = (1ll << k) - (a[i] & ((1ll << k) - 1));
while (it1 != seg.begin() && prev(it1)->x >= key) it1--;
while (it2 != seg.begin() && prev(it2)->x >= key + (1ll << k)) it2--;
if (a[i] >> k & 1) {
seg[0].tag++, it1->tag--, it1->val = 1;
if (it2 != seg.end()) it2->tag++, it2->val = 1;
}
else {
it1->tag++, it1->val = 1;
if (it2 != seg.end()) it2->tag--, it2->val = 1;
}
}
for (int i = 1; i < seg.size(); i++) seg[i].tag += seg[i - 1].tag;
Node cur{-1}; seg[0].val = 0;
seg[seg.size() >> 1].val = 1;
vector<Node> nseg;
for (int i = 0; i < seg.size(); i++) {
if (seg[i].val) nseg.push_back(cur), cur = Node{-1};
int ov = k ? (i < lseg.size() ? lseg[i].val
: lseg[i - lseg.size()].val) : 0;
chmax(cur.val, ov + seg[i].tag);
cur.tag = seg[i].tag;
if (cur.x == -1) cur.x = seg[i].x;
}
nseg.push_back(cur), swap(seg, nseg);
}
sort(qry.begin(), qry.end());
int i = 0, top = 0; vector<int> ans(q);
for (int j = 0; j < q; j++) {
auto [l, r, id] = qry[j];
for (; i < seg.size() && seg[i].x <= r; i++) {
while (top && seg[top - 1].val < seg[i].val) top--;
seg[top++] = seg[i];
}
ans[id] = lower_bound(seg.begin(), seg.begin() + top, Node{l})->val;
}
for (int i = 0; i < q; i++) cout << ans[i] << '\n';
return 0;
}
::::