HDU 2473 Junk-Mail Filter (删点并查集)
2015-04-14 00:40
411 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2473
题意:给n个点,m个操作,操作分两种,可以把两点合在同一集合或者把某点从原集合分离出去
思路:并查集要增添一个“删除”功能,即保持原树的形态不变,新建一个节点,把要删除的点的信息映射到该点上,之后对此点操作即可
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
#include <utility>
#include <functional>
#include <string>
#include <set>
using namespace std;
const int maxn = 2000010;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
int fa[maxn], id[maxn];
void init(int n)
{
for (int i = 0; i < n; i++)
fa[i] = id[i] = i;
}
int find(int x)
{
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
void unite(int x, int y)
{
x = find(x), y = find(y);
if (x != y)
fa[x] = y;
}
int main()
{
int n, m, ca = 1;
while (~scanf("%d%d", &n, &m) && (n + m))
{
init(n);
int cnt = n;
while (m--)
{
char c;
scanf(" %c", &c);
if (c == 'M')
{
int x, y;
scanf("%d%d", &x, &y);
unite(id[x], id[y]);
}
else
{
int x;
scanf("%d", &x);
id[x] = cnt;
fa[cnt] = cnt;
cnt++;
}
}
set <int> s;
for (int i = 0; i < n; i++)
s.insert(find(id[i]));
printf("Case #%d: %d\n", ca++, s.size());
}
return 0;
}
题意:给n个点,m个操作,操作分两种,可以把两点合在同一集合或者把某点从原集合分离出去
思路:并查集要增添一个“删除”功能,即保持原树的形态不变,新建一个节点,把要删除的点的信息映射到该点上,之后对此点操作即可
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
#include <utility>
#include <functional>
#include <string>
#include <set>
using namespace std;
const int maxn = 2000010;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
int fa[maxn], id[maxn];
void init(int n)
{
for (int i = 0; i < n; i++)
fa[i] = id[i] = i;
}
int find(int x)
{
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
void unite(int x, int y)
{
x = find(x), y = find(y);
if (x != y)
fa[x] = y;
}
int main()
{
int n, m, ca = 1;
while (~scanf("%d%d", &n, &m) && (n + m))
{
init(n);
int cnt = n;
while (m--)
{
char c;
scanf(" %c", &c);
if (c == 'M')
{
int x, y;
scanf("%d%d", &x, &y);
unite(id[x], id[y]);
}
else
{
int x;
scanf("%d", &x);
id[x] = cnt;
fa[cnt] = cnt;
cnt++;
}
}
set <int> s;
for (int i = 0; i < n; i++)
s.insert(find(id[i]));
printf("Case #%d: %d\n", ca++, s.size());
}
return 0;
}
相关文章推荐
- (step5.1.2)hdu 2473(Junk-Mail Filter——并查集)
- HDU 2473 Junk-Mail Filter 删点并查集
- hdu 2473 Junk-Mail Filter(删除节点操作的并查集)
- HDU 2473 Junk-Mail Filter 并查集 删点
- HDU 2473 Junk-Mail Filter 并查集,虚拟删除操作
- HDU 2473 Junk-Mail Filter 删点并查集
- HDU 2473 Junk-Mail Filter 删点并查集
- HDU 2473 Junk-Mail Filter 并查集 惰性删除
- HDU 2473 ( Junk-Mail Filter ) (并查集删除操作)
- HDU-2473 Junk-Mail Filter(并查集的删除)
- hdu 2473 Junk-Mail Filter(并查集+虚拟节点)
- HDU 2473 Junk-Mail Filter(并查集+删点,设立虚父节点/找个代理)
- HDU 2473 - Junk-Mail Filter ,并查集的删点
- HDU 2473 Junk-Mail Filter 并查集拆分
- hdu 2473 Junk-Mail Filter (暴力并查集)
- HDU 2473 Junk-Mail Filter(带分离操作的并查集)
- 来个杭电的题 ---并查集 HDU 2473 Junk-Mail Filter
- hdu 2473 Junk-Mail Filter 并查集 虚父节点
- HDU 2473 Junk-Mail Filter(并查集)
- HDU 2473 Junk-Mail Filter (并查集的删除操作)