2024/3/26

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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值