参考博客: https://blog.csdn.net/qq_40079933/article/details/79394429
题目是说有k条线路是可以免费的,同时这k条线路未定。
那么我们可以建立一个k+1层的图,使得s->t点中有一条路线一定是有k次免费的。
所以,难点在于建图,跑单源最短路。
#include"stdio.h"
#include"string.h"
#include"queue"
#include"algorithm"
using namespace std;
const int INF = 1e9 + 7;
const int N = 20010,M = 3000100;
typedef pair<int,int> PII;
int head[13 * N],ver[M],edge[M],Next[M],tot;
int n,m,k,s,t;
int dist[N * 13];
int vis[N * 13];
void add(int u,int v,int w)
{
ver[++ tot] = v; edge[tot] = w;
Next[tot] = head[u]; head[u] = tot;
}
struct com{
bool operator()(const PII &t1,const PII &t2)
{
return t1.second > t2.second ;
}
};
void dfs()
{
priority_queue<PII,vector<PII>,com> Q;
Q.push({s,0});
for(int i = 0; i <= n * k + n; i ++) dist[i] = INF;
dist[s] = 0;
while(!Q.empty())
{
PII p = Q.top(); Q.pop();
int u = p.first;
int w = p.second;
if(dist[u] != w) continue;
if(vis[u] == 1) continue;
vis[u] = 1;
for(int i = head[u]; i; i = Next[i])
{
int v = ver[i];
int val = edge[i];
if(dist[v] > w + val)
{
dist[v] = w + val;
Q.push({v,dist[v]});
}
}
}
}
int main()
{
scanf("%d%d%d",&n,&m,&k);
scanf("%d%d",&s,&t);
s ++;t ++;
for(int i = 1; i <= m; i ++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
a ++; b ++;
for(int j = 0; j <= k; j ++)
{
add(j * n + a,j * n + b,c);
add(j * n + b,j * n + a,c);
if(j < k)
{
add(j * n + a,(j + 1) * n + b,0);
add(j * n + b,(j + 1) * n + a,0);
}
}
}
dfs();
int ans = INF;
for(int i = 0; i <= k; i ++)
ans = min(ans,dist[i * n + t]);
printf("%d\n",ans);
}