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;
}