题意:有n个点,m条边,q个操作,连通的点属于同一个集合。操作有两种:
1:Q a,b,询问a和b是否属于同一个集合,若属于,输出"Yes",否则输出“No”;
2:D i,删去第i条边
分析:并查集删边。将q个操作先保存起来,然后逆向扫描每一个操作,因为将边建立好后再删边,等价于将删边的顺序反过来建边。
代码如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
using namespace std;
const int M=1010;
const int N=100010;
int n,m,q,top,f[N];
int u[N],v[N],tag[N];
bool vis[N];
typedef struct NODE
{
char c[3];
int a,b;
}Node;
Node st[N];
int Find(int x)
{
return x==f[x]?x:(f[x]=Find(f[x]));
/* if (x==f[x]) return Find(f[x]); 这样子写居然超时,不明白。。。。。。
return x; */
}
void build()
{
int i;
top=0;
memset(vis,false,sizeof(vis));
for (i=1;i<=N;i++) f[i]=i;
for (i=1;i<=m;i++){
scanf("%d%d",u+i,v+i);
}
for (i=0;i<q;i++) {
Node t;
scanf("%s",t.c);
if (t.c[0] =='D') {
scanf("%d",&t.a);
vis[t.a]=true;
}
else {
scanf("%d%d",&t.a,&t.b);
}
st[top++]=t;
}
}
int main()
{
int i,j,x,y;
while(~scanf("%d %d %d",&n,&m,&q))
{
build();
for (i=1;i<=m;i++) if (!vis[i]) { // 若第i条边不删去,则将其两端的点建立联系
x=Find(u[i]),y=Find(v[i]);
if (x!=y) f[y]=x;
}
for (i=j=0;i<q;i++) {
Node t=st[--top];
if (t.c[0] =='D'){
x=Find(u[t.a]),y=Find(v[t.a]);
if (x!=y) { f[y]=x; }
}
else {
x=Find(t.a),y=Find(t.b);
if (x==y) tag[j++]=1;
else tag[j++]=0;
}
}
for (i=j-1;i>=0;i--) // 逆向输出操作结果
if (tag[i]) puts("Yes");
else puts("No");
}
}
/*
5 3 3
1 2
2 5
3 4
Q 1 5
D 2
Q 1 5
2 1 3
1 2
Q 1 2
D 1
Q 1 2
*/