hdu 5014 Number Sequence 位运算+规律

来源:互联网 发布:其孰能讥之乎的其 编辑:程序博客网 时间:2024/06/04 18:32

Problem Description
There is a special number sequence which has n+1 integers. For each number in sequence, we have two rules:

● ai ∈ [0,n] 
● ai ≠ aj( i ≠ j )

For sequence a and sequence b, the integrating degree t is defined as follows(“⊕” denotes exclusive or):

t = (a0 ⊕ b0) + (a1 ⊕ b1) +···+ (an ⊕ bn)


(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 ≤ 105), The second line contains a0,a1,a2,...,an.
 

Output
For each case, output two lines.The first line contains the maximum integrating degree t. The second line contains n+1 integers b0,b1,b2,...,bn. There is exactly one space between bi and bi+1(0 ≤ i ≤ n - 1). Don’t ouput any spaces after bn.
 

Sample Input
42 0 1 4 3
 

Sample Output
201 0 2 3 4
 

题意:输入n,然后输入n+1个数,是【0,n】中不同的数。然后再找到一种排列,也是【0,n】中不同数组成的;

然后一一对应,异或后相加;输入结果 和新数列


思路:

从题目中的

2 0 1 4 3

1 0 2 3 4  看出每个数都可以找到完全匹配的,异或后不浪费任何一个1(也就是1所在位均和0匹配)。

再手算下

0 1 2 3 4 5 

5 2 1 4 3 0


0 1 2 3 4 5 6

0 6 5 4 3 2 1

匹配后都能符合这个规律。没有1浪费掉。

所以sum=(0+n)*(n+1)/2*2=n*(n+1)

然后找和 i 匹配的;

如 i=5 = 101(B)  用111(B)和他^异或操作,就能得到相反数10(B)=2;

如 i=7 = 111(B) 也用111(B),^后,得到相反数0(B)=0;

要保证111。。。 的位数不能比i 的第一个1所在的位数大;


#include<stdio.h>#include<string.h>int data[200000];int main(){int n,i,tem,yi;while(scanf("%d",&n)!=EOF){ memset(data,-1,sizeof(data));yi=1;while(yi<=n){yi=yi*2+1;}for(i=n;i>=0;i--){if(yi/2>=i){yi>>=1;}if(data[i]==-1){data[i]=yi^i;data[yi^i]=i;}} printf("%I64d\n",(__int64)(0+n)*(n+1));for(i=0;i<n+1;i++){scanf("%d",&tem);if(i==0)printf("%d",data[tem]);elseprintf(" %d",data[tem]);}puts("");}return 0;} 




0 0
原创粉丝点击