1. 程式人生 > >WOJ 43 電話邀請

WOJ 43 電話邀請

namespace 直接 廣泛 same include spl 維護 != closed

並查集縮點這個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; }
View Code

WOJ 43 電話邀請