洛谷 P1346 电车(双端队列广搜)

发布时间:2022-07-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了洛谷 P1346 电车(双端队列广搜)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

传送门


解题思路

水题一个。 数据范围可以Floyd水过去。 但是苏轼告诉我们:

守其初心,始终不变。

屈原告诉我们:

虽九死其犹未悔。

所以我用了O(n+m)的搜索。 其实这叫做双端队列广搜,碰到边权为0放到队列首,边权为1放到队列尾。 但我没学过,就用了DFs+bfs结合体水过去了。

AC代码

#include<cstdio>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cmath>
#include<algorIThm>
#include<queue>
using namespace std;
const int maxn=105;
queue<int> q;
int n,s,t,vis[maxn],to[maxn][maxn],cnt[maxn],dis[maxn];
void dfs(int u){
	if(cnt[u]&&!vis[to[u][1]]){
		dis[to[u][1]]=dis[u];
		vis[to[u][1]]=1;
		dfs(to[u][1]);
	}
	for(int i=1;i<=cnt[u];i++){
		if(vis[to[u][i]]) continue;
		dis[to[u][i]]=dis[u]+1;
		vis[to[u][i]]=1;
		q.push(to[u][i]);
	}
}
int main(){
	ios::sync_with_stdio(false);
	memset(dis,-1,sizeof(dis));
	cin>>n>>s>>t;
	for(int i=1;i<=n;i++){
		cin>>cnt[i];
		for(int j=1;j<=cnt[i];j++) cin>>to[i][j];
	}
	q.push(s);
	vis[s]=1;
	dis[s]=0;
	while(!q.empty()){
		int u=q.front();
		q.pop();
		if(cnt[u]&amp;&!vis[to[u][1]]){
			dis[to[u][1]]=dis[u];
			vis[to[u][1]]=1;
			dfs(to[u][1]);
		}
		for(int i=1;i<=cnt[u];i++){
			if(vis[to[u][i]]) continue;
			dis[to[u][i]]=dis[u]+1;
			vis[to[u][i]]=1;
			q.push(to[u][i]);
		}
	}
	cout<<dis[t];
    return 0;
}

脚本宝典总结

以上是脚本宝典为你收集整理的洛谷 P1346 电车(双端队列广搜)全部内容,希望文章能够帮你解决洛谷 P1346 电车(双端队列广搜)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。