1. 程式人生 > >D. Valid BFS? (BFS)

D. Valid BFS? (BFS)

The BFS algorithm is defined as follows.

  1. Consider an undirected graph with vertices numbered from 1

to n. Initialize q as a new queue containing only vertex 1, mark the vertex 1

  • as used.
  • Extract a vertex v
  • from the head of the queue q
  • .
  • Print the index of vertex v
  • .
  • Iterate in arbitrary order through all such vertices u
  • that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q
    1. .
    2. If the queue is not empty, continue from step 2.
    3. Otherwise finish.

    Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.

    In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1

    . The tree is an undirected graph, such that there is exactly one simple path between any two vertices.

    Input

    The first line contains a single integer n

    (1≤n≤2⋅105

    ) which denotes the number of nodes in the tree.

    The following n−1

    lines describe the edges of the tree. Each of them contains two integers x and y (1≤x,y≤n

    ) — the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree.

    The last line contains n

    distinct integers a1,a2,…,an (1≤ai≤n

    ) — the sequence to check.

    Output

    Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise.

    You can print each letter in any case (upper or lower).

    Examples

    Input

    Copy

    4
    1 2
    1 3
    2 4
    1 2 3 4
    
    Output

    Copy

    Yes
    Input

    Copy

    4
    1 2
    1 3
    2 4
    1 2 4 3
    
    Output

    Copy

    No

    Note

    Both sample tests have the same tree in them.

    In this tree, there are two valid BFS orderings:

    • 1,2,3,4
  • ,
  • 1,3,2,4
  • .

The ordering 1,2,4,3

doesn't correspond to any valid BFS order.

題意:給了一顆n節點,n-1條邊的樹,進行BFS遍歷,問遍歷順序是否可能是所給陣列的順序

思路:先對構樹的鄰接表通過序列中的數的次序進行排序,再直接對樹bfs,看其結果是否相同即可

#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int N = 2e5+5;
vector<int>G[N];
int arr[N],id[N];
bool vis[N];
void init(){
	memset(vis,0,sizeof(vis));
	for(int i=0;i<N;i++)
		G[i].clear();
}
bool cmp(int a,int b){
	return id[a]<id[b];
}
int BFS(){
	vis[1]-=1;
	int cnt=1;
	queue<int>p;
	p.push(1);
	while(!p.empty()){
		int u=p.front();
		p.pop();
		if(arr[cnt]!=u) return 0;
		else cnt++;
		for(int i=0;i<G[u].size();i++){
			if(!vis[G[u][i]]){
				vis[G[u][i]]=1;
				p.push(G[u][i]);
			}
		}
	}
	return 1;
}
int main(){
	int n;
	while(~scanf("%d",&n)){
		init();
		for(int i=1;i<n;i++){
			int u,v;
			scanf("%d%d",&u,&v);
			G[u].push_back(v);
			G[v].push_back(u);
		}
		for(int i=1;i<=n;i++){
			scanf("%d",&arr[i]);
			id[arr[i]]=i;
		}
		for(int i=1;i<=n;i++)
			sort(G[i].begin(),G[i].end(),cmp);
		if(BFS()) printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}

相關推薦

D. Valid BFS? BFS

The BFS algorithm is defined as follows. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new queue con

Bubble Cup 11 - Finals [Online Mirror, Div. 1] D. Interstellar battle bfs序 + 期望 + 樹狀陣列

題目連結:http://codeforces.com/contest/1045/problem/D 題目大意:有一棵n個結點的樹,編號為 i 的結點都有一個屬性p[i],表示 i 這個結點有p[i]的概率會消失。接下來有q次操作,每次操作會把結點u的p[u]值修改為一個新的值np,在每次修改之後

水池數目 ~ BFS

                                          &nb

圖的廣度優先搜尋BFSC++

用於實驗的圖: r->2; 1->s; t->3; u->4; v->5; w->6; x->7; y->8 這裡對連結串列的結構進行了改編: /*

求樹層數&深搜BFS模板

本例子中是二叉樹,如果不是二叉樹的話用vector會比較好  #include <iostream> #include <algorithm> #include <c

BFS:廣度優先搜尋的基本思想

      廣度優先搜尋BFS(Breadth First Search)也稱為寬度優先搜尋,它是一種先生成的結點先擴充套件的策略。       在廣度優先搜尋演算法中,解答樹上結點的擴充套件是按它們在樹中的層次進行的。首先生成第一層結點,同時檢查

BFS:雙向廣度優先搜尋

      所謂雙向廣度搜索指的是搜尋沿兩個方向同時進行:(1)正向搜尋:從初始結點向目標結點方向搜尋;(2)逆向搜尋:從目標結點向初始結點方向搜尋;當兩個方向的搜尋生成同一子結點時終止此搜尋過程。       廣度雙向搜尋通常有兩種方法:(1)兩

LeetCode:20. Valid ParenthesesEasy

實現 16px parent 數字 字符串 java 給定 遇到 ray 1. 原題鏈接 https://leetcode.com/problems/valid-parentheses/description/ 2. 題目要求 給定一個字符串s,s只包含‘(‘, ‘)‘,

附錄D——自動微分Autodiff

cal war 意思 出了 三種 依賴 虛表 ever 我想 本文介紹了五種微分方式,最後兩種才是自動微分。 前兩種方法求出了原函數對應的導函數,後三種方法只是求出了某一點的導數。 假設原函數是$f(x,y) = x^2y + y +2$,需要求其偏導數$\frac{\pa

牛客網暑期ACM多校訓練營第一場D Two Graphs

scanf fir fde pre map 部分 一場 rst using 題意 給兩個圖G1和G2,求G2的子圖中與G1同構的數目。 分析 首先n=8,那麽n!的算法問題不大。枚舉G1的每個點,在G2中找同構的頂點序列。需要註意的是G1存在自同構的情況,所以對G1本

Valid Parentheses python

列表 所有 感覺 後綴 如果 ali ima 表達式 分享 這道題主要用棧來實現的。什麽是棧呢,參照書上的後綴表達式的例子談談自己的理解,棧最明顯的特征是先進後出。所以可以有效的結合題目中 ()對匹配問題,可以把從列表中獲取的符號先存到棧中。 首先建個空列表用於映射棧中元素

AtCoder Regular Contest 103 Problem D Robot Arms 構造

https con 進制 bsp code lap 直接 coder efi 題目鏈接 Problem D 給定$n$個坐標,然後讓你構造一個長度為$m$的序列, 然後給每個坐標規定一個長度為$m$的序列,ULRD中的一個,意思是走的方向, 每次從原點出發按照這個序

Codeforces Round #513 D - Social Circles貪心

std typedef ORC using codeforce names nbsp 代碼 code 題目大意:有n(n≤105)個人排成一圈,第i個人要求自己左邊空出li個座位,右邊空出ri(li,ri≤109)個座位。問最少需要安排多少個座位。思路:一開始先假設每

Codeforces Round #514 (Div. 2) D Nature Reserve二分

題意:一個圓與X軸相切,問最小的半徑,使得圓包含所有給定的點。 思路:因為圓是y軸xi相切的,設半徑為R,所以圓心肯定在y=R上,以每個點為圓心作半徑為R的圓與y=R交於l和r,那麼要求的圓的圓心肯定在這個區間,那麼列舉每一個點的l和r,這樣就可以一直縮小l和r的範圍,最後如果l<r,也就

D-Bus學習 Method的收發小例子

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

D-Bus學習 Signal的收發小例子

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

Codeforces Round #388 (Div. 2)D. Leaving Auctionset

題意:有有許多人蔘加拍賣,問當假定某些人不參加的時候剩餘的人當中誰是最終的贏家,輸出他的編號和最終競價,注:每個人都不能和自己競價,即若某人連續競價兩次,以第一次價格為準。輸入資料保證競價遞增。 思路: 我們只要把每個人競價的最大值存起來, 並且把每個人的所有競價維護在一個有序陣列(方便二分

【2008-2009 ICPC NEERC D】Deposits暴力

題目連結 題意: 給你n個數a[i],m個數b[i],求出有幾對數滿足a[i]能整除b[i]。  題解: 直接暴力,先將第一組數存入a陣列,第二組數存入b陣列,然後在第二組數中遍歷它整數倍的數(在10^6之內),其次相加求和即可。 #include<bits/stdc++.h&

Codeforces Round #162 (Div. 2): D. Good SequencesDP

  題意: 給你n個數字,求出最長相鄰不互質子序列   思路: 設dp[i]表示以第i個數字結尾的最長子序列長度 考慮不互質的兩個數(x,y),它們一定存在相同的質因子 在DP過程中求出R[p]表示p的倍數當前最晚出現的位置,那麼就可以得出d

【LeetCode】36. Valid SudokuC++

地址:https://leetcode.com/problems/valid-sudoku/ 題目: Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated accord