dijkstra+priority_queue+vector
最短路
时间限制: 3 Sec 内存限制: 128 MB题目描述
给定M条边,N个点的带权无向图
求1到N的最短路
N<=100000
M<=500000
输入
第一行:N,M
接下来M行3个正整数:ai,bi,ci 表示ai,bi之间有一条长度为ci的路
0<=ci<=1000
输出
一个整数,表示1到N的最短距离
样例输入
4 4
1 2 1
2 3 1
3 4 1
2 4 1
样例输出
2
提示
注意图中可能有重边和自环,数据保证1到N有路径相连
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<cstring> 5 #include<cmath> 6 #include<cstdlib> 7 #include<vector> 8 #include <queue> 9 using namespace std; 10 typedef long long ll; 11 typedef long double ld; 12 typedef pair<int,int> pr; 13 const double pi=acos(-1); 14 #define rep(i,a,n) for(int i=a;i<=n;i++) 15 #define per(i,n,a) for(int i=n;i>=a;i--) 16 #define Rep(i,u) for(int i=head[u];i;i=Next[i]) 17 #define clr(a) memset(a,0,sizeof(a)) 18 #define pb push_back 19 #define mp make_pair 20 #define fi first 21 #define sc second 22 #define pq priority_queue 23 #define pqb priority_queue <int, vector<int>, less<int> > 24 #define pqs priority_queue <pr, vector<pr>, greater<pr> > 25 ld eps=1e-9; 26 ll pp=1000000007; 27 ll mo(ll a,ll pp){if(a>=0 && a<pp)return a;a%=pp;if(a<0)a+=pp;return a;} 28 ll powmod(ll a,ll b,ll pp){ll ans=1;for(;b;b>>=1,a=mo(a*a,pp))if(b&1)ans=mo(ans*a,pp);return ans;} 29 void fre() { freopen("c://test//input.in", "r", stdin); freopen("c://test//output.out", "w", stdout); } 30 //void add(int x,int y,int z){ v[++e]=y; next[e]=head[x]; head[x]=e; cost[e]=z; } 31 int dx[5]={0,-1,1,0,0},dy[5]={0,0,0,-1,1}; 32 ll read(){ ll ans=0; char last=' ',ch=getchar(); 33 while(ch<'0' || ch>'9')last=ch,ch=getchar(); 34 while(ch>='0' && ch<='9')ans=ans*10+ch-'0',ch=getchar(); 35 if(last=='-')ans=-ans; return ans; 36 } 37 #define N 100005 38 const int inf=1<<29; 39 vector<pr> vec[N]; 40 pqs Q; 41 int dis[N],vis[N]; 42 int main() 43 { 44 int n=read(),m=read(); 45 for (int i=1;i<=m;i++) { 46 int a=read(),b=read(),c=read(); 47 vec[a].pb(mp(b,c)); 48 vec[b].pb(mp(a,c)); 49 } 50 for (int i=1;i<=n;i++) dis[i]=inf; 51 dis[1]=0; Q.push(mp(dis[1],1)); 52 while (!Q.empty()){ 53 pr p=Q.top(); Q.pop(); int u=p.sc; 54 if (vis[u]) continue; vis[u]=1; 55 for (int i=0;i<vec[u].size();i++){ 56 if (vec[u][i].sc+dis[u]<dis[vec[u][i].fi]) 57 dis[vec[u][i].fi]=vec[u][i].sc+dis[u]; 58 Q.push(mp(dis[vec[u][i].fi],vec[u][i].fi)); 59 } 60 } 61 printf("%d",dis[n]); 62 return 0; 63 }