BZOJ 1015 星球大战(并查集)

正着不好搞,考虑倒着搞。倒着搞就是一个并查集。

# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi acos(-1.0)
# define eps 1e-3
# define MOD 1000000007
# define INF (LL)1<<60
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<1,l,mid
# define rch p<<1|1,mid+1,r
# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
    int res=0, flag=0;
    char ch;
    if((ch=getchar())=='-') flag=1;
    else if(ch>='0'&&ch<='9') res=ch-'0';
    while((ch=getchar())>='0'&&ch<='9')  res=res*10+(ch-'0');
    return flag?-res:res;
}
void Out(int a) {
    if(a<0) {putchar('-'); a=-a;}
    if(a>=10) Out(a/10);
    putchar(a%10+'0');
}
const int N=400005;
//Code begin...
 
int edge[N][2], node[N], fa[N], res[N];
bool vis[N];
VI head[N];
 
int find(int x)
{
    int s, temp;
    for (s=x; fa[s]>=0; s=fa[s]) ;
    while (s!=x) temp=fa[x], fa[x]=s, x=temp;
    return s;
}
void union_set(int x, int y)
{
    int temp = fa[x]+fa[y];
    if (fa[x]>fa[y]) fa[x]=y, fa[y]=temp;
    else fa[y]=x, fa[x] = temp;
}
int main ()
{
    int n, m, p;
    mem(fa,-1);
    scanf("%d%d",&n,&m);
    FOR(i,1,m) scanf("%d%d",&edge[i][0],&edge[i][1]);
    scanf("%d",&p);
    int ans=n-p;
    FOR(i,1,p) scanf("%d",node+i), vis[node[i]]=1;
    FOR(i,1,m) {
        if (vis[edge[i][0]]) head[edge[i][0]].pb(edge[i][1]);
        if (vis[edge[i][1]]) head[edge[i][1]].pb(edge[i][0]);
        if (!vis[edge[i][0]] && !vis[edge[i][1]]) {
            int u=find(edge[i][0]), v=find(edge[i][1]);
            if (u!=v) union_set(u,v), --ans;
        }
    }
    res[p+1]=ans;
    for (int i=p; i>=1; --i) {
        int u=node[i];
        for (int j=0; j<head[u].size(); ++j) {
            if (vis[head[u][j]]) continue;
            int v=find(u), w=find(head[u][j]);
            if (v!=w) union_set(v,w), --ans;
        }
        ++ans;
        res[i]=ans;
        vis[u]=0;
    }
    FOR(i,1,p+1) printf("%d\n",res[i]);
    return 0;
}
View Code

 

posted @ 2017-02-28 19:44  free-loop  阅读(108)  评论(0编辑  收藏  举报