1 solutions
-
-2
颐气(capital)
此题显然是最小生成树问题,但 过大,直接 Kruskal 无法通过。发现每类横边或纵边的权值都一样,在排序后 Kruskal 时是连续加入的,因此可以试图整体加入一类边。
注意到加入一类边相当于将网格图的两行或两列合并,且一个方向的一类边加入时另一方向的边不会影响其是否被加入,只会影响当前类边中实际加入的边个数。例如加入一类横边时,若已加入了 类纵边,则 列被缩成 列,加入当前类横边时只会加入 条。因此对于横纵坐标分别以横纵类边做 Kruskal,并同时维护另一方向已加入的边类数以计算加入当前类边时的实际边数即可。复杂度 。
#include<bits/stdc++.h> #define int long long using namespace std; const int N=5e6+10; int n, m, p, q, tot, fa[N], cl, cr, ans, sum; struct dat { int op, x, y, w; } a[N]; bool cmp(dat u,dat v) { return u.w<v.w; } int get(int x) { if(fa[x]==x) return x; return fa[x]=get(fa[x]); } signed main() { freopen("capital.in","r",stdin); freopen("capital.out","w",stdout); ios::sync_with_stdio(0); cin.tie(0); cin >> n >> m >> p >> q; for(int i=1; i<=p; ++i) { tot++; cin >> a[tot].x >> a[tot].y >> a[tot].w; a[tot].op=1, sum+=a[tot].w*n; } for(int i=1; i<=q; ++i) { tot++; cin >> a[tot].x >> a[tot].y >> a[tot].w; a[tot].op=2, sum+=a[tot].w*m; } sort(a+1,a+1+tot,cmp); for(int i=1; i<=n+m; ++i) fa[i]=i; for(int l=1; l<=tot; ++l) { if(a[l].op==1) { int x=get(a[l].x), y=get(a[l].y); if(x^y) fa[x]=y, ans+=a[l].w*(n-cr), cl++; } else { int x=get(a[l].x+m), y=get(a[l].y+m); if(x^y) fa[x]=y, ans+=a[l].w*(m-cl), cr++; } } cout << sum-ans; return 0; }
- 1
Information
- ID
- 132
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 8
- Tags
- (None)
- # Submissions
- 22
- Accepted
- 6
- Uploaded By