AGC016D - XOR Replace 置换/轮换



题目链接

AGC016D - XOR Replace

题解

可以发现一次操作相当于一次置换
对于每个a上的位置映射到b对应
可以找到置换群中的 所有轮换
一个k个元素的轮换需要k+1步完成
那么答案就是边数+轮换数-1
-1的话发现当最一个数为缺少的数时不需吧最后一步换回来

代码

#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; 
} 

转载于:https://www.cnblogs.com/sssy/p/9874786.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值