Agri-Net(最小生成树)

基础题,最小生成树

#include<string>
#include<string.h>
#include<iostream>
#include<stdio.h>
#include<queue>
#include<algorithm>
using namespace std;
int a[110][110];
int book[110];
int visit[110];
int main(){
	int n;
	while(scanf("%d",&n)!=EOF){
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				scanf("%d",&a[i][j]);
			}
			book[i] = 0x3f3f3f3f;
		}
		long long ans = 0;
		memset(visit,0,sizeof(visit));
		queue<int >q;
		visit[0] = 1;
		q.push(0);
		int count = 1;
		while(!q.empty()&&count!=n){
			int t = q.front();
			q.pop();
			int p;
			int low = 0x3f3f3f3f;
			for(int i=0;i<n;i++){
				if(book[i]>a[t][i]&&visit[i]==0){
					book[i] = a[t][i];
				}
				if(low>book[i]&&visit[i]==0){	//注意 
					low = book[i];
					p = i;
				}
			}
			visit[p] = 1;
			ans += book[p];
			count++;
			q.push(p);
		}
		printf("%I64d\n",ans);
	}
	return 0;
}


你可能感兴趣的:(最小生成树)