BestCoder Round #53 (div.2) HDOJ5423 Rikka with Tree(bfs)
2015-08-30 16:51
344 查看
Rikka with Tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 312 Accepted Submission(s): 156
Problem Description
As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:
For a tree T,
let F(T,i) be
the distance between vertice 1 and vertice i.(The
length of each edge is 1).
Two trees A and B are
similiar if and only if the have same number of vertices and for each i meet F(A,i)=F(B,i).
Two trees A and B are
different if and only if they have different numbers of vertices or there exist an number i which
vertice i have
different fathers in tree A and
treeB when
vertice 1 is root.
Tree A is
special if and only if there doesn't exist an tree B which A and B are
different and A and B are
similiar.
Now he wants to know if a tree is special.
It is too difficult for Rikka. Can you help her?
Input
There are no more than 100 testcases.
For each testcase, the first line contains a number n(1≤n≤1000).
Then n−1 lines
follow. Each line contains two numbers u,v(1≤u,v≤n) ,
which means there is an edge between u and v.
Output
For each testcase, if the tree is special print "YES" , otherwise print "NO".
Sample Input
3 1 2 2 3 4 1 2 2 3 1 4
Sample Output
YES NO HintFor the second testcase, this tree is similiar with the given tree: 4 1 2 1 4 3 4
问你一棵树是否特殊,一棵树特树当且仅当非叶子结点个数不多于一个。 bfs写一遍~
AC代码:
#include "iostream" #include "cstdio" #include "cstring" #include "algorithm" #include "vector" #include "queue" using namespace std; const int MAXN = 1005; int n; bool vis[MAXN]; vector<int> v[MAXN]; void bfs() { queue<int> q; int sum = 1; q.push(1); vis[1] = true; while(!q.empty()) { int x = q.front(), tmp = 0; q.pop(); for(int i = 0; i < v[x].size(); ++i) { int y = v[x][i]; if(vis[y]) continue; vis[y] = true; tmp++; q.push(y); } sum += tmp; if(tmp != 1) break; } if(sum == n) printf("YES\n"); else printf("NO\n"); } int main(int argc, char const *argv[]) { while(scanf("%d", &n) != EOF) { memset(vis, false, sizeof(vis)); for(int i = 0; i <= n; ++i) v[i].clear(); for(int i = 0; i < n - 1; ++i) { int x, y; scanf("%d%d", &x, &y); v[x].push_back(y); v[y].push_back(x); } bfs(); } return 0; }
相关文章推荐
- 面向程序员的免费杂志
- CGI
- CGI
- Windows API函数大全
- Emacs使用笔记
- 将视频导入到iOS Simulator中
- java集合框架小结
- Toast(提示)
- Java记录 -18- static与final关键字续
- 【Python基础】Python面向对象 - 1
- 《剑指Offer》面试题:从尾到头打印链表
- Swift - 基本运算符
- 自己实现简单RPC功能
- C++ 强制类型转换
- 数据结构中排序算法-交换排序(2)
- 分布式中Redis实现Session终结篇
- 常见问题总结篇 一 、Objective C 方法和 C方法的混合调用
- Merge k Sorted Lists
- GTK+浅谈之一Windows10下QtCreator中GTK+环境搭建
- 富文本Html.fromHtml方法