HDU 2120 Ice_cream's world I 并查集

来源:互联网 发布:湖南云箭集团知乎 编辑:程序博客网 时间:2024/05/22 16:56
Ice_cream's world ITime Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1138    Accepted Submission(s): 684Problem Descriptionice_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.InputIn 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.OutputOutput the maximum number of ACMers who will be awarded.One answer one line.Sample Input8 100 11 21 32 43 40 55 66 73 64 7Sample Output3AuthorWiskeySourceHDU 2007-10 Programming Contest_WarmUp
//作图后可以看出每有一条回路,就会有一块地被划分出#include <cstdio>#include <iostream>#include <cstring>#include <algorithm>using namespace std;#define MAXN 100000*2int Par[MAXN], Rank[MAXN];void Init(int n){    for (int i = 1;i <= n;i++)    {        Par[i] = i;        Rank[i] = 0;    }}int Find(int x){    if (Par[x] == x) return x;    else return Par[x] = Find(Par[x]); ///同时压缩路径}void Unite(int x, int y){    x = Find(x);y = Find(y);    if (x == y) return;    if (Rank[x]<Rank[y]) Par[x] = y;    else Par[y] = x;    if (Rank[x] == Rank[y]) Rank[x]++;}int main(void){    //freopen("F:\\test.txt","r",stdin);    int N,M;    while(~scanf("%d %d",&N,&M))    {        Init(N);int Count = 0;        for(int i=1,a,b;i<=M&&scanf("%d %d",&a,&b);i++)        {            if(Find(a+1)!=Find(b+1)) Unite(a+1,b+1);            else Count++;//利用并查集判断是否有回路,自圈也是回路        }        printf("%d\n",Count);    }}

来源: http://acm.hdu.edu.cn/showproblem.php?pid=2120

0 0