题意:一个城市中有m个点和n条线,破坏掉第i条线时,还有几个区域连通。
链接:http://acm.hdu.edu.cn/showproblem.php?pid=4496
思路:并查集,离线逆序合并,求连通块数量。
注意点:合并操作写挫,查了半天才发现。
以下为AC代码:
Run ID | Submit Time | Judge Status | Pro.ID | Exe.Time | Exe.Memory | Code Len. | Language | Author |
12427865 | 2014-12-08 11:53:22 | Accepted | 4496 | 327MS | 2376K | 1777 B | G++ | 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;
}