加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

PKU POJ 2377 Prim

(2010-02-28 21:11:00)
标签:

杂谈

分类: 图论

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;
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有