CCF 201609-4

CCF 201609-4
迪杰斯特拉算法微调,重点看一下核心算法怎么写的

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int M=100105;
const int oo=2147483647;
int n,m,tot,s;
int nex[2*M],head[M],to[2*M],adj[2*M],dist[M];
struct node{
    int id,d;
    node(){}
    node(int _id,int _d){id=_id,d=_d;}
    bool operator<(const node n) const {
        return d > n.d;
    }
};
priority_queue <node > Q;
inline void add(int u,int v,int w){
    nex[++tot]=head[u];
    head[u]=tot;
    to[tot]=v;
    adj[tot]=w;
    return;
}

long long ans=0;

int LL[M];
bool viss[M]={false};
void dijkstra(){
    for (int i=1;i<=n;i++)
        dist[i]=oo;
    dist[s]=0;
    Q.push(node(s,0));
    node top;
    while (!Q.empty()){
        top=Q.top();
        Q.pop();
        if (top.d!=dist[top.id])
            continue;
        if(!viss[top.id]){
            viss[top.id]=true;
        }else continue;

        for (int i=head[top.id];i>0;i=nex[i]){
            if (top.d+adj[i]<dist[to[i]]){
                dist[to[i]]=top.d+adj[i];
                if(adj[i]<LL[to[i]] || LL[to[i]]==-1) LL[to[i]]=adj[i];
                Q.push(node(to[i],dist[to[i]]));
            }else if((adj[i]<LL[to[i]] || LL[to[i]]==-1) && top.d+adj[i]==dist[to[i]]){
                LL[to[i]]=adj[i];
//                cout << to[i] << ' ' << adj[i] << endl;
            }
        }
    }
    return;
}

int main(){
    cin>>n>>m;
    for(int i=0;i<=n;i++){
        head[i]=-1;
        LL[i]=-1;
    }
    for (int i=1;i<=m;i++){
        int u,v,w;
        cin>>u>>v>>w;
        add(u,v,w);
        add(v,u,w);
    }
    s=1;
    dijkstra();
    for (int i=2;i<=n;i++){
        ans+=LL[i];
    }
    cout << ans;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值