hdu 1233 堆优化prim

#include<bits/stdc++.h>
using namespace std;
const int maxn=100005;
const int inf=0x3f3f3f3f;
typedef struct
{
    int to,cost,next;
}node;
node edge[maxn*2];
int cnt,pre[maxn],dis[maxn],vis[maxn];
struct cmp
{
    bool operator() (int &a, int &b)const{
        return dis[a] > dis[b];
    }
};
void prim()
{
    int res=0;
    priority_queue<int,vector<int>,cmp> que;
    dis[1]=0;
    vis[1]=1;
    que.push(1);
    while(que.size())
    {
        int now=que.top();
        que.pop();
        res+=dis[now];
        dis[now]=0;
        for(int i=pre[now];i!=-1;i=edge[i].next)
        {
            int tp=edge[i].to;
            dis[tp]=min(dis[tp],edge[i].cost);
            if(vis[tp])
            {
                queue<int> quee;
                while(que.size())
                {
                    quee.push(que.top());
                    que.pop();
                }
                while(quee.size())
                {
                    que.push(quee.front());
                    quee.pop();
                }
                continue;
            }
            que.push(tp);
            vis[tp]=1;
        }
    }
    printf("%d\n",res);
}
void add_edge(int u,int v,int w)
{
    edge[cnt].cost=w;
    edge[cnt].to=v;
    edge[cnt].next=pre[u];
    pre[u]=cnt++;
}
void init()
{
    memset(pre,-1,sizeof(pre));
    memset(dis,0x3f,sizeof(dis));
    memset(vis,0,sizeof(vis));
    cnt=0;
}
int main()
{
    int n,u,v,w,i;
    while(scanf("%d",&n)!=EOF&&n)
    {
        init();
        for(i=1;i<=n*(n-1)/2;i++)
        {
            scanf("%d%d%d",&u,&v,&w);
            add_edge(u,v,w);
            add_edge(v,u,w);
        }
        prim();
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值