倒着来 水题
1671. Anansi's Cobweb
Time limit: 1.0 second
Memory limit: 64 MB
Memory limit: 64 MB
Usatiy-Polosatiy XIII decided to destroy Anansi's home — his cobweb. The cobweb consists of
Nnodes, some of which are connected by threads. Let us say that two nodes belong to the same piece if it is possible to get from one node to the other by threads. Usatiy-Polosatiy has already decided which threads and in what order he would tear and now wants to know the number of pieces in cobweb after each of his actions.
Input
The first line contains integers
N and
M — the number of nodes and threads in the cobweb, respectively
(2 ≤
N ≤ 100000;
1 ≤
M ≤ 100000)
. Each of the next
M lines contains two different integers — the 1-based indices of nodes connected by current thread. The threads are numbered from 1 to
M in the order of description. Next line contains an integer
Q which denotes the quantity of threads Usatiy-Polosatiy wants to tear
(1 ≤
Q ≤
M)
. The last line contains numbers of these threads — different integers separated by spaces.
Output
Output
Q integers — the number of pieces in Anansi's cobweb after each of Usatiy-Polosatiy's action. Separate numbers with single spaces.
Samples
input | output |
---|---|
4 4 1 2 2 3 1 3 3 4 3 2 4 3 | 1 2 3 |
3 1 1 2 1 1 | 3 |
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
#define MAXN 140000
#define MAXM 9200100
int n,m;
int set[MAXN];
void init(int n)
{
for(int i=0;i<=n;i++)
set[i]=i;
}
int find(int a)
{
int root=a;
int temp;
while(set[root]!=root)
root=set[root];
while(set[a]!=root)
{
temp=a;
a=set[a];
set[temp]=root;
}
return root;
}
bool merge(int a,int b)
{
int x=find(a);
int y=find(b);
if(x==y)
return false;
set[x]=y;
return true;
}
int ans[110000],q,ID[110000];
int u[110000],v[110000];
bool del[110000];
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=m;i++)
scanf("%d%d",&u[i],&v[i]);
scanf("%d",&q);
memset(del,0,sizeof(del));
for(int i=0;i<q;i++)
{
scanf("%d",&ID[i]);
del[ID[i]]=1;
}
int cnt=n;
init(n);
for(int i=1;i<=m;i++)
{
if(del[i]) continue;
//cout<<u[i]<<" "<<v[i]<<endl;
if(find(u[i])==find(v[i])) continue;
cnt--;
merge(find(u[i]),find(v[i]));
}
for(int i=q-1;i>=0;i--)
{
int id=ID[i];
int uu=u[id];
int vv=v[id];
ans[i]=cnt;
if(find(uu)!=find(vv))
{
merge(find(uu),find(vv));
cnt--;
}
}
for(int i=0;i<q;i++)
printf("%d ",ans[i]);
printf("\n");
}
return 0;
}