模板 Djkstra+链式前向星+堆优化

模板 Dijkstra+链式前向星+堆优化

#include
#include
#include
#include
#include
#define inf 0x3f3f3f3f
using namespace std;
struct Edge{
    int nex,to,w;
}edge[1000005];
int head[100005];
bool vis[100005];
int cnt=0;
int dis[100005];
int n;
inline void add(int u,int v,int w){
    edge[cnt].to=v;
    edge[cnt].w=w;
    edge[cnt].nex=head[u];
    head[u]=cnt++;
}
inline void read(int&x) {
    int f=1;x=0;char c=getchar();
    while(c>'9'||c<'0') {if(c=='-') f=-1;c=getchar();}
    while(c>='0'&&c<='9') {x=(x<<3)+(x<<1)+c-48,c=getchar();}
    x=x*f;
}

typedef pair<int, int> P;

void dij(int s){
    priority_queue

vector

,greater

>q; memset(vis,0,sizeof vis); memset(dis,0x3f,sizeof dis); dis[s] = 0; q.push(P(0,s)); while (!q.empty()){ P p = q.top(); q.pop(); int u = p.second; if(vis[u])continue; vis[u] = 1; for(int i = head[u];~i;i=edge[i].nex){ int v = edge[i].to; int w = edge[i].w; if(dis[v]>dis[u]+w&&!vis[v]){ dis[v] = dis[u]+w; q.push(P(dis[v],v)); } } } } int main() { int m; scanf("%d%d",&n,&m); cnt=0; memset(head,-1,sizeof head); int u,v,w; for(int i=1;i<=m;i++){ read(u),read(v),read(w); add(u,v,w); } dij(1); if(dis[n]>=inf){ printf("-1\n"); } else{ printf("%d\n",dis[n]); } return 0; } /* 3 5 5 1 2 6 2 3 4 2 4 5 4 5 6 1 5 1 */

你可能感兴趣的:(wanghr模板,最短路径)