(J)free dp+bfs
题目描述
Your are given an undirect connected graph.Every edge has a cost to pass.You should choose a path from S to T and you need to pay for all the edges in your path. However, you can choose at most k edges in the graph and change their costs to zero in the beginning. Please answer the minimal total cost you need to pay.
输入描述:
The first line contains five integers n,m,S,T,K.
For each of the following m lines, there are three integers a,b,l, meaning there is an edge that costs l between a and b.
n is the number of nodes and m is the number of edges.
输出描述:
An integer meaning the minimal total cost.
示例1:
输入
3 2 1 3 1
1 2 1
2 3 2
输出
1
备注:
Multiple edges and self loops are allowed.
链接:https://ac.nowcoder.com/acm/contest/884/J
题意
给两个点(s,t),求出从s走到t,至多免费走k条边的最短距离。
分析
由于m的范围比较小,可以考虑对每个点已经走了几条免费路花费最小值进行dp。以s为起点,对相邻的点动态转移。
假设现在的点为a,已经走过的免费路的个数为c,它有个相邻点b。
1.不选择将a->b的路设为免费路,如果dp[b][c]>dp[a][c]+mp[a][b],则可以转移,dp[b][c]=dp[a][c]+mp[a][b]
2.选择将a->b的路设为免费路,那么显然要满足c<k,如果dp[b][c+1]>dp[a][c],则可以转移,dp[b][c+1]=dp[a][c];
(dp[i][j]表示走到位置i已经走了j条免费路的最小花费,mp[i][j]记录i,j之间的距离)
那么我们如何在图上实现转移,可以用bfs,以s点为起点,对于每个可以转移到的情况压入队列中。
题目中还强调有重边和自环,这个容易处理,用二维数组记录每两个点之间的最小值,自环距离即为0。
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 1e9;
const int N = 1e3+5;
vector<int>v[N];
int mp[N][N];
int n,m,s,t,k,a,b,c;
int dp[N][N];
struct node{
int pos,numk;//pos为当前的位置,numk为已经走的免费路的条数
}cur,ne;
void bfs()
{
queue<node>q;
while(!q.empty())
q.pop();
cur.pos=s;
cur.numk=0;
q.push(cur);//将s压入队列
while(!q.empty())
{
cur=q.front();
q.pop();
for(int i=0;i<v[cur.pos].size();i++)//访问相邻点
{
int a=cur.pos,b=cur.numk,c=v[a][i];
// cout<<a<<" "<<b<<" "<<c<<endl;
// cout<<dp[c][b]<<" "<<dp[a][b]<<" "<<mp[a][c]<<endl;
if(dp[c][b]>dp[a][b]+mp[a][c])
{
dp[c][b]=dp[a][b]+mp[a][c];
ne.pos=c;
ne.numk=b;
q.push(ne);
}
if(b<k&&dp[c][b+1]>dp[a][b])
{
dp[c][b+1]=dp[a][b];
ne.pos=c;
ne.numk=b+1;
q.push(ne);
}
}
}
}
int main()
{
scanf("%d %d %d %d %d",&n,&m,&s,&t,&k);
for(int i=0;i<=n;i++)//初始化dp和mp
{
for(int j=0;j<=n;j++)//记得j要从0开始,不然dp[i][0]会出事
{
if(i==j)
mp[i][j]=0;
else
mp[i][j]=INF;
if(i==s)
dp[i][j]=0;
else
dp[i][j]=INF;
}
}
for(int i=1;i<=m;i++)
{
scanf("%d %d %d",&a,&b,&c);
if(a==b)
continue;
if(mp[a][b]==INF)
{
v[a].push_back(b);
v[b].push_back(a);
}
if(mp[a][b]>c)//记录最短的边
mp[a][b]=mp[b][a]=c;
}
int mi=INF;
bfs();
for(int i=0;i<=k;i++)
mi=min(mi,dp[t][i]);
printf("%d\n",mi);
}