NOIP模拟 MST - 类次小生成树

题目大意:

给一张无向图,可以将图中权值为v的边修改为k-v,求修改后的最小生成树边权和。

题目分析:

最小生成树的环切定理:任何非树边一定比对应树链上的所有边权值要大。否则我们可以将链上最大的树边删去而连接这一条边。
运用这个性质,先求出原图的最小生成树,然后再来枚举边,如果枚举到一条边:

  • 它是最小生成树中的边,如果更优, 那么更新答案。
  • 它不是最小生成树中的边,找到它连接的两点在最小生成树中的链上边权的最大值,如果山出发这条边,加入枚举的这条更优,就更新答案

code

#include<bits/stdc++.h>
using namespace std;
const int N = 1050, M = 1e6 + 50, OO = 0x3f3f3f3f;
int n;
int m, k, ans1, ans2;
struct node{
	int x, y, t;
	inline bool operator < (const node &b) const{
		return t < b.t;
	}
}edge[M];
struct node2{
	int ecnt, adj[N], go[N << 1], nxt[N << 1], len[N << 1], used[M], d[N][N], anc[N];
	node2(){}
	inline void init(){
		ecnt = 0;
		memset(adj, 0, sizeof adj);
		memset(used, 0, sizeof used);
		for(int i = 1; i <= n; i++) anc[i] = i;
	}
	inline int getAnc(int x){
		return x == anc[x] ? x : (anc[x] = getAnc(anc[x]));
	}
	inline void addEdge(int u, int v, int t){
		nxt[++ecnt] = adj[u], adj[u] = ecnt, go[ecnt] = v, len[ecnt] = t;
	}
	inline int kruskals(){
		int ret = 0;
		sort(edge + 1, edge + m + 1);
		for(int i = 1; i <= m; i++){
			int fx = getAnc(edge[i].x), fy = getAnc(edge[i].y);
			if(fx != fy){
				anc[fx] = fy;
				ret += edge[i].t;
				used[i] = 1;
				addEdge(edge[i].x, edge[i].y, edge[i].t);
				addEdge(edge[i].y, edge[i].x, edge[i].t);
			}
		}
		return ret;
	}
	inline void dfs(int now, int u, int f, int mx){
		d[now][u] = d[u][now] = mx;
		for(int e = adj[u]; e; e = nxt[e]){
			int v = go[e];
			if(v == f) continue;
			dfs(now, v, u, max(mx, len[e]));
		}
	}
}mst;

namespace IO{
    inline int read(){
        int i = 0, f = 1; char ch = getchar();
        for(; (ch < '0' || ch > '9') && ch != '-'; ch = getchar());
        if(ch == '-') f = -1, ch = getchar();
        for(; ch >= '0' && ch <= '9'; ch = getchar()) i = (i << 3) + (i << 1) + (ch - '0');
        return i * f;
    }
    inline void wr(int x){
        if(x < 0) x = -x, putchar('-');
        if(x > 9) wr(x / 10);
        putchar(x % 10 + '0');
    } 
}using namespace IO;

int main(){
	freopen("h.in", "r", stdin);
	n = read(), m = read(), k = read();
	ans2 = OO;
	mst.init();
	for(int i = 1; i <= m; i++)
		edge[i].x = read(), edge[i].y = read(), edge[i].t = read();
	ans1 = mst.kruskals();
	for(int i = 1; i <= n; i++)
		mst.dfs(i, i, 0, 0);
//	for(int i = 1; i <= n; i++) 
//		for(int j = 1; j <= n; j++)
//			cout<<i<<" "<<j<<" "<<mst.d[i][j]<<endl;
	for(int i = 1; i <= m; i++){
		int x = edge[i].x, y = edge[i].y, t = edge[i].t;
		if(mst.used[i] == 1)
			ans2 = min(ans2, ans1 - edge[i].t + (k - edge[i].t));
		else
			ans2 = min(ans2, ans1 - mst.d[x][y] + (k - edge[i].t));
	}
	printf("%d", ans2);
	return 0;
}
posted @ 2017-10-25 21:22  CzYoL  阅读(285)  评论(0编辑  收藏  举报