蓝桥杯 PREV-25 城市建设(最小生成树)

题目链接:

PREV-25 城市建设

思路:

1.先考虑没有码头的情况,使用kruskal算得最小生成树,但是需要检查一下所有点之间是否连通;
2.而后考虑建码头的情况,所谓建码头的城市均可以互相连通,我们可以设立一个虚点,城市到虚点的边权即是建造码头的费用,再使用kruskal算法算得最小生成树的最小权值;
3.我们取两种情况的最小值(注意第一种情况要保证连通);
4.在写最小生成树的时候,我们需要注意如果有负边,则此边必须加入进来;

代码:

#include<bits/stdc++.h>

using namespace std;

const int maxv = 1e4 + 5;
const int maxe = 1e5 + maxv;
int par[maxv], rk[maxv];
void init_set(int n) {
    
    
	for(int i = 0; i <= n; i++) par[i] = i, rk[i] = 0;	
}
inline int find(int x) {
    
    
	if(par[x] == x) return x;
	return par[x] = find(par[x]);	
}
inline void unite(int x, int y) {
    
    
	x = find(x), y = find(y);
	if(x == y) return;
	if(rk[y] > rk[x]) par[x] = y;
	else {
    
    
		par[y] = x;
		if(rk[x] == rk[y]) ++rk[x];
	}		
}
inline bool same(int x, int y) {
    
    
	return find(x) == find(y);	
}

struct edge {
    
    
	int u, v, cost;
	bool operator < (edge & e) const {
    
    
		return cost < e.cost;
	}
}es[maxe];

int kruskal(int v, int e) {
    
    
	init_set(v);
	sort(es, es + e);
	int res = 0, cnt = 0;
	for(int i = 0; i < e; i++) 
	if(!same(es[i].u, es[i].v) || es[i].cost < 0) {
    
    
		unite(es[i].u, es[i].v);
		res += es[i].cost;
	}
	for(int i = 1; i <= v; i++) {
    
    
		if(par[i] == i && ++cnt > 1) return INT_MAX;	
	}
	return res;
}

int main() {
    
    
#ifdef MyTest
	freopen("Sakura.txt", "r", stdin);
#endif
	int n, m;
	scanf("%d %d", &n, &m);
	for(int i = 0; i < m; i++) {
    
    
		scanf("%d %d %d", &es[i].u, &es[i].v, &es[i].cost);
	}
	int cnt = 0, w, best = kruskal(n, m);
	for(int i = 1; i <= n; i++) {
    
    
		scanf("%d", &w);
		if(~w) ++cnt, es[m + cnt - 1] = edge {
    
     n + 1, i, w };
	}
	printf("%d", min(best, kruskal(n + 1, m + cnt)));
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45228537/article/details/104577921
今日推荐