题意:n个点,m条边,起点s,终点t,可以最多选k条边免费,问你s到t的一共最小花费多少。
题解:多层图最短路板子题。dis[i][j]表示起点s到点i最多选j条边的最小花费。优先队列q(u,dist,d)分别表示点i,s到i的最小花费,目前已用d条免费边。松弛的时候考虑这条边要不要变成免费边(当然,变成免费边的前提是d+1<=k),如果不变成免费边,dis[v][d] = dis[u][d] + w,q.push({v,dis[v][d],d});如果变成免费边,dis[v][d+1] = dis[u][d],q.push({v,dis[v][d+1],d+1})。最后从dis[t][1]到dis[t][k]里取个min。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 2005;
const int INF = 0x3f3f3f3f;
int n,m,k,s,t,tot;
int dis[maxn][maxn],head[maxn];
struct edge
{
int to,next,w;
}a[maxn];
struct node
{
int u,dist,d;
bool operator < (const node &t) const {
return dist > t.dist;
}
};
void add(int u,int v,int w)
{
a[tot].to = v;
a[tot].next = head[u];
a[tot].w = w;
head[u] = tot++;
}
priority_queue<node>q;
void dij(int s)
{
memset(dis,0x3f,sizeof(dis));
dis[s][0] = 0;
q.push({s,0,0});
while(!q.empty())
{
int u = q.top().u;
int dist = q.top().dist;
int d = q.top().d;
q.pop();
if(dis[u][d] < dist)
continue;
for(int i=head[u]; i!=-1; i=a[i].next)
{
int v = a[i].to;
int w = a[i].w;
if(dis[v][d] > dis[u][d] + w)
{
dis[v][d] = dis[u][d] + w;
q.push({v,dis[v][d],d});
}
if(d+1<=k && dis[v][d+1] > dis[u][d])
{
dis[v][d+1] = dis[u][d];
q.push({v,dis[v][d+1],d+1});
}
}
}
}
int main()
{
scanf("%d%d%d%d%d",&n,&m,&s,&t,&k);
memset(head,-1,sizeof(head));
for(int i=1; i<=m; i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);
add(v,u,w);
}
dij(s);
int ans = INF;
for(int i=0; i<=k; i++)
{
ans = min(ans,dis[t][i]);
}
printf("%d",ans);
}