Number Sequence
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1279 Accepted Submission(s): 548
Special Judge
Problem Description
There is a special number sequence which has n+1 integers. For each number in sequence, we have two rules:
● a i ∈ [0,n]
● a i ≠ a j( i ≠ j )
For sequence a and sequence b, the integrating degree t is defined as follows(“⊕” denotes exclusive or):
t = (a
0 ⊕ b
0) + (a
1 ⊕ b
1) +···+ (a
n ⊕ b
n)
(sequence B should also satisfy the rules described above)
Now give you a number n and the sequence a. You should calculate the maximum integrating degree t and print the sequence b.
● a i ∈ [0,n]
● a i ≠ a j( i ≠ j )
For sequence a and sequence b, the integrating degree t is defined as follows(“⊕” denotes exclusive or):
(sequence B should also satisfy the rules described above)
Now give you a number n and the sequence a. You should calculate the maximum integrating degree t and print the sequence b.
Input
There are multiple test cases. Please process till EOF.
For each case, the first line contains an integer n(1 ≤ n ≤ 10 5), The second line contains a 0,a 1,a 2,...,a n.
For each case, the first line contains an integer n(1 ≤ n ≤ 10 5), The second line contains a 0,a 1,a 2,...,a n.
Output
For each case, output two lines.The first line contains the maximum integrating degree t. The second line contains n+1 integers b
0,b
1,b
2,...,b
n. There is exactly one space between b
i and b
i+1
(0 ≤ i ≤ n - 1). Don’t ouput any spaces after b
n.
Sample Input
4 2 0 1 4 3
Sample Output
20 1 0 2 3 4
Source
Recommend
解题思路
这道题关键是在a[i]的范围是在0~n之间,而要保证a[0]^b[0]+a[1]^b[1]+……a[n]^b[n]的值最大。也就是要尽量将a[i]在二进制下的每一位取反。但是这样容易产生重复的问题,不知道如何去取舍。比如样例中的a[i]为2时,b[i]可以取1,a[i]为0时,b[i]可以取1。这样便产生了问题。。所以为了保证数值的最大,2^1=3,而0^1=1,所以应该优先满足较大的数。又因为a[i]和b[i]的范围都是0~n。所以可以从n到0做一个循环,从大到小逐个数进行考虑。将这个i的每一位取反,得到一个新的数。然后就得到一对数,保证他们局部的异或值最大。然后将这些异或的值加起来即可。
总的来说,这道题用到了贪心的思想,而且用到了哈希的思想,建立一一映射。还是比较巧妙的。
参考代码
#include<cstdio>
#include<iostream>
#define __CLR(x) memset(x,-1,sizeof(x))
#define ll long long
using namespace std;
const int maxn=100010;
int a[maxn],b[maxn];
int main()
{
//ios_base::sync_with_stdio(0);
int n;
while(~scanf("%d",&n))
{
for(int i=0; i<=n; i++)
scanf("%d",&a[i]);
ll ans=0;
__CLR(b);
for(int i=n; i>=0; i--)
{
if(b[i]>=0) continue;
int num=0,k=i,s=1;
while(k>0)
{
int t=(k%2)?0:1;
num=num+s*t;
s*=2;
k/=2;
}
b[num]=i;
b[i]=num;
ans+=2*(b[i]^b[num]);
}
printf("%I64d\n",ans);
for(int i=0;i<=n;i++)
{
if(i>0) printf(" ");
printf("%d",b[a[i]]);
}
printf("\n");
}
}