题目大意:有一个n个点的图,有n条边,西安有两个人A,B分别位于点a/b,每轮两个人同时开始向相邻点移动,问B有没有可能永远不和A汇合
3<=n<=2e5;1<=a,b<=n
思路:如果要永远不汇合,那么他们最终肯定在一个环里,而边的数量等于点数,说明图中有且只有一个环,那么B只要比A先到这个环即可。
所以我们先跑一个dfs找到所有环上的点,然后再以b为起点,找到b距离环上的哪个点最近,且是哪个点,然后再从a出发跑bfs找到b到那个点的距离,如果b一开始就在环上且到那个点比a更近,就有必胜策略,同时如果ab重合一定没有必胜策略
//#include<__msvc_all_public_headers.hpp>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1e9 + 7;
const int N = 2e5 + 5;
int head[N];
int cnt = 0;
int n;
struct Edge
{
int v, next;
}e[N * 2];
void addedge(int u, int v)
{
e[++cnt].v = v;
e[cnt].next = head[u];
head[u] = cnt;
}
bool vis[N];
bool incycle[N];
bool flag = 0;
void init()
{
cnt = 0;
for (int i = 1; i <= n; i++)
{
flag = 0;
head[i] = -1;
vis[i] = 0;
incycle[i] = 0;
}
}
int path[N];
void find_cycle(int u, int fa)
{//标记哪些点在环上
vis[u] = 1;
for (int i = head[u]; ~i; i = e[i].next)
{
int v = e[i].v;
if (v == fa || flag)
continue;
if (vis[v])
{//出现访问过的点,说明这里成环
flag = 1;
int now = u;
while (now != v)
{
incycle[now] = 1;
now = path[now];
}
incycle[now] = 1;
return;
}
path[v] = u;//记录父节点
find_cycle(v, u);
}
}
void solve()
{
int a, b;
cin >> n >> a >> b;
init();
for (int i = 1; i <= n; i++)
{
int u, v;
cin >> u >> v;
addedge(u, v);
addedge(v, u);
}
find_cycle(1, 0);
queue<pair<int, int>>q;
q.push({ b,0 });
int dis1 = -1;
int poi;
for(int i = 1; i <= n; i++)
{
vis[i] = 0;
}
vis[b] = 1;
while (!q.empty())
{//以b为起点
int u = q.front().first;
int d = q.front().second;
if (incycle[u])
{//找到最近的在环上的点
poi = u;
dis1 = d;
break;
}
q.pop();
for (int i = head[u]; ~i; i = e[i].next)
{
int v = e[i].v;
if (vis[v])
continue;
vis[v] = 1;
q.push({ v, d + 1 });
}
}
queue<pair<int, int>>q2;
q2.push({ a,0 });
int dis2 = -1;
for (int i = 1; i <= n; i++)
{
vis[i] = 0;
}
vis[a] = 1;
while (!q2.empty())
{//以a为起点
int u = q2.front().first;
int d = q2.front().second;
if (u == poi)
{//找到b要去的环上的点
dis2 = d;
break;
}
q2.pop();
for (int i = head[u]; ~i; i = e[i].next)
{
int v = e[i].v;
if (vis[v])
continue;
vis[v] = 1;
q2.push({ v, d + 1 });
}
}
cout << ((( dis1 == 0 || dis2 > dis1) && a != b) ? "YES" : "NO") << endl;//b先到且b和a起始不重合
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--)
{
solve();
}
return 0;
}