Ice_cream's world I
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 549 Accepted Submission(s): 308
Problem Description
ice_cream's world is a rich country, it has many fertile lands. Today, the queen of ice_cream wants award land to diligent
ACMers. So there are some watchtowers are set up, and wall between watchtowers be build, in order to partition the ice_cream’s world. But how many ACMers at most can be awarded by the queen is a big problem. One wall-surrounded land must be given to only one
ACMer and no walls are crossed, if you can help the queen solve this problem, you will be get a land.
Input
In the case, first two integers N, M (N<=1000, M<=10000) is represent the number of watchtower and the number of wall. The
watchtower numbered from 0 to N-1. Next following M lines, every line contain two integers A, B mean between A and B has a wall(A and B are distinct). Terminate by end of file.
Output
Output the maximum number of ACMers who will be awarded.
One answer one line.
One answer one line.
Sample Input
8 10 0 1 1 2 1 3 2 4 3 4 0 5 5 6 6 7 3 6 4 7
Sample Output
3
题意很明确,就是说哨塔和墙围起来的那一块地可以被分给acmer,求这样的地最多有多少,其实就是求有多少个环。
这个题目我一开始...不会做..(说明对并查集理解的还是不够透彻)主要被难在了判环上。
后来经人点拨了一下明白了,比如说我们拿下面这个例子与函数find_root结合来看一下。
<span style="font-family:Microsoft YaHei;font-size:14px;">int find_root(int x)
{
return ( x == set[x]) ? x : find_root(set[x]);
}</span>
这个函数的作用是找到点x所在树的根节点(初始化时根节点是自己)假设已经构建好了如上图所示的图,然后我们读取一组数据
3 4(表明3 4 边相连)
find_root(3) = 0
find_root(4) = 0
这两个有着共同的根节点,3,4又有关系,那么就相当于这样,于是就得到了一个环。
代码如下(亲测15MS)
<span style="font-family:Microsoft YaHei;font-size:14px;">#include <stdio.h>
#include <string.h>
#define maxn 1005
int ans,set[maxn];
void initialize()
{
for(int i = 0 ; i < maxn ; i++)
set[i] = i;
ans = 0;
}
int find_root(int x)
{
return ( x == set[x]) ? x : find_root(set[x]);
}
void Union(int x, int y)
{
int root1 = find_root(x);
int root2 = find_root(y);
if(root1 != root2)
set[root2] = root1;
}
int main()
{
int N,M;
int p1,p2;
int root1,root2;
while(scanf("%d%d",&N,&M) != EOF)
{
initialize();
for(int i = 0 ; i < M ; i++)
{
scanf("%d%d",&p1,&p2);
root1 = find_root(p1);
root2 = find_root(p2);
if(root1 == root2)
ans ++ ;
else
Union(p1,p2);
}
printf("%d\n",ans);
}
return 0;
}</span>