Gym 101149L Right Build[BFS]

题意:给了一个可能有环的n+1(<=2e5)个点m(<=2e5)条边的有向图,问从点 0 到 a, b 的总距离最短是多少


思路:我们可以先预处理出n到每个点的距离,然后再处理出a和b到每个点的距离,最后枚举每个点求出最小的答案就行了,这里处理只能用BFS,DFS会TLE,还有一个坑点就是点的标号是(0~n)


下面是代码部分:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<cstring>
#include<string>
#include<vector>
#include<unordered_set>
#include<unordered_map>
#include<cmath>
using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;

const int MAXN = 200005;
const int MAXM = 1000005;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const double FINF = 1e30;

vector<int>G[MAXN], RG[MAXN];
int cnt[3][MAXN];
bool vis[MAXN];
struct node
{
	int dep, v;
	node(){}
	node(int _dep,int _v):v(_v),dep(_dep){}
};
void bfs(int ty,int u)
{
	memset(vis, 0, sizeof(vis));
	queue<node>qe;
	qe.push(node(0, u));
	vis[u] = 1;
	while (!qe.empty())
	{
		node now = qe.front(); qe.pop();
		cnt[ty][now.v] = now.dep;
		if (ty == 0)
		{
			for (int i = 0; i < G[now.v].size(); ++i)
			{
				if (vis[G[now.v][i]] == 0) 
				{
					vis[G[now.v][i]] = 1;
					qe.push(node(now.dep + 1, G[now.v][i]));
				}
			}
		}
		else
		{
			for (int i = 0; i < RG[now.v].size(); ++i)
			{
				if (vis[RG[now.v][i]] == 0)
				{
					vis[RG[now.v][i]] = 1;
					qe.push(node(now.dep + 1, RG[now.v][i]));
				}
			}
		}

	}
}
int main()
{
	int n, m, a, b, x, y;
	scanf("%d%d%d%d", &n, &m, &a, &b);
	memset(cnt, INF, sizeof(cnt));
	for (int i = 0; i < m; ++i)
	{
		scanf("%d%d", &x, &y);
		G[x].push_back(y);
		RG[y].push_back(x);
	}
	bfs(0, 0); bfs(1, a); bfs(2, b);
	int ans = INF;
	for (int i = 0; i <= n; ++i)
	{
		if (cnt[0][i] + cnt[1][i] + cnt[2][i] < ans)
		{
			ans = cnt[0][i] + cnt[1][i] + cnt[2][i];
		}
	}
	printf("%d\n", ans);
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值