生成樹專題訓練1

好長時間沒碰電腦了,決定把簡單的東西再過一遍,同時加深理解,提高認知,對其有更深的認識。
比較常用的應該改是kruscal了。
kruscal是用邊做的,把邊排序,然後按順序加邊,直到形成一棵樹。
今天的例題是個簡單題。
poj2485
就不翻譯了,應該可以看懂。
顯然是直接用最小生成樹,然後再找邊的時候,保存最後一次加的邊的長度,即爲最終答案。
代碼如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct edge{
	int u,v,w;
};
int readInt(){
	int a=0;
	char c=getchar();
	for(;c<'0'||c>'9';c=getchar()){}
	for(;c>='0'&&c<='9';c=getchar()){
		a=a*10+c-'0';
	}
	return a;
}
int T;
int n;
edge e[250005];
int p[505];
int cnt;
int ans;
int cmp(edge a,edge b){
	return a.w<=b.w;
}
int find(int cur){
	return cur==p[cur]?p[cur]:find(p[cur]);
}
void work(){
	ans=0;
	for(int i=1;i<=n;i++){
		p[i]=i;
	}
	sort(e,e+cnt,cmp);
	for(int i=0;i<cnt;i++){
		int x=find(e[i].u),y=find(e[i].v);
		if(x!=y){
			ans=max(ans,e[i].w);
			p[x]=y;
		}
	}
}
int main(){
	T=readInt();
	while(T--){
		n=readInt();
		cnt=0;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				int w;
				w=readInt();
				if(j>i){
					e[cnt].w=w;
					e[cnt].u=i;
					e[cnt].v=j;
					cnt++;
				}
				
			}
		}
		work();
		printf("%d\n",ans);
		
	} 
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章