栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

奇偶游戏-----带权并查集+扩展域并查集

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

奇偶游戏-----带权并查集+扩展域并查集

奇偶游戏 题目链接

本题图片以及题解来自Bug-Free
题解网址:https://www.acwing.com/solution/content/29308/


带权并查集
#include 
#include 
#include 
#include 
using namespace std;
const int N = 10010;
int n=0,m;
int p[N],d[N];
unordered_mapS;
int get(int x)
{
    if(!S.count(x))
    {
        S[x]=++n;
    }
    return S[x];
}
int find(int x)
{
    if(p[x]!=x)
    {
        int root=find(p[x]);
        d[x]^=d[p[x]];
        p[x]=root;
    }
    return p[x];
}
int main()
{
    cin>>n>>m;
    n=0;
    int res=m;
    for(int i=0;i>a>>b>>s;
        a=get(a-1),b=get(b);
        int t=0;
        if(s=="odd")t=1;
        
        int pa=find(a),pb=find(b);
        if(pa==pb)
        {
            if((d[a]^d[b])!=t)
            {
                res=i-1;
                break;
            }
        }
        else 
        {
            p[pa]=pb;
            d[pa]=d[a]^d[b]^t;
        }
    }
    cout< 

扩展域并查集
#include 
#include 
#include 
#include 
using namespace std;
const int N = 10010,base=N/2;
int n,m;
int p[N],d[N];
unordered_mapS;
int get(int x)
{
    if(!S.count(x))
    {
        S[x]=++n;
    }
    return S[x];
}
int find(int x)
{
    if(p[x]!=x)p[x]=find(p[x]);
    return p[x];
}
int main()
{
    cin>>n>>m;
    n=0;
    int res=m;
    for(int i=0;i>a>>b>>s;
        a=get(a-1),b=get(b);
        if(s=="even")
        {
            if(find(a+base)==find(b))
            {
                res=i-1;
                break;
            }
            p[find(a)]=find(b);
            p[find(a+base)]=find(b+base);
        }
        else
        {
            if(find(a)==find(b))
            {
                res=i-1;
                break;
            }
            p[find(a+base)]=find(b);
            p[find(a)]=find(b+base);
        }
    }
    cout<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/510817.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号