【图论】-最短路-模板题-牛客网

题目链接:

https://www.nowcoder.com/questionTerminal/b39dacd574ba49c7a4d10974b1bb325f

Dijkstra

 

#include
using namespace std;
#define en '\n'
#define ll long long
const ll maxn =1e5+10;
const int inf=0x3f3f3f3f;
#define lowbit(x) (x&-x)
int head[maxn];
int rd(){int tem;scanf("%d",&tem);return tem;}
int n,m;
int val;
int cnt=0;
bool v[maxn];
struct node{
    int nxt,v,val;
}edge[maxn];
int d[maxn];
priority_queue >q;
void add(int x,int y,int val){
    edge[++cnt]=node{head[x],y,val};
    head[x]=cnt;
}
signed main(){
    #ifdef swt
     freopen("input.txt","r",stdin);
    #endif
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        d[i]=inf;
    }
    int x,y,val;
    d[1]=0;
    while(m--){
        cin>>x>>y>>val;
        add(x,y,val);
    }
    q.push({0,1});
    while(!q.empty()){
        int now=q.top().second;
        q.pop();
        if(v[now])continue;
        v[now]=1;
        for(int i=head[now];i;i=edge[i].nxt){
            int v=edge[i].v;
            if(d[v]>d[now]+edge[i].val){
                d[v]=d[now]+edge[i].val;
                q.push({-d[v],v});
            }
        }
    }
    if(d[n]==inf)
        cout<<-1<

你可能感兴趣的:(图论--最短路)