P3527 [POI2011] MET-Meteors

· · 题解

P3527 [POI2011] MET-Meteors

给出一种不同于 jiangly 的更容易理解且更好写的单 \log 做法。

设 n, m, k 同阶,很显然我们有主席树 + 直接二分的做法,但空间复杂度和时间复杂度不优秀。

考虑整体二分,则 \mathrm{solve} 相当于进行所有区间加之后单点查询,通过差分做到线性。问题在于向下递归时,我们不能直接下传原有坐标,否则每个区间处理的复杂度均为 \mathcal{O}(n)。

解决方法非常简单。在处理每个 \mathrm {solve} 前,将所有相关下标离散化。这里离散化可以直接用桶维护而不需要排序,因为复杂度和它父区间离散化后的值域相关,加起来还是 \mathcal{O}(n\log n) 的。

时间复杂度 \mathcal{O}(n\log n),空间复杂度 \mathcal{O}(n)。代码非常好写,因为常数小所以跑得也很快。

#include <bits/stdc++.h>
using namespace std;
#define TIME 1e3 * clock() / CLOCKS_PER_SEC

constexpr int N = 3e5 + 5;
int n, m, k, cnt, p[N], ans[N];
int id[N], _id[N];
long long d[N], res[N];
vector<int> buc[N];
struct shower {
  int id, l, r, a;
} c[N << 1];
void solve(int l, int r, int cl, int cr, int range) {
  if(cl > cr) return;
  if(l == r) {
    for(int i = cl; i <= cr; i++) ans[id[i]] = l;
    return;
  }

  // relabel
  for(int i = 1; i <= range; i++) d[i] = 0;
  for(int i = cl; i <= cr; i++) for(int it : buc[id[i]]) d[it] = 1;
  for(int i = 1; i <= range; i++) d[i] += d[i - 1];
  for(int i = cl; i <= cr; i++) for(int &it : buc[id[i]]) it = d[it];
  for(int i = l; i <= r; i++) c[i].l = d[c[i].l - 1] + 1, c[i].r = d[c[i].r];
  range = d[range];

  // binary search
  int m = l + r >> 1, cm = cl - 1, cd;
  for(int i = 1; i <= range; i++) d[i] = 0;
  for(int i = l; i <= m; i++) d[c[i].l] += c[i].a, d[c[i].r + 1] -= c[i].a;
  for(int i = 2; i <= range; i++) d[i] += d[i - 1];
  for(int i = cl; i <= cr; i++) {
    res[i] = 0;
    for(int it : buc[id[i]]) res[i] = min(0x3f3f3f3fll, res[i] + d[it]);
    if(res[i] >= p[id[i]]) _id[++cm] = id[i];
  }
  cd = cm;
  for(int i = cl; i <= cr; i++)
    if(res[i] < p[id[i]])
      p[id[i]] -= res[i], _id[++cm] = id[i];
  for(int i = cl; i <= cr; i++) id[i] = _id[i];

  solve(l, m, cl, cd, range);
  solve(m + 1, r, cd + 1, cr, range);
}
int main() {
  #ifdef ALEX_WEI
    FILE* IN = freopen("1.in", "r", stdin);
    FILE* OUT = freopen("1.out", "w", stdout);
  #endif
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n >> m;
  for(int i = 1, o; i <= m; i++) cin >> o, buc[o].push_back(i);
  for(int i = 1; i <= n; i++) cin >> p[i];
  cin >> k;
  for(int i = 1; i <= k; i++) {
    int l, r, a;
    cin >> l >> r >> a;
    if(l <= r) c[++cnt] = {i, l, r, a};
    else c[++cnt] = {i, l, m, a}, c[++cnt] = {i, 1, r, a};
  }
  for(int i = 1; i <= n; i++) id[i] = i;
  solve(1, cnt + 1, 1, n, m);
  for(int i = 1; i <= n; i++)
    if(ans[i] > cnt) cout << "NIE\n";
    else cout << c[ans[i]].id << "\n";
  return cerr << "Time: " << TIME << " ms\n", 0;
}