您的位置:首页 > 其它

ZOJ 1372 / POJ 1287 Networking ( kruskal+prim )

2010-09-01 17:35 253 查看
史上第二水最小生成树。

我刚开始是想练练prim算法,没想到是段错误,我感觉自己的算法没什么错误,就把提交到了poj上,没想到AC了,晕倒。没办法,上网搜了一下数据,测试之后发现竟然答案全部正确,faint~~果断换kruskal,用priority_queue,一次过,哎~~~

有人知道我prim哪里错了的说一声啊。。。。。

KRUSKAL:

#include<iostream>
#include<string>
#include<queue>
typedef struct
{
int from,to,w;
} node;node t;
struct cmp
{
bool operator() (const node a,const node b)
{return a.w > b.w;}
};
int p[51];
int find(int i)
{return p[i]==i?i:p[i]=find(p[i]);}
const int INF = 90000990;
using namespace std;
int main(void)
{

priority_queue<node,vector<node>,cmp> q;
int dist[51],flag[51];
int n,m;
int j,i,k;
int from,to,w;
int sum,min,now;
while( cin >> n >> m  )
{
if( n == 0 ) break;
while(!q.empty() ) q.pop();
for( i = 1; i <= n; i++ )
p[i] = i;

for( i = 1; i <= m; i++ )
{
cin >> t.from >> t.to >> t.w;
q.push(t);
}

sum = 0;
while( !q.empty() )
{
t = q.top();q.pop();
from = t.from;
to = t.to;
from = find(from);
to = find(to);
if( from != to )
{sum += t.w;p[from]=to;}
}
cout << sum << endl;
}
return 0;
}


PRIM:

#include<iostream>
#include<string>
const int INF = 90000990;
using namespace std;
int main(void)
{

int map[51][51],dist[51],flag[51];
int n,m;
int j,i,k;
int from,to,w;
int sum,min,now;
while( cin >> n >> m  )
{
if( n == 0 ) break;
for( i = 1; i <= n; i++ )
{
dist[i] = INF;
flag[i] = 0;
for( j = 1; j <= n; j++ )
map[i][j] = INF;
}

for( i = 1; i <= m; i++ )
{
cin >> from >> to >> w;
if( w < map[from][to] )
map[from][to]=map[to][from]=w;
}

dist[from] = sum = 0;
flag[now = from] = 1;
for( i = 1; i < n; i++ )
{
for( j = 1; j <= n; j++ )
if( !flag[j] && map[now][j] < dist[j] )
dist[j] = map[now][j];
for( j = 1,min = INF; j <= n; j++ )
if( !flag[j] && dist[j] < min )
min = dist[now = j];

sum += min;flag[now] = 1;
}

cout << sum << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: