Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- mt19937 rd(chrono::steady_clock::now().time_since_epoch().count());
- struct Node {
- int key, prior, val = 1;
- Node *l = nullptr, *m = nullptr, *r = nullptr;
- Node(int _key) { key = _key; prior = rd(); }
- };
- typedef pair<Node*, Node*> nodepair;
- const int MAXK = 1e6 + 1, inf = 2e9;
- vector<Node*> color(MAXK);
- int val(Node *p) { return (p == nullptr ? 0 : p->val); }
- void upd(Node *p) {
- if (p == nullptr) return;
- p->val = val(p->l) + val(p->m) + val(p->r) + 1;
- }
- void push(Node *p);
- nodepair split(Node *p, int x);
- Node* merge(Node *p1, Node *p2);
- void push(Node *p) {
- if (p == nullptr || p->m == nullptr) return;
- push(p->l);
- push(p->r);
- nodepair q = split(p->m, p->key);
- if (p->l) {
- p->l->m = q.fi;
- } else {
- p->l = q.fi;
- }
- if (p->r) {
- p->r->m = q.se;
- } else {
- p->r = q.se;
- }
- p->m = nullptr;
- upd(p); upd(p->l); upd(p->r);
- }
- nodepair split(Node *p, int x) {
- if (p == nullptr) return {nullptr, nullptr};
- push(p);
- if (p->key <= x) {
- nodepair q = split(p->r, x);
- p->r = q.fi;
- upd(p);
- return {p, q.se};
- } else {
- nodepair q = split(p->l, x);
- p->l = q.se;
- upd(p);
- return {q.fi, p};
- }
- }
- Node* merge(Node *p1, Node *p2) {
- if (p1 == nullptr) return p2;
- if (p2 == nullptr) return p1;
- push(p1); push(p2);
- if (p1->prior > p2->prior) {
- p1->r = merge(p1->r, p2);
- upd(p1);
- return p1;
- } else {
- p2->l = merge(p1, p2->l);
- upd(p2);
- return p2;
- }
- }
- Node* unite(Node *p1, Node *p2) {
- if (p1 == nullptr) return p2;
- if (p2 == nullptr) return p1;
- if (p1->prior < p2->prior) swap(p1, p2);
- push(p1);
- p1->m = p2;
- upd(p1);
- return p1;
- }
- void insert(int c, int k) {
- Node *p = new Node(k);
- nodepair q = split(color[c], k);
- color[c] = merge(merge(q.fi, p), q.se);
- }
- Node* remove_segment(int c, int l, int r) {
- nodepair q = split(color[c], r);
- nodepair p = split(q.fi, l - 1);
- color[c] = merge(p.fi, q.se);
- return p.se;
- }
- int update(int l, int r, int c1, int c2) {
- Node *p = remove_segment(c1, l, r);
- int ans = val(p);
- color[c2] = unite(color[c2], p);
- return ans;
- }
- int main() {
- fast
- // file_in
- int n, q;
- cin >> n >> q;
- for (int i = 1; i <= n; ++i) {
- insert(0, i);
- }
- int l, r, c1, c2;
- while (q--) {
- cin >> l >> r >> c1 >> c2;
- cout << update(l, r, c1, c2) << '\n';
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement