hdu1233最小生成树prim算法模版题

#include<iostream>

#include<vector>

#include<queue>

#include<cstdio>

using namespace std; struct edge { int from,to,cost; friend bool operator <(edge e1,edge e2) { return e1.cost>e2.cost; } }; const int MAXN=105;

vector<edge>v[MAXN]; bool selected[MAXN]; int prim(int p) {

    priority_queue<edge>q; int sum=0;

    selected[p]=1; int i=0; while(!q.empty()) {

        q.pop(); } for(i=0;i<=int(v[p].size())-1;i++) { int to=v[p][i].to; if(!selected[to]) {

            q.push(v[p][i]); } } while(!q.empty()) { int from; int i=0; int to;

        edge e=q.top();

        to=e.to;

        from=e.from;

        q.pop(); if(!selected[to]) {

            sum=sum+e.cost;

            selected[e.to]=1; for(i=0;i<=int(v[to].size())-1;i++) { int too=v[to][i].to; if(!selected[too]) {

                    q.push(v[to][i]); } } } } return sum; } void init(int n) { int i=0; for(i=0;i<=n;i++) {

        v[i].clear(); }

    memset(selected,0,sizeof(selected)); } int main() { int n; while((scanf("%d",&n))&&(n!=0)) { int from,to,cost;

        init(n);

        n=(n*(n-1))/2; while(n--) {

            scanf("%d%d%d",&from,&to,&cost);

            edge e={from,to,cost};

            v[e.from].push_back(e);

            swap(e.from,e.to);

            v[e.from].push_back(e); }

        cout<<prim(1)<<endl; } return  0; }

  

你可能感兴趣的:(最小生成树)