【每日一题2019-11-13】-蓝桥杯 prev54 合根植物
1.问题描述
- w星球的一个种植园,被分成 m*n 个小格子(东西方向m行,南北方向n列)。每个格子里种了一株合成植物。这种植物有个特点,它的根可能会沿着南北或者东西方向伸展,从而与另外一个格子的植物合成一体。如果我们告诉你哪些小格子间出现了连根现象,你能说出这个园中一共有多少株合成根植物吗?
2.输入格式
第一行,两个整数m,n,用空格分开,表示格子的行数、列数(1 < m, n < 1000)。接下来一行,一个整数k,表示下面还有k行数据(0 < k < 100000) 接下来 k 行,第行两个整数 a,b,表示编号为 a 的小格子和编号为 b 的小格子合根了。格子的编号一行一行,从上到下,从左到右编号。比如:5 * 4 的小格子,编号:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
3.样例输入
5 4
16
2 3
1 5
5 9
4 8
7 8
9 10
10 11
11 12
10 14
12 16
14 18
17 18
15 19
19 20
9 13
13 17
4.样例输出
5
其合根情况参考下图
5.分析
考点— 并 查 集 \color{red}并查集 并查集
1-找到所有集合的终点
每个集合有一个代表或者祖先
int find(int x) { // 返回x所在集合的终点或特征元 while(x != uset[x]) x = uset[x]; return x; }
2-合并路线【赋权写法】
如初始化后 1 2 3 4 0 0 0 0 5 6 7 8 0 0 0 0 9 10 11 12 0 0 0 0 12 14 15 16 0 0 0 0 17 18 19 20 0 0 0 0 如插入(2,3) unit(2,3) t1 = 2 ,t2=3 1 3 3 4 0 0 1 0 5 6 7 8 0 0 0 0 9 10 11 12 0 0 0 0 12 14 15 16 0 0 0 0 17 18 19 20 0 0 0 0
void uni(int x, int y) { // 赋权写法,每个子集只有一个特征元 int t1 = find(x), t2 = find(y); if (weight[t1] > weight[t2]) uset[t2] = t1; else { uset[t1] = t2; if (weight[t1] == weight[t2]) ++weight[t2]; } }
6.代码
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
vector<int> uset, weight;
int find(int x) { // 返回x所在集合的终点或特征元
while(x != uset[x])
x = uset[x];
return x;
}
int find(int x) { // find 的递归写法
return x == uset[x] ? x : find(uset[x]);
}
void uni(int x, int y) { // 朴素写法
uset[find(x)] = find(y); // 将 x 集合的终点记作 y
}
void uni(int x, int y) { // 赋权写法,每个子集只有一个特征元
int t1 = find(x), t2 = find(y);
if (weight[t1] > weight[t2])
uset[t2] = t1;
else {
uset[t1] = t2;
if (weight[t1] == weight[t2])
++weight[t2];
}
}
int main() {
int m, n, k, ans = 0;
scanf("%d%d%d", &m, &n, &k);
for(int i = 0; i <= m * n; i++) { // init
uset.push_back(i);
weight.push_back(0);
}
for(int i = 0; i < k; i++) {
int t1, t2;
scanf("%d%d", &t1, &t2);
uni(t1, t2);
}
// 每个集合总存在这样一个终点,它的 find 值等于自身
for(int i =1; i <= m*n; i++)
if(find(i) == i) // 一个并集的终点
ans++;
cout << ans << endl;
return 0;
}