Codefest 18 (rated, Div. 1 + Div. 2)-D-Valid BFSvj地址
题意:给你一段bfs序列,让你判断是否正确
思路:先给节点排序(很关键) 我们给每一个的点的邻接表按照给出的bfs序列排序,排好后, 我跑一下bfs,出来的序列应该是一样的,如果不一样,则是错误的。
代码
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstdlib>
#include <stack>
#include <vector>
#include <set>
#include <map>
#define INF 0x3f3f3f3f3f3f3f3f
#define FILL(a,b) (memset(a,b,sizeof(a)))
#define re register
#define lson rt<<1
#define rson rt<<1|1
#define lowbit(a) ((a)&-(a))
#define ios std::ios::sync_with_stdio(false);std::cin.tie(0);std::cout.tie(0);
#define fi first
#define rep(i,n) for(int i=0;(i)<(n);i++)
#define rep1(i,n) for(int i=1;(i)<=(n);i++)
#define se secondusing namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int > pii;
int dx[4]= {-1,1,0,0},dy[4]= {0,0,1,-1};
const ll mod=10001;
const ll N =6e5+10;
const double eps = 1e-4;
const double pi=acos(-1);
ll gcd(int a,int b){return !b?a:gcd(b,a%b);}
int dep[200005],n,a[200005],flag[200005],mark,id[200005];
vector<int>q[200005];
queue<int>qq;
bool comp(int x,int y)//关键的排序 函数
{if(id[x]<id[y])return 1;return 0;
}
int main(void)
{int x,y;scanf("%d",&n);for(int i=1;i<n;i++){scanf("%d%d",&x,&y);q[x].push_back(y);q[y].push_back(x);}for(int i=1;i<=n;i++)scanf("%d",&a[i]),id[a[i]]=i;//给他们排名,以便后面排名for(int i=1;i<=n;i++)sort(q[a[i]].begin(),q[a[i]].end(),comp);qq.push(1);flag[1]=1; int cnt=1;while(qq.empty()==0){int tmp=qq.front();qq.pop();if(a[cnt]!=tmp){mark=1;break;}for(int i=0;i<q[tmp].size();i++){if(flag[q[tmp][i]]==0)qq.push(q[tmp][i]),flag[q[tmp][i]]=1;}cnt++;}if(mark) printf("No\n");else printf("Yes\n");return 0;
}