H. Mad City
原题链接:Problem - 1873H - Codeforces
题目大意:
n个顶点,n条边的图。
题目做法:
AC代码:
#include<bits/stdc++.h>
#define pb(element) push_back(element)
#define fast ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
//#define int long long
using namespace std;
const int mode = 1e9 + 7;
const int maxn = 2e5 + 10;
vector<int> node[maxn];
int sdist[2][maxn], n;
bool isin[maxn];
bool vis[maxn],flag = 0, ended = 0;
void dfs1(int now, int from){
for(auto it:node[now]){
if(it == from) continue;
if(vis[it] == 1){
isin[it] = 1;
flag = 1;
return ;
}
vis[it] = 1;
dfs1(it, now);
vis[it] = 0;
if(flag == 1 && ended == 0){
if(isin[it] == 1) ended = 1;
isin[it] = 1;
return ;
}
}
}
void dijkstra(int ini, int num){
sdist[num][ini] = 0;
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > q;
for(int i = 1; i <= n; i++){
vis[i] = 0;
}
q.push(make_pair(0,ini));
while(!q.empty()){
pair<int,int> x = q.top();
q.pop();
int u = x.second;
if(vis[u]) continue;
vis[u] = 1;
for(auto it:node[u]){
int tv = it;
if(sdist[num][tv] > sdist[num][u] + 1){
sdist[num][tv] = sdist[num][u] + 1;
q.push(make_pair(sdist[num][tv], tv));
}
}
}
}
void init(int n){
for(int i = 1; i <= n; i++){
sdist[1][i] = 1e9 + 10;
sdist[0][i] = 1e9 + 10;
node[i].clear();
vis[i] = 0;
isin[i] = 0;
}
flag = 0;
ended = 0;
}
void solve(){
int a, b, t1, t2, tminn = 1e9 + 10, minps = 0;
cin >> n >> a >> b;
init(n);
for(int i = 0; i < n; i++){
cin >> t1 >> t2;
node[t1].pb(t2);
node[t2].pb(t1);
}
dfs1(1, -1);
dijkstra(b, 0);
dijkstra(a, 1);
for(int i = 1; i <= n; i++){
if(isin[i] == 1){
if(tminn > sdist[0][i]){
tminn = sdist[0][i];
minps = i;
}
}
}
if(sdist[0][minps] < sdist[1][minps]) cout << "YES" << '\n';
else cout << "NO" << '\n';
}
signed main(){
fast int casen = 1;
cin >> casen;
while(casen--) solve();
}