poj 1287 Networking(最小生成树)

来源:互联网 发布:正交矩阵和实对称矩阵 编辑:程序博客网 时间:2024/06/10 14:54

思路:最小生成树模板。

#include<iostream>#include<stdio.h>#include<string.h>#define min(a,b) a<b?a:busing namespace std;const int INF=0x3f3f3f3f;const int MAXN=110;bool vis[MAXN];int lowc[MAXN];int Prim(int cost[][MAXN],int n){    int ans=0;    memset(vis,false,sizeof(vis));    vis[0]=true;    for(int i=1; i<n; i++)lowc[i]=cost[0][i];    for(int i=1; i<n; i++)    {        int minc=INF;        int p=-1;        for(int j=0; j<n; j++)            if(!vis[j]&&minc>lowc[j])            {                minc=lowc[j];                p=j;            }        if(minc==INF)return -1;//原图不连通        ans+=minc;        vis[p]=true;        for(int j=0; j<n; j++)            if(!vis[j]&&lowc[j]>cost[p][j])                lowc[j]=cost[p][j];    }    return ans;}int main(){    int cost[MAXN][MAXN];    int N,M;    int u,v,w;    while(~scanf("%d%d",&N,&M))    {        if(N==0)break;        for(int i=0; i<MAXN; ++i)        {            for(int j=0; j<MAXN; ++j)            {                cost[i][j]=INF;            }        }        for(int i=0; i<M; ++i)        {            scanf("%d%d%d",&u,&v,&w);            u--,v--;            cost[u][v]=cost[v][u]=min(w,cost[u][v]);        }        printf("%d\n",Prim(cost,N));    }    return 0;}

0 0
原创粉丝点击