【Codeforces813F】Bipartite Checking

6 篇文章 0 订阅
4 篇文章 0 订阅

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值