题意:给你一个仙人掌图,求前K小的生成树的权值之和.
分析:由于图是一个仙人掌,所以显然对于图上的每一个环都需要从环上取出一条边删掉。所以问题就变为有M个集合,每个集合里面都有一堆数字,要从每个集合中选择一个恰好一个数加起来。求所有的这样的和中,前K大的是哪些[求前k大/小:算法竞赛入门经典-训练指南189页]。
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
#include<functional>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 10;
struct E {
int s, to, co;
E() {}
E(int s, int to, int co) : s(s), to(to), co(co) {}
};
struct G {
int s, b;
G(int s, int b) : s(s), b(b) {}
bool operator < (const G &t) const {
return s < t.s;
}
};
int n, m, k, vv = 1;
vector<E> v[maxn];
stack<E> s;
int low[maxn], dfn[maxn];
int clc, ind;
vector<int> x, y, t;
void Merge(vector<int> h) {
priority_queue<G> p;
for(int i = 0; i < h.size(); i++) p.push(G(h[i] + x[0], 0));
t.resize(0);
for(int i = 0; i < k; i++) {
if(p.empty()) break;
G g = p.top(); p.pop();
t.push_back(g.s);
if(g.b + 1 < x.size()) {
p.push(G(g.s - x[g.b] + x[g.b + 1], g.b + 1));
}
}
x = t;
}
void dfs(int u, int fa) {
low[u] = dfn[u] = ++clc;
for(int i = 0; i < v[u].size(); i++) {
int k = v[u][i].to;
if(k == fa) continue;
if(!dfn[k]) {
s.push(v[u][i]);
dfs(k, u);
low[u] = min(low[u], low[k]);
if(low[k] >= dfn[u]) {
y.clear();
while(1) {
E xx = s.top(); s.pop();
y.push_back(xx.co);
if(xx.s == u && xx.to == k) break;
}
if(y.size() > 1) Merge(y);
}
}
else if(dfn[k] < dfn[u]) {
low[u] = min(low[u], dfn[k]);
s.push(v[u][i]);
}
}
}
int main()
{
while(~scanf("%d %d", &n, &m)) {
int u, t, c;
int rec = 0;
for(int i = 0; i < maxn; i++) v[i].clear();
while(!s.empty()) s.pop();
memset(dfn, 0, sizeof dfn);
memset(low, 0, sizeof low);
for(int i = 0; i < m; i++) {
scanf("%d %d %d", &u, &t, &c);
rec += c;
v[u].push_back(E(u, t, c));
v[t].push_back(E(t, u, c));
}
scanf("%d", &k);
clc = 0;
x.clear();
x.push_back(0);
dfs(1, -1);
unsigned ans = 0;
for(int i = 0; i < x.size(); i++) {
ans += (unsigned)(i + 1) * (unsigned)(rec - x[i]);
}
printf("Case #%d: %u\n", vv++, ans);
}
return 0;
}