Loading

P10550 [THUPC2024] 贸易 题解

正式场上拿了这题的首 \(A\),让队伍不至于无奖而返。

思路

容易发现题目的买入卖出过程形似一个括号匹配。

那么我们可以对每一种类型的物品做括号匹配。

若是一个匹配的括号在询问区间内则可以记入答案。

就变成了一个二维数点问题。

离线树状树组即可。

Code

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

#define fro(i, x, y) for (int i = (x); i <= (y); i++)
#define pre(i, x, y) for (int i = (x); i >= (y); i--)

const int N = 5e5 + 10;

int n, q, a[N], c[N], p[N], t[N], l[N], r[N], ans[N];
vector<int> d[N];
vector<int> o[N];

inline void upd(int x) { while (x) t[x]++, x -= (x & (-x)); }
inline auto ask(int x) { int r = 0; while (x <= n) r += t[x], x += (x & (-x)); return r; }

signed main() {
  ios::sync_with_stdio(0), cin.tie(0);
  cin >> n >> q;
  fro(i, 1, n) cin >> a[i];
  fro(i, 1, n) cin >> c[i];
  fro(i, 1, n) {
    if (a[i] == 0) d[c[i]].push_back(i);
    if (a[i] == 1) if (!d[c[i]].empty()) p[i] = d[c[i]].back(), d[c[i]].pop_back();
  }
  fro(i, 1, q) cin >> l[i] >> r[i], o[r[i]].push_back(i);
  fro(i, 1, n) {
    if (p[i]) upd(p[i]);
    for (auto j : o[i]) {
      ans[j] = ask(l[j]);
    }
  }
  fro(i, 1, q) cout << ans[i] << "\n";
  return 0;
}
posted @ 2024-06-03 17:47  JiaY19  阅读(5)  评论(0编辑  收藏  举报