codeup 1954

今天也是为了cc,努力奋斗的一天ヾ(≧▽≦*)o

疑问

暂无

代码

/*

使用邻接表版prim进行实现
*/
#include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;

const int MAXV = 110;
const int INF = 0x3fffffff;

struct Node{
	int v;
	int cost;
	Node(int v,int cost):v(v),cost(cost){}
};

vector<Node> adj[MAXV];
int d[MAXV];
bool vis[MAXV];
//边数 
int n;
//顶点数 
int m;
int ans;

int prim(){
	//初始化
	fill(d,d+MAXV,INF);
	fill(vis,vis+MAXV,false);
	
	d[1] = 0;
	int len = 0;
	
	for(int i=0;i<m;i++){
		int u = -1;
		int min = INF;
		
		for(int j=1;j<=m;j++){
			if(vis[j] == false && d[j] < min){
				u = j;
				min = d[j];
			}
		}
		
		if(u == -1){
			return -1;
		}
		
		vis[u] = true;
		len += d[u];
		
		for(int k=0;k<adj[u].size();k++){
			int v = adj[u][k].v;
			int cost = adj[u][k].cost;
			
			if(vis[v] == false && d[v] > cost){
				d[v] = cost;
			}
		}
	}
	return len; 
}

int main(){
	while(~scanf("%d %d",&n,&m)){
		if(n == 0){
			break;
		}
		
		//初始化 
		for(int i=0;i<MAXV;i++){
			adj[i].clear();
		}
		ans = 0;
		
		for(int i=0;i<n;i++){
			int a,b,distance;
			scanf("%d %d %d",&a,&b,&distance);
			adj[a].push_back(Node(b,distance));
			adj[b].push_back(Node(a,distance));
		} 
		
		ans = prim();
		if(ans == -1){
			printf("?\n");
		}else{
			printf("%d\n",ans);
		}
	}	
	return 0;
}

反思

  1. while(~scanf("%d %d",&n,&m))相当于while(scanf("%d %d",&n,&m) != EOF);
发布了15 篇原创文章 · 获赞 0 · 访问量 190

猜你喜欢

转载自blog.csdn.net/yc_cy1999/article/details/104094658