• 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
    ", ans[i] - i);
    	return 0;
    }
    
  • 相关阅读:
    文件上传案例_Socket_测试
    Linux的小整理(入门)
    full stack 第一天
    基础考题 试题
    shell语法
    网络管理
    图像类
    定时储存
    网络管理
    磁盘管理
  • 原文地址:https://www.cnblogs.com/water-mi/p/10303237.html
Copyright © 2020-2023  润新知