2019牛客多校第四场(J)dp+bfs

1 篇文章 0 订阅
(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);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值