标签:最小 相关 merge fat 覆盖 sam type 一个 init
并查集缩点这个trick感觉明明用得很广泛,为什么以前都不知道……
先把$m$条线路从小到大排个序,这样可以保证之前合并出来的一定是最小的,大的代价不会把小的覆盖掉。
维护两个并查集,一个用来缩点,另一个用来维护生成树的相关信息
直接把每一条树链合并到lca处,最后再把两个lca合并,因为最后要把两个lca合并,所以求lca拆开跳链的做法比较优秀。
链剖求lca还真的比倍增常数小
感觉get了很多。
Code:
#include <cstdio> #include <algorithm> using namespace std; typedef long long ll; const int N = 1e5 + 5; const int Lg = 20; int n, m, tot = 0, head[N], ufs[N]; int fa[N][Lg], same[N], dep[N], siz[N]; ll cost[N]; struct Edge { int to, nxt; } e[N << 1]; inline void add(int from, int to) { e[++tot].to = to; e[tot].nxt = head[from]; head[from] = tot; } struct Lineway { int u1, v1, u2, v2; ll cost; } a[N]; bool cmp(const Lineway &x, const Lineway &y) { return x.cost < y.cost; } template <typename T> inline void read(T &X) { X = 0; char ch = 0; T op = 1; for(; ch > ‘9‘|| ch < ‘0‘; ch = getchar()) if(ch == ‘-‘) op = -1; for(; ch >= ‘0‘ && ch <= ‘9‘; ch = getchar()) X = (X << 3) + (X << 1) + ch - 48; X *= op; } inline void swap(int &x, int &y) { int t = x; x = y; y = t; } void dfs(int x, int fat, int depth) { fa[x][0] = fat, dep[x] = depth; for(int i = 1; i <= 18; i++) fa[x][i] = fa[fa[x][i - 1]][i - 1]; for(int i = head[x]; i; i = e[i].nxt) { int y = e[i].to; if(y == fat) continue; dfs(y, x, depth + 1); } } inline int getLca(int x, int y) { if(dep[x] < dep[y]) swap(x, y); for(int i = 18; i >= 0; i--) if(dep[fa[x][i]] >= dep[y]) x = fa[x][i]; if(x == y) return x; for(int i = 18; i >= 0; i--) if(fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i]; return fa[x][0]; } inline void init() { for(int i = 1; i <= n; i++) same[i] = i, ufs[i] = i, siz[i] = 1, cost[i] = 0LL; } int find(int x) { return ufs[x] == x ? x : ufs[x] = find(ufs[x]); } int findSame(int x) { return same[x] == x ? x : same[x] = findSame(same[x]); } inline void merge(int x, int y, ll c) { int fx = find(x), fy = find(y); if(fx == fy) return; ufs[fx] = fy; siz[fy] += siz[fx]; cost[fy] += cost[fx] + c; } inline void go(int x, int y, ll c) { for(; ; ) { x = findSame(x); if(dep[x] <= dep[y]) return; merge(x, fa[x][0], c); same[x] = fa[x][0]; } } inline void chain(int x, int y, ll c) { int z = getLca(x, y); go(x, z, c), go(y, z, c); } int main() { read(n), read(m); for(int x, y, i = 1; i < n; i++) { read(x), read(y); add(x, y), add(y, x); } dfs(1, 0, 1); for(int i = 1; i <= m; i++) read(a[i].u1), read(a[i].v1), read(a[i].u2), read(a[i].v2), read(a[i].cost); sort(a + 1, a + 1 + m, cmp); init(); for(int i = 1; i <= m; i++) { chain(a[i].u1, a[i].v1, a[i].cost); chain(a[i].u2, a[i].v2, a[i].cost); merge(a[i].u1, a[i].u2, a[i].cost); } int ans = find(1); printf("%d %lld\n", siz[ans], cost[ans]); return 0; }
标签:最小 相关 merge fat 覆盖 sam type 一个 init
原文地址:https://www.cnblogs.com/CzxingcHen/p/9501566.html