仙人掌图。
每个环删一条边就能得到一棵生成树。
每个环都是一个边集,跑出点双连通后,可以用优先队列将这些边集合并出前K大的合集。
输出%u,就不用再对(1<<32)取模了。
代码:
#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define CLR(A, X) memset(A, X, sizeof(A))
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const double eps = 1e-10;
int dcmp(double x){if(fabs(x)<eps) return 0; return x<0?-1:1;}
const int N = 1e3+5, MAXK = 1e6+5;
const int INF = 0x3f3f3f3f;
int K = 0, edge_cnt, dfs_clock, top;
int dfn[N], head[N], low[N], st[3*N];
int res[MAXK], A[3*N], B[MAXK];
struct Edge {
int u, v, w, next;
}edges[3*N];
struct node {
int w, x, y;
bool operator < (const node& A) const {
return w < A.w;
}
};
void init(int n) {
edge_cnt = dfs_clock = top = 0;
for(int i = 1; i <= n; i++) {
head[i] = -1;
dfn[i] = 0;
}
res[0] = 1;
res[1] = 0;
}
void AddEdge(int u, int v, int w) {
edges[edge_cnt] = (Edge){u, v, w, head[u]}, head[u] = edge_cnt++;
edges[edge_cnt] = (Edge){v, u, w, head[v]}, head[v] = edge_cnt++;
}
void Merge() {
B[0] = 0;
priority_queue<node> Q;
for(int i = 1; i <= A[0]; i++) Q.push((node){res[1]+A[i], 1, i});
while(B[0]<K && !Q.empty()) {
node x = Q.top(); Q.pop();
B[++B[0]] = x.w;
if(x.x+1 <= res[0]) {
x.x++;
Q.push((node){res[x.x]+A[x.y], x.x, x.y});
}
}
for(int i = 0; i <= B[0]; i++) res[i] = B[i];
}
void dfs(int u, int fa) {
low[u] = dfn[u] = ++dfs_clock;
for(int i = head[u]; i != -1; i = edges[i].next) {
int v = edges[i].v;
if(v == fa) continue;
if(!dfn[v]) {
st[++top] = i;
dfs(v, u);
low[u] = min(low[u], low[v]);
if(low[v] >= dfn[u]) {
A[0] = 0;
for(;;) {
int e = st[top]; top--;
A[++A[0]] = edges[e].w;
if(edges[e].u==u && edges[e].v==v) break;
}
if(A[0] > 1) Merge();
}
}
else if(dfn[v] < dfn[u]) {
low[u] = min(low[u], dfn[v]);
st[++top] = i;
}
}
}
int main() {
int n, m, u, v, w;
while(~scanf("%d%d", &n, &m)) {
init(n);
int sum = 0, ans = 0;
while(m--) {
scanf("%d%d%d", &u, &v, &w);
AddEdge(u, v, w);
sum += w;
}
scanf("%d", &K);
dfs(1, -1);
for(int i = 1; i <= res[0]; i++) ans += i*(sum-res[i]);
static int cas = 0;
printf("Case #%d: %u\n", ++cas, ans);
}
return 0;
}