Codefest 18 (rated, Div. 1 + Div. 2), problem: (D) Valid BFS? 【模拟bfs】

The meaning of problems

Given a tree, and then give you a sequence, this sequence is not asking the tree feasible bfs order

Thinking

Direct simulation again bfs.

Firstly papyrifera adjacency table is sorted by the order number in the sequence, and then directly to the BFS tree, to see whether the result can be the same

code

#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
const int maxn=2e5+5;
int n;
vector<int> G[maxn];
int idx[maxn],a[maxn];
int vis[maxn];
queue<int> q;
bool bfs(){
    q.push(1);
    vis[1]=1;
    int k=1;
    while(!q.empty()){
        int now=q.front();
        q.pop();
        if(now!=a[k])
            return 0;
        else
            k++;
        for(auto v:G[now]){
            if(v==now) continue;
            if(!vis[v]){
                vis[v]=1;
                q.push(v);
            }
        }
    }
    return 1;
}
bool cmp(int a,int b){
    return idx[a]<idx[b];
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    for(int i=0;i<n-1;i++){
        int u,v;
        cin>>u>>v;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    for(int i=1;i<=n;i++){
        cin>>a[i];
        idx[a[i]]=i;
    }
    for(int i=1;i<=n;i++)
        sort(G[i].begin(),G[i].end(),cmp);
    if(bfs())
        cout<<"Yes"<<endl;
    else
        cout<<"No"<<endl;
    return 0;
}
学如逆水行舟,不进则退
Published 424 original articles · won praise 987 · Views 140,000 +

Guess you like

Origin blog.csdn.net/weixin_42429718/article/details/104116426