您的位置:首页 > 其它

NYOJ38布线问题 prim 最小生成树MST

2011-01-23 03:44 537 查看
http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=38

#include<iostream>
#include<cstring>
using namespace std;
#define typec int
#define V 502
const typec inf = 0x0f3f3f3f;
int vis[V]; typec lowc[V];
typec cost[V][V];
typec prim(int n)
{
int i, j, p;
typec minc, res = 0;
memset(vis, 0, sizeof(vis));
vis[1] = 1;
for (i=2; i<=n; i++) lowc[i] = cost[1][i];
for (i=2; i<=n; i++) {
minc = inf; p = -1;
for (j=1; j<=n; j++)
if (1 != vis[j] && minc > lowc[j]) {
minc = lowc[j]; p = j;
}
if (inf == minc) return -1;
res += minc; vis[p] = 1;
for (j=1; j<=n; j++)
if (0 == vis[j] && lowc[j] > cost[p][j])
lowc[j] = cost[p][j];
}
return res;
}
int main()
{
int n;
cin>>n;
while(n--)
{
int v,e;
cin>>v>>e;
int x,y;
for (int i=0;i<e;i++)
{
cin>>x>>y;
cin>>cost[x][y];
cost[y][x]=cost[x][y];
}
int least=999;
int vcost;
for (int i=0;i<v;i++)
{
cin>>vcost;
if(least>vcost)
least=vcost;
}
least +=prim(v);
cout<<least<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: