关闭

Prim_poj 1287 Networking

标签: networkingstructc
171人阅读 评论(0) 收藏 举报
分类:

题意:给出一个具有n个顶点和m条边的图,求其最小生成树。

#include<cstdio>
#include<cstring>
#include<vector>

#define MAXVN 55
#define INF 10000000

using namespace std;
typedef struct{
    int u,v,value;
}Edge;

typedef vector<Edge> VE;
VE eg[MAXVN];

vector<int> UsedPoint;
vector<Edge> UsedEdge;
int visited[MAXVN];

int vn, en;

int Prim(){
    memset(visited, 0 , sizeof(visited));
    UsedEdge.clear();
    UsedPoint.clear();
    UsedPoint.push_back(1);
    visited[1] = 1;
    int count = 1, minE = INF, iflag,jflag;
    while(count++ < vn){
        minE = INF;
        for(int i = 0; i < UsedPoint.size(); i++){
            int tmp = UsedPoint[i];
            for(int j = 0; j < eg[tmp].size(); j++){
                Edge e = eg[tmp][j];
                if(!visited[e.v] && e.value < minE){
                    minE = e.value;
                    iflag = tmp;
                    jflag = j;
                }
            }
        }
        UsedPoint.push_back(eg[iflag][jflag].v);
        visited[eg[iflag][jflag].v] = 1;
        UsedEdge.push_back(eg[iflag][jflag]);
    }
    int sum = 0;
    for(int i = 0; i < UsedEdge.size(); i++){
        sum+=UsedEdge[i].value;
    }
    return sum;

}
int main(){
    int a,b,c,sum;
    Edge te;
    while(scanf("%d", &vn),vn){
        sum = 0;
        for(int i = 1; i <= vn; i++){
            eg[i].clear();
        }
        scanf("%d", &en);
        getchar();
        for(int i = 0; i < en; i++){
            scanf("%d%d%d", &a, &b, &c);
            te.u = a;
            te.v = b;
            te.value = c;
            eg[a].push_back(te);
            te.u = b;
            te.v = a;
            te.value = c;
            eg[b].push_back(te);
        }
        sum = Prim();
        printf("%d\n", sum);
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:81070次
    • 积分:1878
    • 等级:
    • 排名:千里之外
    • 原创:99篇
    • 转载:12篇
    • 译文:0篇
    • 评论:6条
    最新评论