F - Xor Minimization Editorial by TOMWT

More about official editorial

Do you think the code in official editorial is efficient?

Of course not. Take a look at Problem A. Even data generated by that code can make it slow. As it is not guaranteed that the elements are distinct, if all of them are the same, it can be awful.

It takes too much time to move elements between vectors and to copy a whole vector.

In fact, we only need to sort the original array once.

During dfs, we only need to pass two pointers — the largest one and the smallest one.

The code below is the fastest one during the contest.

#include<stdio.h>
#include<algorithm>
using namespace std;
inline char nc()
{
	static char buf[99999],*l,*r;
	return l==r&&(r=(l=buf)+fread(buf,1,99999,stdin),l==r)?EOF:*l++;
}
inline void read(int&x)
{
	char c=nc();for(;c<'0'||'9'<c;c=nc());
	for(x=0;'0'<=c&&c<='9';x=(x<<3)+(x<<1)+(c^48),c=nc());
}
int n,a[155555];
inline int dfs(const int&l,const int&r,const int&now,const int&i)
{
	if(l==r)return 0;
	int mid=lower_bound(a+l,a+r+1,now|1<<i)-a;
	if(mid==l)return dfs(mid,r,now|1<<i,i-1);
	if(mid==r+1)return dfs(l,mid-1,now,i-1);
	return 1<<i|min(dfs(l,mid-1,now,i-1),dfs(mid,r,now|1<<i,i-1));
}
main()
{
	read(n);for(int i=0;i<n;read(a[i++]));sort(a,a+n);
	n=unique(a,a+n)-a;
	printf("%d",dfs(0,n-1,0,29));
}

If we use trie tree, we can also solve it \(\mathcal O(n\log a)\).

posted:
last update: