(bfs无边权最短路)Catch That Cow

文章讨论了如何使用BFS解决边权为1的最短路问题,对比了DFS的不适合性,并提供了BFS的代码实现。同时提到了适用于1e5规模问题的优化DP解法,以及类似问题的应用场景。
摘要由CSDN通过智能技术生成

Problem - 2717 (hdu.edu.cn)

我的思路:

当时想的是dp,dfs(深度优先做不了,求解要把所有可能性都遍历完,复杂度不合适)啥的,完全没想到是bfs的最短路。

题解思路:

每次行动耗费1时间,问到达某点的最短时间。
那就是边权为1的最短路问题了。

代码:

//边权为1的bfs最短路,新情景,每次移动时间耗费+1
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
const int N = 1e5 + 10;
int n,k;

queue<int> q;
int bfs(){
    vector<int> dis(N+1,-1);
	q.push(n);
	dis[n] = 0;
	while(q.size()){
		int t = q.front();
		q.pop();
		for(auto i : vector<int>{1,-1,t}){
			int x = t + i;
			if(x < 0 || x >= N ) continue;
			if(dis[x] != -1) continue;
			q.push(x);
			dis[x] = dis[t] + 1;
			if(x == k) return dis[x];
		}
	}
}
int main(){
	
	while(cin >> n >> k){
		while(q.size()) q.pop(); 
		if(n >= k) cout << n-k << endl;
		else cout << bfs() << endl;
	}
	return 0;
}

套路:

为什么不用dp?1e5的复杂度,不合适。就算一维dp也是需要两重循环的
因为我不会.
附上评论区大哥的dp解法:
__min应该是微软的stdlib.h中的宏,不需要std就能用.
暂时不搞dp,所以就没细看直接贴这了.

#include<bits/stdc++.h>
const int N=2e5+10;
 
int dp[N],n,m;
 
int main(){
	while(~scanf("%d%d",&n,&m)){
 
        for(int i=0;i<=n;i++) dp[i]=n-i;
        for(int i=n+1;i<=m;i++) 
            dp[i]=__min(dp[i-1],dp[(i+1)/2]+i%2)+1;
 
        printf("%d\n",dp[m]);
    }
}

1)bfs无边权最短路

前提条件:求最短路,无边权图。
情景:

1)Catch That Cow

  • Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
  • Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
  • 每次移动,时间加一。时间也可以当作是一种距离。
    2)nearest Black Vertex
  • At least one vertex is painted black.
  • For every i=1,2,…,K, the following holds:
    • the minimum distance between vertex pi​ and a vertex painted black is exactly di​.
    • 把不符合要求的棋子标记为白,然后找出每个白棋子距离最近的黑棋子的距离。

都是需要找一个边权为1的图力点之间的最短距离。

应对:

1)求一个点到n个点的最短路:

把这个点当作起点。

2) 求1种点到距离另一种点的最短距离

把其中一种点全部推入循环,然后dis设置为0.n个起点。

#bfs无边权最短路

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值