zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    强类型、弱类型、静态、动态语言定义(转载)
    What is a non-trivial constructor in C++?(转载)
    面试准备之面试题(C++) (一)
    python实现tail(考虑到几种特殊情况)
    rsyslog应用案例
    FUCK, 排查python写入mysql数据库过慢的过程(心都碎了)
    svn相关操作
    springCloud学习中遇到的问题
    idea启动项目没错,可是debug却一直启动不起来
    前端控制台返回406错误解决方法
  • 原文地址:https://www.cnblogs.com/water-mi/p/10303237.html
Copyright © 2011-2022 走看看