1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include <bits/stdc++.h> using namespace std; const int N = 200000 + 10;
int st[N << 1], top, f[N], d[N]; void init(int n) { for (int i = 1; i <= n; i++) f[i] = i, d[i] = 1; top = 0; } int sf(int x) { return f[x] == x ? x : sf(f[x]); } void back(int tag) { for (; top != tag; top--) { if (st[top] < 0) d[-st[top]]--; else f[st[top]] = st[top]; } } void Union(int x, int y) { if (d[x] > d[y]) swap(x, y); if (d[x] == d[y]) d[y]++, st[++top] = -y; f[x] = y; st[++top] = x; }
struct Data { int x, y, l, r; } E[N];
vector<int> v[N << 2]; void upd(int x, int l, int r, int y) { int mid = (l + r) >> 1; if (E[y].l <= l && r <= E[y].r) { v[x].push_back(y); return; } if (E[y].l < mid) upd(x << 1, l, mid, y); if (E[y].r > mid) upd(x << 1 | 1, mid, r, y); } int n, m, ans = 0; int b[N << 2], x, y, l, r; void dfs(int x, int l, int r) { int mid = (l + r) >> 1, t = top; for (auto y : v[x]) { int fx = sf(E[y].x), fy = sf(E[y].y); if (fx != fy) Union(fx, fy); } if (sf(1) == sf(n)) { ans += b[r] - b[l]; back(t); return; } if (l + 1 == r) { back(t); return; } dfs(x << 1, l, mid); dfs(x << 1 | 1, mid, r); back(t); } int main() { scanf("%d%d", &n, &m); init(n); int cnt = 0; for (int i = 1; i <= m; i++) { scanf("%d%d%d%d", &x, &y, &l, &r); E[i] = {x, y, l, r + 1}; b[++cnt] = l; b[++cnt] = r + 1; } sort(b + 1, b + cnt + 1); int siz = unique(b + 1, b + cnt + 1) - (b + 1); for (int i = 1; i <= m; i++) { E[i].l = lower_bound(b + 1, b + siz + 1, E[i].l) - b; E[i].r = lower_bound(b + 1, b + siz + 1, E[i].r) - b; upd(1, 1, siz, i); } dfs(1, 1, siz); printf("%d\n", ans); return 0; }
|