1037D - Valid BFS - CodeForces Solution


dfs and similar graphs shortest paths trees *1700

Please click on ads to support us..

Python Code:

import sys;input = sys.stdin.readline
from collections import deque

I =  lambda :int(input())
L = lambda :list(map(int, input().split()))
T = lambda :map(int, input().split())

n = I()
graph = [set() for i in range(n+1)]
for i in range(n-1):
    a, b = T()
    graph[a].add(b)
    graph[b].add(a)
order = L()

q = deque([1])
v = [0]*(n+1)
size = [0]*(n+1)
v[1] = 1

while q:
    node = q.popleft()
    for nbr in graph[node]:
        if v[nbr] == 0:
            q.append(nbr)
            v[nbr] = 1
            size[node] += 1

j = 1
for index in range(n):
    node = order[index]
    for k in range(size[node]):
        if j<=n:
            child = order[j]
            if child not in graph[node]:
                print("No")
                sys.exit()
            j += 1
        else:
            print("No")
            sys.exit()

print("Yes")

C++ Code:

#include <bits/stdc++.h>
using namespace std;

const int N = 2e5 + 10;
vector<int> g[N];
queue<int> q;
int a[N], par[N], pos[N];
bool mark[N];

void bfs(int x) {
	q.push(x);
	mark[x] = true;
	par[x] = 0;
	while (!q.empty()) {
		int u = q.front();
		q.pop();
		for (int v: g[u]) {
			if (!mark[v]) {
				q.push(v);
				mark[v] = true;
				par[v] = u;
			}
		}
	}
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	
	int n;
	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 = 0; i < n; i++) {
		cin >> a[i];
		pos[a[i]] = i;
	}
	bfs(1);
	int pnt = 0, cp = 0, mxpos = 0;
	for (int i = 0; i < n; i++) {
		cp = par[a[i]];
		while (i < n && par[a[i]] == cp) {
			i++;
		}
		i--;
		int tmp = i - pnt;
		pnt = i;
		int sz = g[cp].size();
		if (cp != 1 && cp != 0)
			sz--;
		if (tmp != sz || pos[cp] < mxpos) {
			cout << "No" << '\n';
			exit(0);
		}
		mxpos = pos[cp];
	}	
	cout << "Yes" << '\n';
}


Comments

Submit
0 Comments
More Questions

1450A - Avoid Trygub
327A - Flipping Game
411A - Password Check
1520C - Not Adjacent Matrix
1538B - Friends and Candies
580A - Kefa and First Steps
1038B - Non-Coprime Partition
43A - Football
50A - Domino piling
479A - Expression
1480A - Yet Another String Game
1216C - White Sheet
1648A - Weird Sum
427A - Police Recruits
535A - Tavas and Nafas
581A - Vasya the Hipster
1537B - Bad Boy
1406B - Maximum Product
507B - Amr and Pins
379A - New Year Candles
1154A - Restoring Three Numbers
750A - New Year and Hurry
705A - Hulk
492B - Vanya and Lanterns
1374C - Move Brackets
1476A - K-divisible Sum
1333A - Little Artem
432D - Prefixes and Suffixes
486A - Calculating Function
1373B - 01 Game