luoguP5937 poj1733 [CEOI1999]Parity Game

带权并查集

#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<iostream>
using namespace std;
int n,m,x[10010],y[10010],a[20010],l,r,mid,fa[20010],d[20010];
string s;
bool f[10010];
int real(int p)
{
    l=1;r=n;
    while(l+1<r)
    {
        mid=(l+r)>>1;
        if(a[mid]>p)r=mid;
        else l=mid;
    }
    if(a[l]==p)return l;
    else return r;
}
int getfa(int p)
{
    if(p==fa[p])return p;
    int root=getfa(fa[p]);
    d[p]=d[p]^d[fa[p]];
    return fa[p]=root;
}
bool merge(int xx,int yy)
{
    int fx=getfa(xx);
    int fy=getfa(yy);
    if(fx==fy)
    {
        if(d[xx]==d[yy])return false;
        else return true;
    }
    else
    {
        fa[fx]=fy;
        d[fx]=d[xx]^d[yy];
        return false;
    }
}
bool cut(int xx,int yy)
{
    int fx=getfa(xx);
    int fy=getfa(yy);
    if(fx==fy)
    {
        if(d[xx]!=d[yy])return false;
        else return true;
    }
    else
    {
        fa[fx]=fy;
        d[fx]=d[xx]^d[yy]^1;
        return false;
    }
}
int main()
{
    //freopen("xf.in","r",stdin);
    //freopen("xf.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        cin>>x[i]>>y[i];
        x[i]--;
        a[i*2]=x[i];a[i*2-1]=y[i];
        cin>>s;
        if(s=="even")f[i]=true;
        else f[i]=false;
    }
    sort(a+1,a+m*2+1);
    n=unique(a+1,a+m*2+1)-a-1;
    for(int i=1;i<=n;i++)fa[i]=i;
    for(int i=1;i<=m;i++)
    {
        x[i]=real(x[i]);
        y[i]=real(y[i]);
        if(f[i])
        {
            if(merge(x[i],y[i])){printf("%d\n",i-1);return 0;}
        }
        else 
        {
            if(cut(x[i],y[i])){printf("%d\n",i-1);return 0;}
        }
    }
    cout<<m<<endl;
    return 0;
}

开始比较难受的是,在sort和unique的时候,把n错当成m,然后出现一些奇奇怪怪的东西...没错RE了

posted @ 2020-09-03 09:31  mybing  阅读(113)  评论(0编辑  收藏  举报