【题目描述】
给定一个有向连通图,求从1到n的最短路。
【输入】
第一行两个整数n,m,代表点数和边数;
接下来m行,每行三个整数s,t,d,代表从s到t有一条长度为d的有向边。
【输出】
输出一个整数表示最短距离。
【输入样例】
2 3
1 2 1
1 2 -1
2 2 0
【输出样例】
-1
【提示】
【数据规模及约定】
N≤20000,M≤40000,1≤S,T≤N,−109≤D≤109
保证没有负环、1可以到达N。
此题要用 long long 不然会溢出
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N =500010;
long long h[N],e[N],ne[N],w[N],idx;
long long dist[N];
bool st[N];
long long n,m;
void add(int a,int b,int c){
if(a==b) return;
e[idx]=b; w[idx]=c; ne[idx]=h[a]; h[a]=idx++;
}
void spfa(){
queue <long long> q;
memset(dist,0x3f,sizeof(dist));
dist[1]=0;
q.push(1);
st[1]=true;
while(q.size()){
int t=q.front();
q.pop();
st[t]=false;
for(long long i=h[t];i!=-1;i=ne[i]){
long long j=e[i];
if(dist[j]>dist[t]+w[i]){
dist[j]=dist[t]+w[i];
if(!st[j]){
q.push(j);
st[j]=true;
}
}
}
}
}
int main(){
cin>>n>>m;
memset(h,-1,sizeof(h));
while(m--){
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
spfa();
cout<<dist[n];
return 0;
}