Bzoj1015/洛谷P1197 [JSOI2008]星球大战(并查集)

题面

Bzoj

洛谷

题解

考虑离线做法,逆序处理,一个一个星球的加入。用并查集维护一下连通性就好了。

具体来说,先将被消灭的星球储存下来,先将没有被消灭的星球用并查集并在一起,这样做可以路径压缩,然后再将被消灭的星球倒着一个一个加入,然后在\(union\)的时候,如果两个元素不在同一个集合中,答案减一(最初答案为\(n\)),将每一阶段的答案存下来就行了。

#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
using std::min; using std::max;
using std::swap; using std::sort;
typedef long long ll;

const int N = 4e5 + 10, M = 2e5 + 10;
int n, m, from[N], fa[N], ans[N], top, ret;
bool vis[N];
struct Edge { int to, nxt; } e[M << 1]; int cnt;
inline void addEdge(int u, int v) {
    e[++cnt] = (Edge){v, from[u]}, from[u] = cnt;
}
int bro[N], k;

template<typename T>
void read(T &x) {
    x = 0; char ch = getchar();
    while(ch < '0' || ch > '9') ch = getchar();
    while(ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
}

int find(int x) { return fa[x] == x ? x : (fa[x] = find(fa[x])); }
void unionn(int x, int y) { //x -> y; 
    int fx = find(x), fy = find(y);
    if(fx != fy) --ret, fa[fx] = fy;
}

int main () {
#ifdef OFFLINE_JUDGE
    freopen("233.in", "r", stdin);
    freopen("233.out", "w", stdout);
#endif
    read(n), read(m), ret = n;
    for(int i = 0; i < n; ++i) fa[i] = i;
    for(int i = 1, u, v; i <= m; ++i) {
        read(u), read(v);
        addEdge(u, v), addEdge(v, u);
    } read(k), top = k;
    for(int i = 1; i <= k; ++i)
        read(bro[i]), vis[bro[i]] = true;
    for(int u = 0; u < n; ++u)
        if(!vis[u])
            for(int i = from[u]; i; i = e[i].nxt)
                if(!vis[e[i].to])
                    unionn(u, e[i].to);
    ans[top--] = ret;
    for(int i = k; i >= 1; --i) {
        int u = bro[i];
        for(int i = from[u]; i; i = e[i].nxt)
            if(!vis[e[i].to])
                unionn(u, e[i].to);
        vis[u] = false, ans[top--] = ret;
    }
    for(int i = 0; i <= k; ++i)
        printf("%d\n", ans[i] - i);
    return 0;
}

转载于:https://www.cnblogs.com/water-mi/p/10303237.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值