经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C » 查看文章
cf1037D. Valid BFS?(BFS?)
来源:cnblogs  作者:自为风月马前卒  时间:2018/10/8 9:14:59  对本文有异议

题意

题目链接

Sol

非常妙的一道题。。

可以这样想,在BFS序中较早出现的一定是先访问的,所以把每个点连出去的边按出现的前后顺序排个序

看一下按顺序遍历出来的序列与给出的是否相同就行了

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. const int MAXN = 2e5 + 10;
  4. inline int read() {
  5. char c = getchar(); int x = 0, f = 1;
  6. while(c < '0' || c > '9') {if(c == '-')f =- 1; c = getchar();}
  7. while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
  8. return x * f;
  9. }
  10. int N, a[MAXN], dfn[MAXN], tot, vis[MAXN], tim[MAXN];
  11. vector<int> v[MAXN];
  12. int comp(const int &x, const int &y) {
  13. return tim[x] < tim[y];
  14. }
  15. void BFS() {
  16. queue<int> q;
  17. q.push(1);
  18. while(!q.empty()) {
  19. int p = q.front(); q.pop();
  20. dfn[++tot] = p; vis[p] = 1;
  21. for(int i = 0, to; i < v[p].size(); i++) {
  22. if(!vis[(to = v[p][i])]) q.push(to);
  23. }
  24. }
  25. }
  26. main() {
  27. N = read();
  28. for(int i = 1; i <= N - 1; i++) {
  29. int x = read(), y = read();
  30. v[x].push_back(y); v[y].push_back(x);
  31. }
  32. for(int i = 1; i <= N; i++) tim[a[i] = read()] = i;
  33. for(int i = 1; i <= N; i++)
  34. sort(v[i].begin(), v[i].end(), comp);
  35. BFS();
  36. //for(int i = 1; i <= N; i++) printf("%d ", dfn[i]); puts("");
  37. for(int i = 1; i <= N; i++)
  38. if(dfn[i] != a[i]) {puts("No"); return 0;}
  39. puts("Yes");
  40. }
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号