堆优化+prim最小生成树

· · 个人记录

#include <bits/stdc++.h>
using namespace std;

const int N=5000+10;
const int M=200000+10;

int first[N],tot;
int vis[N],dis[N],n,m;

struct edge
{
    int v,w,next;
} e[M*2];

struct node
{
    int dis,v;
    node(int a,int b)   //构造函数,当压入优先队列时使用 
    {
        dis=a;
        v=b;
    }
};
bool operator < (const node &x,const node &y)    
{
    return x.dis>y.dis; //注意小根堆和大根堆符号相反,千万注意 
}

void add_edge(int u,int v,int w)
{
    e[++tot].next=first[u];
    e[tot].v=v;
    e[tot].w=w;
    first[u]=tot;
    printf("第%lld条边:edge[%lld].next=%lld,first[%lld]=%lld,edge[%lld].go=%lld,edge[%lld].w=%lld;\n",tot,tot,e[tot].next,u,tot,tot,v,tot,w); 
}
void prework()
{
    tot=0;
    memset(dis,127,sizeof(dis));    //memset中间十进制数为2的n次方值 
}

priority_queue <node >q;
void prim()
{
    int cnt=0,sum=0;    //cnt记录已经加入的点数,当为n时结束算法 
    dis[1]=0;
    q.push(node(0,1));  //压入第一个点,随机都可以,这里压入1,每个点离自己都是0 
    while(!q.empty()&&cnt<n)    //第一个点已入树,剩余可加数量cnt为n-1
    {
        int d=q.top().dis,u=q.top().v;  //取出堆头,点u及dis[u],u点若尚未使用,则一定是还未加入生成树 且离已经形成的树上某点 距离最小的点 
        q.pop();
        if(!vis[u])
        {
            cnt++;  //成功入树点数+1 
            sum+=d; //最小生成树长度加d 
            printf("第%d个点%d号成功加入最小生成树,现在树长+%d=%d;\n",cnt,u,d,sum);
            vis[u]=1;   //加点置不可以再加 
            for(int i=first[u]; i; i=e[i].next) //由新加入的点更新与其直连的点dis[],若可更新则入堆备用 
            {
                printf("由%d做中间点:尝试更新点%d;\n",u,e[i].v);
                if(e[i].w<dis[e[i].v])  //刚才加入的点为左点,当前边所向目标点为右点,若当前边值比右点的dis[]小,即目标点离当前左点比被之前的某点更新的dis[]小,则右点当前的dis[]更新 
                {
                    dis[e[i].v]=e[i].w;
                    printf("更新成功目标点%d,现在dis[%d]=%d,(点%d,dis[%d])入队;\n\n",e[i].v,e[i].v,dis[e[i].v],e[i].v,dis[e[i].v]);
                    q.push(node(dis[e[i].v],e[i].v));   //更新后的(dis[],u)入堆备用 
                }
                else
                    printf("当前边权w=%d比dis[%d]=%d还大,更新失败!\n\n",e[i].w,e[i].v,dis[e[i].v]);
            }

        }
    }
    if(cnt==n) printf("%d\n",sum);
    else puts("orz");
}
int main()
{
    int u,v,w;
    prework();
    scanf("%d%d",&n,&m);
    for(int i=1; i<=m; i++)
    {
        scanf("%d%d%d",&u,&v,&w);
        add_edge(u,v,w);
        add_edge(v,u,w);
    }
    prim();
    return 0;
}