贪心 HDU 5014



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.
 

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.
 

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
思路:贪心:要明白二进制异或的贪心规则,当2个数异或时最高位是1与0,可以算出最大数。(从最大的一个数开始找能配对使他们的异或值最大的一个数即可)
#include <stdio.h>
#include <string.h>

int str[1000005],judge[1000005];
int main()
{
    int n,i,itemp,j,sum;
    //freopen("e:\\in.txt","r",stdin);
    while(scanf("%d",&n)==1)
    {   long long ans=0;
        memset(judge,-1,sizeof(judge));   //判断数组

        for(itemp=0;itemp<=n;itemp++)
            scanf("%d",&str[itemp]);//输入数组

         for(i=n;i>=0;i--)
         {

             if(judge[i]==-1)
             {   sum=0;
                 for(itemp=0;;itemp++)
                 {
                     if(!(i&(1<<itemp)))   sum+=1<<itemp;

                     if(sum>=i)   break;
                 }
                 sum-=(1<<itemp);
                 ans+=(i^sum)*2;

                 judge[i]=sum;
                 judge[sum]=i;

             }

         }

         printf("%lld\n",ans);
         for(j=0;j<n;j++)
            printf("%d ",judge[str[j]]);
           printf("%d\n",judge[str[n]]);
    }
    return 0;
}
关键:
1.2个数组之间的嵌套。把数组str嵌套在judge,直接把所对应的计算出来即可。
2.对2进制异或内容与数字之间规律的掌握。
3.判断数组judge的判断内容,if(judge[i])与if(judge[i]==-1)这是导致初写程序错误的主要原因。

你可能感兴趣的:(二进制,贪心)