poj 1258 Agri-Net(最小生成树,普里姆算法)

来源:互联网 发布:淘宝强行退款 编辑:程序博客网 时间:2024/06/01 10:06

小记:熟练了下prim,其实是照着dijsktra来写的,就一个判断条件的不同而已


思路:prim算法


代码:

#include <iostream>#include <stdio.h>#include <string.h>#include <math.h>#include <stdlib.h>#include <map>#include <set>#include <vector>#include <stack>#include <queue>#include <algorithm>#include <string>using namespace std;#define mst(a,b) memset(a,b,sizeof(a))#define REP(a,b,c) for(int a = b; a < c; ++a)#define eps 10e-8const int MAX_ = 155;const int N = 100010;const int INF = 0x7fffffff;int n;struct node{    int s, t;};int g[MAX_][MAX_];int d[MAX_];bool vis[MAX_];int m, cnt;int prim(int start){    REP(i, 0, n){        d[i] = INF;        vis[i] = 0;    }    int sum = 0;    d[start] = 0;    REP(i, 0, n){        int mmin = INF, k;        REP(j, 0, n){            if(!vis[j] && d[j] < mmin){                mmin = d[j];                k = j;            }        }        vis[k]  = 1;        sum += mmin;        REP(j, 0, n){            if(!vis[j]  && d[j] > g[k][j]){                d[j] = g[k][j];            }        }    }    return sum;}int main(){int T, ss, tt;while(~scanf("%d", &n)){        REP(i, 0, n)REP(j, 0, n){            scanf("%d", &g[i][j]);        }        int ans = prim(0);        printf("%d\n", ans);}return 0;}


0 0