PAT1118. Birds in Forest (并查集)
来源:互联网 发布:信息图制作软件 编辑:程序博客网 时间:2024/06/06 16:29
思路:并查集一套带走。
AC代码
#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;const int maxn = 10000+5;int par[maxn], vis[maxn];int findRoot(int x) { return x == par[x] ? x : par[x] = findRoot(par[x]);}void unionSet(int x, int y) { x = findRoot(x); y = findRoot(y); if(x != y) { par[x] = y; }}void init(int n) { memset(vis, 0, sizeof(vis)); for(int i = 0; i <= n; i++) { par[i] = i; }}int main() { int n, k, q, len; len = -1; scanf("%d", &n); init(maxn); for(int i = 0; i < n; i++) { int x, y; scanf("%d%d", &k, &x); len = max(len, x); for(int j = 1; j < k; j++) { scanf("%d", &y); len = max(len, y); unionSet(x, y); x = y; } } int tol = 0; for(int i = 1; i <= len; i++) { int root = findRoot(i); if(!vis[root]) { vis[root] = 1; tol++; } } printf("%d %d\n", tol, len); scanf("%d", &q); int x, y; for(int i = 0; i < q; i++) { scanf("%d%d", &x, &y); x = findRoot(x); y = findRoot(y); if(x == y) { printf("Yes\n"); } else { printf("No\n"); } } return 0;}
如有不当之处欢迎指出!
阅读全文
0 0
- PAT1118. Birds in Forest (并查集)
- PAT--1118. Birds in Forest(并查集)
- pat甲1118. Birds in Forest(并查集)
- 1118. Birds in Forest (25) 并查集
- PAT - 甲级 - 1118. Birds in Forest (25) (并查集)
- 1118. Birds in Forest (25) (并查集,注意顺序)
- pat 1118. Birds in Forest (25) 并查集
- PAT A1118. Birds in Forest (25)(并查集)
- 1118. Birds in Forest (25)[并查集]
- 1118. Birds in Forest (25) <并查集+set>
- PAT 1118. Birds in Forest (25) 并查集
- 1118. Birds in Forest (25)-PAT甲级真题(并查集)
- 1118. Birds in Forest
- Birds in Forest
- 1118. Birds in Forest
- 1118. Birds in Forest
- 1118. Birds in Forest (25)
- 1118. Birds in Forest (25)
- 开发经常用到的API
- web.xml配置各节点说明
- lazy loading
- oracle实用知识(三)
- 最小的k个数
- PAT1118. Birds in Forest (并查集)
- 区块链3.0时代:你现在所有的认知将会被颠覆
- python 将一个目录中所有照片设置为iPhone5大小
- 《机器学习》读书笔记 1 序言
- c++---operator重载++,--
- hdu 1171 母函数
- 区块链应用层出不穷 更要踏实前行
- cassandra 读写数据一致性(consistency level)
- listview下拉变黑