返回顶部

Manthan, Codefest 18 (rated, Div. 1 + Div. 2) D. Valid BFS? (排序,bfs)

  • 题意:有一颗树,你需要从根节点开始bfs,将搜到的点按顺序放入栈中,给你一个序列,你需要判断这个序列是否是某一种栈的情况.

  • 题解:存一下序列中每个值的位置,然后对于每个父亲结点,按照所存每个值的位置对儿子进行排序,最后跑bfs判断即可.

  • 代码:

    #include <bits/stdc++.h>
    #define ll long long
    #define fi first
    #define se second
    #define pb push_back
    #define me memset
    #define rep(a,b,c) for(int a=b;a<=c;++a)
    #define per(a,b,c) for(int a=b;a>=c;--a)
    const int N = 1e6 + 10;
    const int mod = 1e9 + 7;
    const int INF = 0x3f3f3f3f;
    using namespace std;
    typedef pair<int,int> PII;
    typedef pair<ll,ll> PLL;
    ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
    ll lcm(ll a,ll b) {return a/gcd(a,b)*b;}
     
    int n;
    vector<int> edge[N];
    int id[N];
    bool flag=true;
    queue<int> res;
    bool st[N];
     
    bool cmp(int x,int y){
    	return id[x]<id[y];
    }
     
    void bfs(){
    	queue<int> q;
    	q.push(1);
    	st[1]=true;
     
    	while(!q.empty()){
    		int cur=q.front();
    		q.pop();
    		int now=res.front();
    		res.pop();
    		if(cur!=now){
    			flag=false;
    			return;
    		}
    		for(auto w:edge[cur]){
    			if(!st[w])
    			q.push(w);	
    			st[w]=true;
    		}
    	}
    }
     
    int main() {
        ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    	cin>>n;
    	rep(i,1,n-1){
    		int u,v;
    		cin>>u>>v;
    		edge[u].pb(v);
    		edge[v].pb(u);
    	}
     
    	rep(i,1,n){
    		int x;
    		cin>>x;
    		res.push(x);
    		id[x]=i;
    	}
     
     
    	rep(i,1,n){
    		sort(edge[i].begin(),edge[i].end(),cmp);
    	}
     
    	bfs();
     
    	if(flag) cout<<"Yes\n";
    	else cout<<"No\n";
     
     
        return 0;
    }
    
posted @ 2021-05-25 18:00  _Kolibri  阅读(45)  评论(0)    收藏  举报