文章目录
蓝桥杯2017合根植物入口
蓝桥杯2017青蛙跳杯子入口
合根植物
题目描述:
w 星球的一个种植园,被分成 m×n 个小格子(东西方向 m行,南北方向 n 列)。每个格子里种了一株合根植物。
这种植物有个特点,它的根可能会沿着南北或东西方向伸展,从而与另一个格子的植物合成为一体。
如果我们告诉你哪些小格子间出现了连根现象,你能说出这个园中一共有多少株合根植物吗?
输入描述:
第一行,两个整数 m,n,用空格分开,表示格子的行数、列数(10001≤m,n≤1000)。
接下来一行,一个整数 k (0≤k≤10^5),表示下面还有 k行数据。
接下来 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
输出描述:
输出植物数量。
输入输出样例
示例
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
5
其合根情况参考下图:
解题思路:
#include<iostream>
using namespace std;
const int MAX = 1000000;
int per[MAX], depth[MAX];
int x, y;
void init(int n)
{
for (int i = 1; i <= n; i++)
{
per[i] = i; //赋初始值
depth[i] = 0; //用于比较两个合根植物的集合大小
}
}
int find(int key)
{
if (per[key] == key)
{
return key;//找到老大返回
}
per[key] = find(per[key]);//用递归往上找老大,压缩路径
return per[key];
}
void unite(int x, int y)
{
int root_x = find(x);
int root_y = find(y);
if (root_x == root_y)
return;
if (depth[root_x] > depth[root_y])//root_x的人数比root_y多,
{
per[root_y] = root_x;//让root_x当老大
}
else
{
if (depth[root_x] == depth[root_y])
depth[root_y]++;
per[root_x] = root_y;//让root_y当老大
}
}
int main()
{
int n, m;
int T, sum = 0;
cin >> m >> n;
cin >> T;
init(m * n);
while (T--)
{
cin >> x >> y;
unite(x, y);
}
for (int i = 1; i <= n * m; i++)
{
if (find(i) == i)
{
sum++;//统计有多少合根
}
}
cout << sum << endl;
return 0;
}
总结:并查集可用于解,最近公共祖先等处理一些不交集(Disjoint Sets)的合并及查询问题。
青蛙跳杯子
题目描述:
X 星球的流行宠物是青蛙,一般有两种颜色:白色和黑色。
X星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去。
如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙。
*WWWBBB
其中,W 字母表示白色青蛙,B 表示黑色青蛙,∗ 表示空杯子。
X 星的青蛙很有些癖好,它们只做 3 个动作之一:
跳到相邻的空杯子里。
隔着 1 只其它的青蛙(随便什么颜色)跳到空杯子里。
隔着 2 只其它的青蛙(随便什么颜色)跳到空杯子里。
对于上图的局面,只要 1 步,就可跳成下图局面:
WWW*BBB
本题的任务就是已知初始局面,询问至少需要几步,才能跳成另一个目标局面。
输入描述:
输入为 2 行,2 个串,表示初始局面和目标局面。我们约定,输入的串的长度不超过 15。
输出描述:
输出要求为一个整数,表示至少需要多少步的青蛙跳。
输入输出样例
示例
*WWBB
WWBB*
2
解题思路:
参考代码
#include<iostream>
#include<queue>
#include<set>
using namespace std;
int mv[6] = { 3,2,1,-1,-2,-3 };
struct node
{
int step;//步数
string str; //字符串
node(int _step, string _str)
{
step = _step;
str = _str;
}
};
void bfs(string strBegin,string strEnd)
{
queue<node>q;
set<string>s;
if (strBegin == strEnd)
{
cout << 0 << endl;
return;
}
q.push(node(0, strBegin));
s.insert(strBegin);
while (!q.empty())
{
node now = q.front();
q.pop();
string str = now.str;
for (int i = 0; i < str.length(); i++)
{
if (str[i] != '*') continue;
for (int j = 0; j < 6; j++)
{
int tx = i + mv[j];
if (tx >= 0 && tx < str.length())
{
swap(str[i], str[tx]);
if (now.str == strEnd)
{
cout << now.step << endl;
return;
}
if (!s.count(str))
{
s.insert(str);
q.push(node(now.step + 1,str));
}
swap(str[i], str[tx]);
}
}
}
}
}
int main()
{
string str_Begin, str_End;
cin >> str_Begin >> str_End;
bfs(str_Begin, str_End);
return 0;
}
BFS算法用途广泛,每个做蓝桥杯的人都应该熟练使用BSF