解題思路:一開始以爲每兩兩異或的最大值取決於初始數列的最大值的二進制位對應的最大數,但是經驗證這是錯誤的,這樣不光會出現重複的數,而且還會得出超過n的數。。。。
正解是:a[i]^b[i]=x,x應該爲a[i]的二進制位數表示的最大數,那麼b[i]=a[i]^x;這樣不會出現超過n的數,並且不會出現相同的b[i];
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<cmath>
#include<string>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
int a[100010];
int ans[100010],temp;
bool flag[100010];
int main(){
int n;
while(~scanf("%d",&n)){
for(int i=0;i<=n;i++){
scanf("%d",&a[i]);
}
ll sum=0;
memset(flag,false,sizeof(flag));
flag[0]=true;
ans[0]=0;
for(int i=n;i>0;i--){
if(flag[i])continue;//已經配對
int len=log2(i)+1;//計算i的二進制位數
temp=(((1<<len)-1)^i);//與i相配的數
//配對
ans[temp]=i;
ans[i]=temp;
//加上這個異或最大值
sum+=((1<<len)-1);
//標記已經配對的
flag[i]=flag[ans[i]]=true;
}
//sum要乘2,因爲flag成對標記
printf("%lld\n",sum*2);
for(int i=0;i<n;i++){
printf("%d ",ans[a[i]]);//與a[i]的配對的數
}
printf("%d\n",ans[a[n]]);
}
return 0;
}
// /\ | / |**、
// / \ | / | \
// / \ |/ | / _____ ____ | /
// /------\ |\ |__/ / \ \ /\ / / \ | /
// / \ | \ | / \ \ / \ / /______\ |/
// / \ | \ | \ / \ / \ / \ |
// / \ | \ | \_____/ \/ \/ \_____ |
/**
* ┏┓ ┏┓
* ┏┛┗━━━━━━━┛┗━━━┓
* ┃ ┃
* ┃ ━ ┃
* ┃ > < ┃
* ┃ ┃
* ┃... ⌒ ... ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃ Code is far away from bug with the animal protecting
* ┃ ┃ 神獸保佑,代碼無bug
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*/
// warm heart, wagging tail,and a smile just for you!
//
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// .' \| |// `.
// / \||| : |||// \
// / _||||| -:- |||||- \
// | | \\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//