题意:给了一个可能有环的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);
}