HDOJ 4619 Warm up 2

留下的数目 = 连通的木块的数目 - 连通的木块的数目/2.....

并查集维护即可......


Warm up 2

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 1635    Accepted Submission(s): 735


Problem Description
  Some 1×2 dominoes are placed on a plane. Each dominoe is placed either horizontally or vertically. It's guaranteed the dominoes in the same direction are not overlapped, but horizontal and vertical dominoes may overlap with each other. You task is to remove some dominoes, so that the remaining dominoes do not overlap with each other. Now, tell me the maximum number of dominoes left on the board.
 

Input
  There are multiple input cases.
  The first line of each case are 2 integers: n(1 <= n <= 1000), m(1 <= m <= 1000), indicating the number of horizontal and vertical dominoes.
Then n lines follow, each line contains 2 integers x (0 <= x <= 100) and y (0 <= y <= 100), indicating the position of a horizontal dominoe. The dominoe occupies the grids of (x, y) and (x + 1, y).
  Then m lines follow, each line contains 2 integers x (0 <= x <= 100) and y (0 <= y <= 100), indicating the position of a horizontal dominoe. The dominoe occupies the grids of (x, y) and (x, y + 1).
  Input ends with n = 0 and m = 0.
 

Output
  For each test case, output the maximum number of remaining dominoes in a line.
 

Sample Input
   
   
   
   
2 3 0 0 0 3 0 1 1 1 1 3 4 5 0 1 0 2 3 1 2 2 0 0 1 0 2 0 4 1 3 2 0 0
 

Sample Output
   
   
   
   
4 6
 

Source
2013 Multi-University Training Contest 2
 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

int tu[110][110],n,m;

int fa[2100],sz[2100];
int vis[4100];

int Find(int x)
{
    if(x==fa[x]) return x;
    return fa[x]=Find(fa[x]);
}

void Union(int a,int b)
{
    a=Find(a),b=Find(b);
    if(a==b) return ;
    if(sz[a]<sz[b])
    {
        fa[b]=a;
        sz[a]+=sz[b];
    }
    else
    {
        fa[a]=b;
        sz[b]+=sz[a];
    }
}

int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(n==0&&m==0) break;
        for(int i=0;i<2100;i++)
            fa[i]=i,sz[i]=1;
        memset(tu,0,sizeof(tu));
        int cnn=0,cnm=n,x,y;
        for(int i=0;i<n;i++)
        {
            cnn++;
            scanf("%d%d",&x,&y);
            tu[x][y]=tu[x+1][y]=cnn;
        }
        for(int i=0;i<m;i++)
        {
            cnm++;
            scanf("%d%d",&x,&y);
            ///x,y+1
            if(tu[x][y])
            {
                Union(tu[x][y],cnm);
            }
            if(tu[x][y+1])
            {
                Union(tu[x][y+1],cnm);
            }
        }
        int ans=0;
        memset(vis,false,sizeof(vis));
        for(int i=1;i<=n+m;i++)
        {
            int f=Find(i);
            if(vis[f]) continue;
            vis[f]=true;
            ans+=sz[f]-sz[f]/2;
        }
        printf("%d\n",ans);
    }
    return 0;
}




你可能感兴趣的:(HDOJ 4619 Warm up 2)