`
wsql
  • 浏览: 11789104 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

Hdu 1863畅通工程 程序参考

 
阅读更多

http://acm.hdu.edu.cn/showproblem.php?pid=1863

#include<iostream>

#include<vector>

using namespace std;



vector< vector<int> > mat;

vector<bool> visited;

vector<int> dist;



int minVertex(){

    int next=-1;	

	for (int i=0;i<dist.size();i++) 

        if (!visited[i])

			if (next==-1 || dist[i]<dist[next]) next=i;  

    return next;

}



int Prim(){    

    dist=mat[0];

    fill(visited.begin(), visited.end(), false);    

    visited[0]=true;

    int cost=0;

    while(true){

        int next = minVertex();

        if (next == -1 || dist[next]==INT_MAX) break;

        visited[next] = true;       

        cost += dist[next];

        for (int i=0; i<mat.size(); i++)

			if (visited[i]==false && mat[next][i]<dist[i]) dist[i]=mat[next][i];                  

    }

	for(int i=0;i<visited.size();i++)

		if (visited[i]==false) return -1;

    return cost;

}



bool run(){

    int i,n,m,x,y,w; 

	scanf("%d %d",&m,&n);

    if(m==0) return false;

    mat.resize(n);

    for(i=0; i<n; i++){

        mat[i].resize(n);

        fill(mat[i].begin(), mat[i].end(),INT_MAX);        

    }

    for(i=0; i<m; i++){      

        scanf("%d%d%d",&x,&y,&w);

        mat[x-1][y-1]=w;

        mat[y-1][x-1]=w;

    }

    dist.resize(n);

    visited.resize(n);

	int t=Prim();

	if (t==-1) printf("?/n");

	else printf("%d/n",t);

    return true;

}



int main(){

   while(run());  

   return 0;

}







分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics