增量最小生成树

定义

每次加入一个新边后,最小生成树的权值是多少?

解法

维护当前的MST的边集,对于新加的一条边,重新计算MST,然后将多余的那条边删掉。

这样每次计算MST的复杂度就是$O(nlogn)$ (手动排序的话就是$O(n)$,因为只有新加的那条边是无序的)

假如一共要加$m$条边,那么时间复杂度为$O(mnlogn)$

例题

题意就是上述。

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
// LightOJ 1123
// ybmj
#include <bits/stdc++.h>
using namespace std;
#define lson (rt << 1)
#define rson (rt << 1 | 1)
#define lson_len (len - (len >> 1))
#define rson_len (len >> 1)
#define pb(x) push_back(x)
#define clr(a, x) memset(a, x, sizeof(a))
#define mp(x, y) make_pair(x, y)
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define my_unique(a) a.resize(distance(a.begin(), unique(a.begin(), a.end())))
#define my_sort_unique(c) (sort(c.begin(), c.end())), my_unique(c)
const int INF = 0x3f3f3f3f;
const int NINF = 0xc0c0c0c0;
const double PI = acos(-1.0);
const int maxn = 205;
int par[maxn];
vector<int> G[maxn];
struct Edge {
int u, v, w;
bool operator<(const Edge &A) const { return w < A.w; }
};
vector<Edge> edges;

inline int find(int x) { return x == par[x] ? x : par[x] = find(par[x]); }
inline bool merge(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return false;
par[x] = y;
return true;
}

int kruskal(vector<Edge> &tmp, int n) {
int ret = 0;
for (int i = 0; i <= n; i++) par[i] = i;
sort(tmp.begin(), tmp.end());
int pos = -1;
for (int i = 0; i < tmp.size(); i++) {
Edge &e = tmp[i];
if (merge(e.u, e.v))
ret += e.w;
else
pos = i;
}
if (pos != -1) tmp.erase(tmp.begin() + pos);
if (tmp.size() == n - 1)
return ret;
else
return -1;
}
int main() {
// /*
#ifndef ONLINE_JUDGE
freopen("1.in", "r", stdin);
freopen("1.out", "w", stdout);
#endif
// */
std::ios::sync_with_stdio(false);
int T, kase = 0;
scanf("%d", &T);
while (T--) {
int n, m;
scanf("%d%d", &n, &m);
edges.clear();
printf("Case %d:\n", ++kase);
for (int i = 0, u, v, w; i < m; i++) {
scanf("%d%d%d", &u, &v, &w);
edges.push_back({u, v, w});
printf("%d\n", kruskal(edges, n));
}
}
}