Catalog
题解 #10067 【构造完全图】

查看原题请戳这里

看这样一个问题:

有两个完全图$G_1$和$G_2$,$G_1$和$G_2$分别有一颗唯一的最小生成树$T_1$和$T_2$。现在在$T_1$中的点$A$和$T_2$中的点$B$之间连一条长度为$w$的边($w$的长大于$G_1$和$G_2$中任意一条边的长)得到$G_3$,显然$G_3$有唯一的最小生成树。如果在$G_1$中的任意点和$G_2$中的任意点之间加入长为$w+1$ 的边,则$G_3$的最小生成树不变。

于是我们可以在用kruskal求最小生成树时进行加边。考虑一开始所有点都不联通,我们按照输入数据给出的边的边权从小到大加入每一条边,若这条边的权为$w$,则用权为$w+1$的边将刚刚加入的边的两个端点所在的连通块构成的图补成完全图。当然,你不需要真的去加边,统计答案即可。

code

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
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#define ll long long
#define INF 0x7fffffff
#define re register
#define qwq printf("qwq\n");

using namespace std;

ll read() {
register ll x = 0,f = 1;register char ch;
ch = getchar();
while(ch > '9' || ch < '0'){if(ch == '-') f = -f;ch = getchar();}
while(ch <= '9' && ch >= '0'){x = x * 10 + ch - 48;ch = getchar();}
return x * f;
}

struct edge {
ll x,y,dist;
}e[100005];

ll ans;

ll n,fa[100005],sum[100005];

bool mysort(edge a, edge b) {
return a.dist < b.dist;
}

ll find(int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
}

int main()
{
n = read();
for(int i = 1; i < n; i++) {
e[i].x = read(); e[i].y = read(); e[i].dist = read();
fa[i] = i; sum[i] = 1;
}
sum[n] = 1; fa[n] = n;
sort(e + 1, e + n, mysort);
for(int i = 1; i < n; i++) {
ll fx = find(e[i].x), fy = find(e[i].y);
ans = ans + sum[fx] * sum[fy] * (e[i].dist + 1) - 1;
fa[fx] = fy; sum[fy] = sum[fy] + sum[fx];
}
printf("%lld", ans);
return 0;
}
Author: wflight
Link: http://yoursite.com/2020/07/30/题解-10067-【构造完全图】/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶

Comment