The general idea of the question: There is a graph with n points and n edges. There are two people A and B in Xi'an, respectively located at points a/b. In each round, the two people start moving to adjacent points at the same time. Is it possible for B to always be at odds with each other? A confluence
3<=n<=2e5;1<=a,b<=n
Idea: If they are to never merge, then they must eventually be in a ring, and the number of edges is equal to the number of points, which means that there is and is only one ring in the graph, then B only needs to arrive at this ring before A.
So we first run a dfs to find all the points on the ring, then use b as the starting point to find which point on the ring is closest to b, and which point it is, and then run bfs starting from a to find the distance from b to that point. If b is on the ring from the beginning and is closer to that point than a, there will be a winning strategy. At the same time, if ab overlaps, there will be no winning strategy.
//#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;
}