LA 4487

LA 4487

題意是有n個數,Q個操作,你並不知道這n個數的具體值。操作有三種:
1)I p v,告訴你第p個數值爲v
2)I p q v,告訴你第p個數和第q個數的異或值爲v
3)Q k a1…ak,詢問a1…ak這k個數的異或值
考慮並查集,par[x]保存x的父節點,v[x]保存x和par[x]的異或值。
I p q v時,合併p和q,並在尋根時路徑壓縮,更新父節點以及和父節點的異或值。
I p v可以視作I p 0 v,把0當做超級父節點,v[0]=0,那麼v[x]=v[x]^v[0]=v。
詢問時,被查詢節點的根節點不是超級節點時,說明具體值未確定,只有和它同根的節點與它的異或值纔是確定的,因此,統計待查詢節點的根節點個數,若它不是超級父節點,且個數爲奇數,那麼無解。否則,有解,直接異或v[a1]^….v[ak]即爲解。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define debug puts("Infinity is awesome!")
#define LS (root<<1)
#define RS (root<<1|1)
#define LSON LS,l,mid
#define RSON RS,mid+1,r
#define LL long long
const int Inf=1e9+7;
const int maxn=2e4+5;
int par[maxn], v[maxn];
void init(){
    for(int i=0;i<maxn;i++){
        par[i]=i;
        v[i]=0;
    }
}
int find(int x){
    if(x==par[x]) return x;
    int fx=par[x];
    par[x]=find(par[x]);
    v[x]^=v[fx];
    return par[x];
}
bool unite(int x,int y,int p){
    int fx=find(x);
    int fy=find(y);
    if(fx==fy) return (v[x]^v[y])==p;
    if(fx==0) swap(fx,fy);//0 -> virtual super root
    par[fx]=fy;
    v[fx]=v[x]^v[y]^p;
    return true;
}
int main(){
    int n, Q;
    int cas=0;
    int a[20], fa[20];
    char ins[100];

    while(~scanf("%d%d",&n,&Q)){
        if(n==0&&Q==0) break;
        printf("Case %d:\n",++cas);
        init();
        int facts=0, K;
        int x, y, val;
        bool err=false;
        for(int i=0;i<Q;i++){
            scanf("%s",ins);
            if(ins[0]=='I'){
                facts++;
                gets(ins);
                if(sscanf(ins,"%d%d%d",&x,&y,&val)==2){
                    val=y;
                    y=-1;
                }
                x++, y++;
                if(err) continue;
                if(!unite(x,y,val)){
                    printf("The first %d facts are conflicting.\n",facts);
                    err=true;
                }
            }else{
                scanf("%d",&K);
                for(int j=0;j<K;j++){
                    scanf("%d",&a[j]);
                    a[j]++;
                    fa[j]=find(a[j]);
                }
                if(err) continue;
                fa[K]=Inf;
                sort(fa,fa+K);
                int cnt=0, no_ans=0;
                for(int j=0;j<K;j++){
                    cnt++;
                    if(fa[j]!=fa[j+1]){
                        if(cnt%2==1&&fa[j]!=0)
                            no_ans=1;
                        else
                            cnt=0;
                    }
                }
                if(no_ans) {
                    puts("I don't know.");
                    continue;
                }
                int ans=0;
                for(int j=0;j<K;j++)
                    ans^=v[a[j]];
                printf("%d\n",ans);
            }
        }
        puts("");
    }
    return 0;
}
發佈了54 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章