agc016 D - XOR Replace

Problem Statement

There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices Ai and Bi and has a length of Ci.

Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the tree above.

Joisino would like to know the length of the longest Hamiltonian path (see Notes) in this complete graph. Find the length of that path.

Notes

A Hamiltonian path in a graph is a path in the graph that visits each vertex exactly once.

Constraints

2≤N≤105
1≤Ai

题目大意

给定两个序列a,b。
每次可以执行一个操作:
就序列的异或和来代换原序列的某个数。
求从a序列变为b序列的最少操作数。

题解

一个序列的异或和代换了一个原序列的数之后,
新序列的异或和就是这个被替换的数。
如果将序列的异或和单独作为一个数,
那么操作就变成了数与数之间的两两交换。
要使操作数最少,相同的必然是不作任何修改。
如果 aibi a i 和 b i 不同,就在 aibi a i 和 b i 之间连一条边,
在连完边之后,就在相应的联通块里面进行交换,花费就是联通块大小。
如果一个联通块原先并没有包含整个的异或和,
那么它还需要花费1的操作数来跟整个的异或和交换。

code

#include<queue>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include <cstring>
#include <string.h>
#include <cmath>
#include <math.h>
#include <time.h>
#define ll long long
#define N 100003
#define M 103
#define db double
#define P putchar
#define G getchar
#define inf 998244353
using namespace std;
char ch;
void read(int &n)
{
    n=0;
    ch=G();
    while((ch<'0' || ch>'9') && ch!='-')ch=G();
    ll w=1;
    if(ch=='-')w=-1,ch=G();
    while('0'<=ch && ch<='9')n=(n<<3)+(n<<1)+ch-'0',ch=G();
    n*=w;
}

int max(int a,int b){return a>b?a:b;}
int min(int a,int b){return a<b?a:b;}
ll abs(ll x){return x<0?-x:x;}
ll sqr(ll x){return x*x;}
void write(ll x){if(x>9) write(x/10);P(x%10+'0');}

int a[N],b[N],c[N],d[N],n,ans,f[N],g[N],s,x,y;
bool bz[N];

int get(int x)
{
    return f[x]=(x==f[x]?x:get(f[x]));
}

int main()
{
    read(n);s=0;
    for(int i=1;i<=n;i++)
        read(a[i]),s^=a[i];
    a[n+1]=s;s=0;
    for(int i=1;i<=n;i++)
        read(b[i]),s^=b[i];
    b[++n]=s;

    for(int i=1;i<=n;i++)
        c[i]=a[i],d[i]=b[i],f[i]=i;

    sort(c+1,c+1+n);
    sort(d+1,d+1+n);

    for(int i=1;i<=n;i++)
        if(c[i]!=d[i])
        {
            P('-');P('1');
            return 0;
        }

    for(int i=1;i<=n;i++)
    {
        if(a[i]!=b[i] || i==n)
        {
            if(i!=n)ans++;
            x=lower_bound(c+1,c+1+n,a[i])-c;
            y=lower_bound(c+1,c+1+n,b[i])-c;
            bz[x]=bz[y]=1;
            f[get(x)]=get(y);
        }
    }
    if(ans==0)
    {
        P('0');
        return 0;
    }

    for(int i=1;i<=n;i++)
        if(bz[i] && f[i]==i)ans++;

    write(ans-1);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值