洛谷P2330 [SCOI2005]繁忙的都市【最小生成樹】

題目鏈接:P2330 [SCOI2005]繁忙的都市

程序說明:

題目中的條件明顯能看出來是最小生成樹吧(太明顯了),最後要求的是最小生成樹裏權值最大的邊。prim和kruskal都能做,kruskal做這道題簡直不要太簡單。

代碼如下:

#include <iostream>
#include <algorithm>
using namespace std;

const int N = 1010, M = 100010;
int n, m, p[N], cnt, maxn;
struct node {
	int a, b, w;
	bool operator < (const node &x) const {
		return w < x.w;
	}
} edge[M];

int find(int x) {
	if(p[x] != x) p[x] = find(p[x]);
	return p[x];
}

void kruskal() {
	sort(edge, edge + m);
	for(int i = 1; i <= n; i++) p[i] = i;
	for(int i = 0; i < m; i++) {
		int a = edge[i].a;
		int b = edge[i].b;
		int w = edge[i].w;
		a = find(a), b = find(b);
		if(a != b) {
			p[a] = b;
			cnt++;
			maxn = w;
		}
	}	
}
int main() {
	cin>>n>>m;
	for(int i = 0; i < m; i++) {
		int a, b, w;
		cin>>a>>b>>w;
		edge[i].a = a;
		edge[i].b = b;
		edge[i].w = w;
	}	
	kruskal();
	cout<<n - 1<<" "<<maxn;
	return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
const int N = 5010, INF = 0x3f3f3f3f;

int g[N][N], dist[N], st[N], n, m, maxn;

int prim() {
	memset(dist, 0x3f, sizeof dist);
	int res = 0;
	for(int i = 0; i < n; i++) {
		int t = -1;
		for(int j = 1; j <= n; j++)
			if(!st[j] && (t == -1 || dist[j] < dist[t]))
				t = j;
		
		if(i && dist[t] == INF) return INF;	
		if(i && dist[t] != INF)	maxn = max(maxn, dist[t]);
		st[t] = 1;
		for(int j = 1; j <= n; j++)
			dist[j] = min(dist[j], g[t][j]);			
	}
}
int main() {
	ios::sync_with_stdio(0), cin.tie(0);
	memset(g, 0x3f, sizeof g);
	cin>>n>>m;
	while(m--) {
		int x, y, z;
		cin>>x>>y>>z;
		g[x][y] = g[y][x] = min(g[x][y], z);
	}
	prim();
		
	cout<<n - 1<<" "<<maxn<<endl;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章