HDOJ 4496 D-City

题意:一个城市中有m个点和n条线,破坏掉第i条线时,还有几个区域连通。

链接:http://acm.hdu.edu.cn/showproblem.php?pid=4496

思路:并查集,离线逆序合并,求连通块数量。

注意点:合并操作写挫,查了半天才发现。


以下为AC代码:

Run IDSubmit TimeJudge StatusPro.IDExe.TimeExe.MemoryCode Len.LanguageAuthor
124278652014-12-08 11:53:22Accepted4496327MS2376K1777 BG++luminous11

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <deque>
#include <list>
#include <cctype>
#include <algorithm>
#include <climits>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#define ll long long
#define ull unsigned long long
#define all(x) (x).begin(), (x).end()
#define clr(a, v) memset( a , v , sizeof(a) )
#define pb push_back
#define mp make_pair
#define read(f) freopen(f, "r", stdin)
#define write(f) freopen(f, "w", stdout)
using namespace std;

struct node
{
    int be;
    int en;
} k[100006];
int sum;
int SET[100005];
int ans[100005];
int cnt = 0;
int find ( int x )
{
    if ( x == SET[x] )
    {
        return x;
    }
    else
    {
        SET[x] = find( SET[x] );
        return SET[x];
    }
}

int main()
{
    //freopen ( "data.in", "r", stdin );
    //freopen ( "ans.out", "w", stdout );
    ios::sync_with_stdio ( false );
    int m, n;
    while ( scanf( "%d%d", &m, &n) != EOF )
    {
        for ( int i = 0; i < 10000; i ++ )
        {
            SET[i] = i;
        }
        sum = m;
        cnt = 0;
        for ( int i = 0; i < n; i ++ )
        {
            scanf ( "%d%d", & k[i].be, &k[i].en );
        }
        for ( int i = n - 1; i >= 0; i -- )
        {
            int x = find ( k[i].be );
            int y = find ( k[i].en );
            ans[cnt++] = sum;
            if ( x != y )
            {
                sum -= 1;
                SET[x] = y;
            }
        }
        for ( int i = cnt - 1; i >= 0; i -- )
        {
            printf ( "%d\n", ans[i] );
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值