Time Limit: 3 Sec Memory Limit: 162 MB
Submit: 7256 Solved: 3399
[Submit][Status][Discuss]
Description
很久以前,在一个遥远的星系,一个黑暗的帝国靠着它的超级武器统治者整个星系。某一天,凭着一个偶然的
机遇,一支反抗军摧毁了帝国的超级武器,并攻下了星系中几乎所有的星球。这些星球通过特殊的以太隧道互相直
接或间接地连接。 但好景不长,很快帝国又重新造出了他的超级武器。凭借这超级武器的力量,帝国开始有计划
地摧毁反抗军占领的星球。由于星球的不断被摧毁,两个星球之间的通讯通道也开始不可靠起来。现在,反抗军首
领交给你一个任务:给出原来两个星球之间的以太隧道连通情况以及帝国打击的星球顺序,以尽量快的速度求出每
一次打击之后反抗军占据的星球的连通快的个数。(如果两个星球可以通过现存的以太通道直接或间接地连通,则
这两个星球在同一个连通块中)。
Input
输入文件第一行包含两个整数,N (1 < = N < = 2M) 和M (1 < = M < = 200,000),分别表示星球的
数目和以太隧道的数目。星球用 0 ~ N-1的整数编号。接下来的M行,每行包括两个整数X, Y,其中(0 < = X <>
Y 表示星球x和星球y之间有“以太”隧道,可以直接通讯。接下来的一行为一个整数k,表示将遭受攻击的星球的
数目。接下来的k行,每行有一个整数,按照顺序列出了帝国军的攻击目标。这k个数互不相同,且都在0到n-1的范
围内。
Output
第一行是开始时星球的连通块个数。接下来的K行,每行一个整数,表示经过该次打击后现存星球
的连通块个数。
Sample Input
8 13
0 1
1 6
6 5
5 0
0 6
1 2
2 3
3 4
4 5
7 1
7 2
7 6
3 6
5
1
6
3
5
7
Sample Output
1
1
1
2
3
3
并查集只能添加节点,所以,时光倒流。
学到了,统计联通块不用O(n)扫,添加节点+1,合并节点-1。
/**************************************************************
Problem: 1015
User: GhostCai
Language: C++
Result: Accepted
Time:2072 ms
Memory:8724 kb
****************************************************************/
//Stay foolish,stay hungry,stay young,stay simple
#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
const int MAXN=400005;
int n,m,q;
int num;
bool ocp[MAXN];
stack<int> que;
stack<int> ans;
int fa[MAXN];
int fnd(int x){
return x==fa[x]?x:fa[x]=fnd(fa[x]);
}
void cat(int x,int y){
x=fnd(x);y=fnd(y);
if(x!=y) {
fa[y]=x;
num--;
}
}
struct Edge{
int next,to;
}e[MAXN];
int ecnt=1,head[MAXN];
void add(int x,int y){
e[++ecnt].next = head[x];
e[ecnt].to = y;
head[x]=ecnt;
}
void updata(int x){
num++;
for(int i=head[x];i;i=e[i].next){
int v=e[i].to ;
if(ocp[v]) continue;
cat(x,v);
}
}
int query(){
return num;
}
int main(){
cin>>n>>m;
int x,y;
for(int i=1;i<=m;i++){
// cin>>x>>y;
scanf("%d%d",&x,&y);
x++;y++;
add(x,y);
add(y,x);
}
cin>>q;
for(int i=1;i<=q;i++){
// cin>>x;
scanf("%d",&x);
x++;
ocp[x]=1;
que.push(x);
}
for(int i=1;i<=n;i++) fa[i]=i;
for(int i=1;i<=n;i++){
if(ocp[i]) continue;
updata(i);
}
ans.push(query());
while(!que.empty()){
int top=que.top() ;
que.pop() ;
ocp[top]=0;
updata(top);
ans.push(query());
}
while(!ans.empty()){
// cout<<ans.top()<<endl;
printf("%d\n",ans.top());
ans.pop() ;
}
return 0;
}