贪心 HDU 5014

来源:互联网 发布:淘宝列王的纷争礼包 编辑:程序博客网 时间:2024/05/19 07:11


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
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)这是导致初写程序错误的主要原因。

1 0
原创粉丝点击