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序列的最少操作数。
题解
一个序列的异或和代换了一个原序列的数之后,
新序列的异或和就是这个被替换的数。
如果将序列的异或和单独作为一个数,
那么操作就变成了数与数之间的两两交换。
要使操作数最少,相同的必然是不作任何修改。
如果
ai和bi
a
i
和
b
i
不同,就在
ai和bi
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;
}