AcWing 920. 最优乘车
H城是一个旅游胜地,每年都有成千上万的人前来观光。
为方便游客,巴士公司在各个旅游景点及宾馆,饭店等地都设置了巴士站并开通了一些单程巴士线路。
每条单程巴士线路从某个巴士站出发,依次途经若干个巴士站,最终到达终点巴士站。
一名旅客最近到H城旅游,他很想去S公园游玩,但如果从他所在的饭店没有一路巴士可以直接到达S公园,则他可能要先乘某一路巴士坐几站,再下来换乘同一站台的另一路巴士, 这样换乘几次后到达S公园。
现在用整数1,2,…N 给H城的所有的巴士站编号,约定这名旅客所在饭店的巴士站编号为1,S公园巴士站的编号为N。
写一个程序,帮助这名旅客寻找一个最优乘车方案,使他在从饭店乘车到S公园的过程中换乘的次数最少
#include<bits/stdc++.h> using namespace std; const int maxn=1e5; const int INF=0x3f3f3f3f; typedef long long LL; typedef pair<int,int> P; struct edge{ int to,cost; }; int vis[maxn],dis[maxn]; vector<edge>g[maxn]; int m,n; void dijkstra() { int s=1; fill(dis,dis+n+10,INF);fill(vis,vis+n+10,0); dis[s]=0; priority_queue< P, vector<P> ,greater<P> > que; que.push({0,s}); while(!que.empty()) { P p=que.top();que.pop(); int v=p.second; if(vis[v]) continue; vis[v]=1; for(int i=0;i<g[v].size();i++) { edge e=g[v][i]; if(dis[e.to]>dis[v]+e.cost) { dis[e.to]=dis[v]+e.cost; que.push({dis[e.to],e.to}); } } } if(dis[n]==0x3f3f3f3f) cout<<"NO"<<endl; else cout<<dis[n]-1<<endl; } int main(void) { cin>>m>>n; string line; getline(cin,line);int lines[maxn]; while(m--) { getline(cin,line); stringstream ssin(line); int cnt=0,p; while(ssin>>p) lines[cnt++]=p; for(int i=0;i<cnt;i++) for(int j=i+1;j<cnt;j++) g[lines[i]].push_back({lines[j],1}); } dijkstra(); return 0; }

浙公网安备 33010602011771号