MyPojId == zhaozhouyang
好久没有做题了,偶然做一道最大生成树的,以为prim算法是纯粹的贪心,谁知一直WA,晕了半天才意识到每加入一个新的节点,都要从这个节点对剩余的节点进行扫描,来维护目前点到剩余点的最大(小)值,这样的贪心。。。。。不能总是套模板了。。。。
#include<iostream>
using namespace std;
#define MAX 1005
#define MAXCOST -1
int cnt;
int graph[MAX][MAX], Mcost[MAX], vst[MAX];
int MyPrim(int n)
{
int from =
1, to, mm, ans = 0;
memset(vst,
0, sizeof(vst));
vst[1] =
1;
for(int i =
2; i <= n; i ) Mcost[i] = graph[from][i];
for(int i =
2; i <= n; i )
{
mm = -1;
for(int i = 2; i <= n; i )
if (!vst[i] && Mcost[i]
> mm)
mm = Mcost[i], to = i;
if (mm == -1)
return mm;
vst[to] = 1, ans = mm;
for(int i = 2; i <= n; i )
if (graph[to][i] > Mcost[i])
Mcost[i] = graph[to][i];
}
return
ans;
}
int main()
{
int n, m;
scanf("%d %d", &n,
&m);
int i, j;
cnt = 0;
for(i = 1; i <=
n; i )
for(j = 1; j
<= n; j )
graph[i][j] = MAXCOST;
for(i = 0; i <
m; i )
{
int a, b,
c;
scanf("%d %d
%d", &a, &b,
&c);
if (c
> graph[a][b])
{
graph[a][b] = c;
graph[b][a] = c;
}
}
printf("%d\n", MyPrim(n));
return 0;
}
加载中,请稍候......