https://blog.csdn.net/HTallperson/article/details/81118574
Alice和Bob现在要乘飞机旅行,他们选择了一家相对便宜的航空公司。该航空公司一共在n个城市设有业务,设这些城市分别标记为0到n-1,一共有m种航线,每种航线连接两个城市,并且航线有一定的价格。Alice和Bob现在要从一个城市沿着航线到达另一个城市,途中可以进行转机。航空公司对他们这次旅行也推出优惠,他们可以免费在最多k种航线上搭乘飞机。那么Alice和Bob这次出行最少花费多少?
数据的第一行有三个整数,n,m,k,分别表示城市数,航线数和免费乘坐次数。
第二行有两个整数,s,t,分别表示他们出行的起点城市编号和终点城市编号。(0<=s,t<n)
接下来有m行,每行三个整数,a,b,c,表示存在一种航线,能从城市a到达城市b,或从城市b到达城市a,价格为c。(0<=a,b<n,a与b不相等,0<=c<=1000)
只有一行,包含一个整数,为最少花费。
Sample Input
5 6 1 0 4 0 1 5 1 2 5 2 3 5 3 4 5 2 3 3 0 2 100
Sample Output
8
对于30%的数据,2<=n<=50,1<=m<=300,k=0;
对于50%的数据,2<=n<=600,1<=m<=6000,0<=k<=1;
对于100%的数据,2<=n<=10000,1<=m<=50000,0<=k<=10.
#include <iostream> #include <queue> #include <cstring> #include <algorithm> #include <cstdio> using namespace std; const int maxn = 1e6+1000; const int maxm = 1e7+10; const int INF = 0x3f3f3f3f; int head[maxn],d[maxn],vis[maxn]; int n,m,k; struct node { int to,w,next; }eg[maxm]; int cnt=0; void add(int u,int v,int w) { eg[cnt].to=v; eg[cnt].w=w; eg[cnt].next=head[u]; head[u]=cnt++; } typedef pair<int , int> P; void dijkstra(int s) { priority_queue<P,vector<P>,greater<P> >que; d[s]=0; que.push(P(0,s)); while(!que.empty()) { P p = que.top(); que.pop(); int v=p.second; if(d[v]<p.first) continue; for(int i=head[v];i!=-1;i=eg[i].next) { node e=eg[i]; if(e.w+d[v]<d[e.to]) { d[e.to]=e.w+d[v]; que.push(P(d[e.to],e.to)); } } } } int main() { memset(d,INF,sizeof(d)); memset(head,-1,sizeof(head)); cin>>n>>m>>k; int s,t; cin>>s>>t; for(int i=0;i<m;i++) { int a,b,c; cin>>a>>b>>c; for(int j=0;j<=k;j++) { add(a+j*n,b+j*n,c); add(b+j*n,a+j*n,c); if(j!=k) { add(a+j*n,b+(j+1)*n,0); add(b+j*n,a+(j+1)*n,0); } } } dijkstra(s); int MIN=INF; for(int i=0;i<=k;i++) { MIN=min(MIN,d[i*n+t]); } cout<<MIN<<endl; return 0; }