最小生成树---prim模板(二叉堆优化)

题目描述

代码

#include 
#include 
#include 
#include 
#include 
#define open(s) freopen(s".in","r",stdin); freopen(s".out","w",stdout);
#define close fclose(stdin); fclose(stdout);

using namespace std;

struct Edge
{
    int next;
    int to;
    int w;
};

struct node
{
    int d;
    int pos;
    bool operator < (const node &b) const
    {
        return d>b.d;
    }
};

int ans;
int n,m;
int cnt;
int head[5005];
int d[5005];
bool f[5005];
Edge edge[400005];

void add(int x,int y,int z)
{
    ++cnt;
    edge[cnt].to=y;
    edge[cnt].next=head[x];
    edge[cnt].w=z;
    head[x]=cnt;
}

void prim()
{
    priority_queueq;
    memset(d,0x3f,sizeof(d));
    d[1]=0;
    int T=n;
    q.push((node){0,1});
    for(int t=1;t && T;)
    {
        node p=q.top(); q.pop(); --t;
        if(f[p.pos]) continue ;
        f[p.pos]=1; ans+=p.d; --T;
        for(int i=head[p.pos];i;i=edge[i].next)
        if(!f[edge[i].to] && d[edge[i].to]>edge[i].w)
        {
            d[edge[i].to]=edge[i].w;
            q.push((node){d[edge[i].to],edge[i].to});
            ++t;
        }
    }
    if(T) printf("orz"); else printf("%d",ans);
}

int main()
{
    open("3366");

    scanf("%d %d",&n,&m);
    for(int i=1;i<=m;++i)
    {
        int x,y,z;
        scanf(" %d %d %d",&x,&y,&z);
        add(x,y,z);
        add(y,x,z);
    }
    prim();

    close;
    return 0;
}

你可能感兴趣的:(----图论----,MST,最小生成树-prim)