AGC016D - XOR Replace 置換/輪換



題目連接

AGC016D - XOR Replaceget

題解

能夠發現一次操做至關於一次置換
對於每一個a上的位置映射到b對應
能夠找到置換羣中的 全部輪換
一個k個元素的輪換須要k+1步完成
那麼答案就是邊數+輪換數-1
-1的話發現當最一個數爲缺乏的數時不需吧最後一步換回來it

代碼

#include<map> 
#include<cstdio> 
#include<algorithm> 
#define gc getchar()
#define pc putchar
inline int read() { 
    int x = 0,f = 1; 
    char c = gc; 
    while(c < '0' || c > '9')c = gc; 
    while(c <= '9' && c >= '0') x = x * 10 + c - '0',c = gc; 
    return x * f; 
} 
void print(int x) { 
    if(x < 0) { 
        pc('-'); 
        x = -x; 
    } 
    if(x >= 10) print(x / 10); 
    pc(x % 10 + '0'); 
} 
const int maxn = 1000007; 
int a[maxn],b[maxn],c[maxn],d[maxn]; 
int n; 
std::map<int,int>f; 
int fa[maxn]; 
int find(int x) { 
    if(fa[x] != x) fa[x] = find(fa[x]); 
    return fa[x]; 
} 
int main() { 
    n = read(); 
    for(int i = 1;i <= n;++ i) a[i] = read(); 
    for(int i = 1;i <= n;++ i) b[i] = read(); 
    int t = 0; 
    for(int i = 1;i <= n;++ i) t ^= a[i]; 
    a[n + 1] = t; 
    t = 0; 
    for(int i = 1;i <= n;++ i) t ^= b[i]; 
    b[++ n] = t; 
    for(int i = 1;i <= n;++ i) c[i] = a[i],d[i] = b[i]; 
    std::sort(c + 1,c + n + 1); 
    std::sort(d + 1,d + n + 1); 
    for(int i = 1;i <= n;++ i) { 
        if(c[i] != d[i]) { 
            puts("-1"); 
            return 0; 
        } 
    } 
    int tot = 0; 
    int ans = 0; 
    for(int i = 1;i <= n;++ i) { 
         if(a[i] != b[i] || i == n)  { 
            if(i < n) ans ++; 
            if(!f[a[i]])f[a[i]] = ++tot; 
            if(!f[b[i]])f[b[i]] = ++tot; 
            
         }  
    }    
    if(!ans) { 
        pc('0'); 
        return 0; 
    } 
    for(int i = 1;i <= tot;++ i) fa[i] = i; 
    for(int i = 1;i <= n;++ i) { 
        if(a[i] != b[i]) fa[find(f[a[i]])] = find(f[b[i]]); 
    } 
    for(int i = 1;i <= tot;++ i) if(fa[i] == i) ans ++; 
    print(ans - 1); 
    return 0; 
}
相關文章
相關標籤/搜索