CF1037D Valid BFS?

该问题要求检查给定序列是否对应于从顶点1开始的给定树的某个有效BFS遍历。树是一个无向图,其中任意两个顶点之间都恰好有一条简单路径。给定树的节点数和边的细节以及要检查的序列,输出'Yes'如果序列符合BFS,否则输出'No'。

CF1037D Valid 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

(1n2105

) which denotes the number of nodes in the tree.

The following n1

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

) — 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 (1ain

) — 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
 
题意:给定一个bfs序列,看是不是合法的;
我们建立边的时候,可以按边端点出现的顺序先排序,这样才可能会出现题目所给的序列;
如果不一样,那么就是不合法的;
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<bitset>
#include<ctime>
#include<deque>
#include<stack>
#include<functional>
#include<sstream>
//#include<cctype>
//#pragma GCC optimize("O3")
using namespace std;
#define maxn 200005
#define inf 0x3f3f3f3f
#define INF 9999999999
#define rdint(x) scanf("%d",&x)
#define rdllt(x) scanf("%lld",&x)
#define rdult(x) scanf("%lu",&x)
#define rdlf(x) scanf("%lf",&x)
#define rdstr(x) scanf("%s",x)
typedef long long  ll;
typedef unsigned long long ull;
typedef unsigned int U;
#define ms(x) memset((x),0,sizeof(x))
const long long int mod = 1e9 + 7;
#define Mod 1000000000
#define sq(x) (x)*(x)
#define eps 1e-3
typedef pair<int, int> pii;
#define pi acos(-1.0)
const int N = 1005;
#define REP(i,n) for(int i=0;i<(n);i++)
typedef pair<int, int> pii;
inline ll rd() {
	ll x = 0;
	char c = getchar();
	bool f = false;
	while (!isdigit(c)) {
		if (c == '-') f = true;
		c = getchar();
	}
	while (isdigit(c)) {
		x = (x << 1) + (x << 3) + (c ^ 48);
		c = getchar();
	}
	return f ? -x : x;
}

ll gcd(ll a, ll b) {
	return b == 0 ? a : gcd(b, a%b);
}
ll sqr(ll x) { return x * x; }

/*ll ans;
ll exgcd(ll a, ll b, ll &x, ll &y) {
	if (!b) {
		x = 1; y = 0; return a;
	}
	ans = exgcd(b, a%b, x, y);
	ll t = x; x = y; y = t - a / b * y;
	return ans;
}
*/



ll qpow(ll a, ll b, ll c) {
	ll ans = 1;
	a = a % c;
	while (b) {
		if (b % 2)ans = ans * a%c;
		b /= 2; a = a * a%c;
	}
	return ans;
}

int vis[maxn];
int n;
int pre[maxn];
queue<int>q;
int a[maxn];
vector<int>vc[maxn];
int b[maxn];

bool cmp(int x, int y) {
	return pre[x] < pre[y];
}

void bfs() {
	q.push(1); vis[1] = 1;
	int cnt = 0;
	while (!q.empty()) {
		int u = q.front(); q.pop();
		b[++cnt] = u;
		for (int i = 0; i < vc[u].size(); i++) {
			if (vis[vc[u][i]])continue;
			int v = vc[u][i]; vis[v] = 1; q.push(v);
		}
	}
}

int main()
{
	//ios::sync_with_stdio(0);
	rdint(n);
	for (int i = 1; i < n; i++) {
		int u, v; rdint(u); rdint(v);
		vc[u].push_back(v); vc[v].push_back(u);
	}
	for (int i = 1; i <= n; i++) {
		rdint(a[i]); pre[a[i]] = i;
	}
	for (int i = 1; i <= n; i++) {
		sort(vc[i].begin(), vc[i].end(), cmp);
	}
	bfs();
	for (int i = 1; i <= n; i++) {
		if (a[i] != b[i]) { cout << "No" << endl; return 0; }
	}
	cout << "Yes" << endl;
    return 0;
}

 

posted @ 2018-11-16 11:06 NKDEWSM 阅读( ...) 评论( ...) 编辑 收藏
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define INF 0x7ffffff #define rep(i,s,t) for(register ll i = s;i <= t;++i) #define per(i,t,s) for(register ll i = t;i >= s;--i) const ll N = 25; struct node { ll x; ll y; ll rnk; bool operator < (const node& u) const { return rnk < u.rnk; } bool operator == (const node& u) const { return x == u.x && y == u.y && rnk == u.rnk; } }; ll n; ll m; ll ans = INF; ll dx[5] = {0,0,1,0,-1}; ll dy[5] = {0,1,0,-1,0}; char a[N][N] = {}; set <node> s; inline ll read() { ll x = 0; ll y = 1; char c = getchar(); while(c < '0' || c > '9') { if(c == '-') y = -y; c = getchar(); } while(c >= '0' && c <= '9') { x = (x << 3) + (x << 1) + (c ^ '0'); c = getchar(); } return x * y; } inline void write(ll x) { if(x < 0) { putchar('-'); write(-x); return; } if(x > 9) write(x / 10); putchar(x % 10 + '0'); } inline bool posfind(node tmp,set <node> cur) { for(register auto i : cur) if(i.x == tmp.x && i.y == tmp.y) return true; return false; } inline void bfs() { queue <pair<set <node>,ll> > q; q.push({s,0}); while(!q.empty()) { set <node> cur = q.front().first; ll stp = q.front().second; q.pop(); node head = *cur.begin(); if(a[head.x][head.y] == '@') { ans = stp; break; } ll cnt = 0; set <node> tmp; for(register auto i : cur) { cnt++; if(cnt == 1 || cnt == cur.size()) continue; tmp.insert({i.x,i.y,i.rnk + 1}); } rep(i,1,4) { ll nx = head.x + dx[i]; ll ny = head.y + dy[i]; node tmp1 = {nx,ny,1}; if(posfind(tmp1,tmp) || a[nx][ny] == '#' || nx < 1 || nx > n || ny < 1 || ny > m) continue; set <node> tmp2 = tmp; tmp2.insert(tmp1); q.push({tmp2,stp + 1}); } } } int main() { cin >> n >> m; rep(i,1,n) { rep(j,1,m) { cin >> a[i][j]; if(a[i][j] >= '0' && a[i][j] <= '9') s.insert({i,j,(ll)(a[i][j] - '0')}); } } bfs(); if(ans == INF) cout << -1; else cout << ans; return 0; }请针对以下问题优化上述代码的时间空间复杂度,极度精确保留源代码风格# CF225D Snake ## 题目描述 Let us remind you the rules of a very popular game called "Snake" (or sometimes "Boa", "Python" or "Worm"). The game field is represented by an $ n×m $ rectangular table. Some squares of the field are considered impassable (walls), all other squares of the fields are passable. You control a snake, the snake consists of segments. Each segment takes up exactly one passable square of the field, but any passable square contains at most one segment. All segments are indexed by integers from $ 1 $ to $ k $ , where $ k $ is the snake's length. The $ 1 $ -th segment is the head and the $ k $ -th segment is the tail. For any $ i $ ( $ 1<=i<k $ ), segments with indexes $ i $ and $ i+1 $ are located in the adjacent squares of the field, that is, these squares share a common side. One of the passable field squares contains an apple. The snake's aim is to reach the apple and eat it (that is, to position its head in the square with the apple). The snake moves throughout the game. During one move the snake can move its head to an adjacent field square. All other segments follow the head. That is, each segment number $ i $ $ (1<i<=k) $ moves to the square that has just had segment number $ i-1 $ . Consider that all segments including the head move simultaneously (see the second test sample). If the snake's head moves to an unpassable square or to the square, occupied by its other segment, the snake dies. That's why we will consider such moves unvalid. Your task is to determine the minimum number of valid moves that the snake needs to reach the apple. ## 输入格式 The first line contains two space-separated integers $ n $ and $ m $ ( $ 1<=n,m<=15 $ ) &mdash; the number of rows and columns of the game field. Next $ n $ lines describe the game field. Each of these lines contains $ m $ characters. Character "\#" represents a wall, "." is a passable square, "@" is an apple. The snake's first segment is represented by character "1", the second one segment &mdash; by character "2" and so on. The game field description doesn't contain any characters besides "\#', ".", "@" and digits (except 0). It is guaranteed that the described field is correct. It is guaranteed that the described field contains exactly one apple and exactly one snake, the snake's length is at least 3 and at most 9. ## 输出格式 Print a single integer to the output &mdash; the minimum number of moves needed to reach the apple. If the snake can't reach the apple, print -1. ## 输入输出样例 #1 ### 输入 #1 ``` 4 5 ##... ..1#@ 432#. ...#. ``` ### 输出 #1 ``` 4 ``` ## 输入输出样例 #2 ### 输入 #2 ``` 4 4 #78# .612 .543 ..@. ``` ### 输出 #2 ``` 6 ``` ## 输入输出样例 #3 ### 输入 #3 ``` 3 2 3@ 2# 1# ``` ### 输出 #3 ``` -1 ```
最新发布
07-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值