cdq分治维护并查集。
并查集时,只要按秩合并,不要路径压缩,方便还原。
(好吧,还不是看po姐博客的)
#include <bits/stdc++.h>
#define gc getchar()
#define ll long long
#define mid (l+r>>1)
#define N 400009
using namespace std;
int n,m,sta[N],top;
struct edge
{
int x,y,st,ed;
};
map<pair<int,int>,int> mp;
vector<edge> e;
namespace Union_Find_Set
{
int fa[N],Rank[N],dis[N];
int find(int x)
{
return fa[x]==x?x:find(fa[x]);
}
int get_dis(int x)
{
return fa[x]==x?0:dis[x]^get_dis(fa[x]);
}
void Union(int x,int y,int z)
{
x=find(x),y=find(y);
if (x==y) return;
if (Rank[x]>Rank[y]) swap(x,y);
if (Rank[x]==Rank[y]) Rank[y]++,sta[++top]=-y;
fa[x]=y,dis[x]=z,sta[++top]=x;
}
void Restore(int bottom)
{
while (top>bottom)
{
if (sta[top]<0) Rank[-sta[top]]--;
else fa[sta[top]]=sta[top],dis[sta[top]]=0;
top--;
}
}
}
int read()
{
int x=1;
char ch;
while (ch=gc,ch<'0'||ch>'9') if (ch=='-') x=-1;
int s=ch-'0';
while (ch=gc,ch>='0'&&ch<='9') s=s*10+ch-'0';
return s*x;
}
void solve(int l,int r,vector<edge> E)
{
using namespace Union_Find_Set;
vector<edge> L,R;
int bottom=top;
for (auto now:E)
{
if (now.st<=l&&now.ed>=r)
{
int x=find(now.x);
int y=find(now.y);
int z=get_dis(now.x)^get_dis(now.y)^1;
if (x!=y) Union(x,y,z);
else
if (z&1)
{
for (int i=l;i<=r;i++) puts("NO");
Restore(bottom);
return;
}
}
else
{
if (now.st<=mid) L.push_back(now);
if (now.ed>mid) R.push_back(now);
}
}
if (l==r)
{
puts("YES");
Restore(bottom);
return;
}
solve(l,mid,L);
solve(mid+1,r,R);
Restore(bottom);
}
int main()
{
n=read(),m=read();
for (int i=1;i<=n;i++) Union_Find_Set::fa[i]=i;
for (int i=1;i<=m;i++)
{
int x=read(),y=read();
if (!mp[make_pair(x,y)]) mp[make_pair(x,y)]=i;
else
{
e.push_back((edge){x,y,mp[make_pair(x,y)],i-1});
mp[make_pair(x,y)]=0;
}
}
for (auto now:mp)
if (now.second)
e.push_back((edge){now.first.first,now.first.second,now.second,m});
solve(1,m,e);
return 0;
}