hdu 5014__Number Sequence

Number Sequence

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2044    Accepted Submission(s): 798
Special Judge


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
 

Sample Output
20 1 0 2 3 4
 

Source
 
題意:給出一個數字n,接下來輸入n+1個數字記爲數列a,這些數字不重複且大於等於從0到n。現要求另一數列b(特性與a數列一致)使得對應(a0+b0)^(a1+b1)^(a2+b2)^...^(an+bn)所得值最大。

想法:對於一個數a,從0到a的數字中與它異或得最大值的只有它的取反的數。例如5->101;從0到5裏應該取010,這樣就能夠利用貪心思想,從大到小,求出與之對應的那個值。

代碼如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int main()
{
    int n,b[100000+10],a,ans[100000+10];
    while(~scanf("%d",&n)) {
        memset(ans,0,sizeof(ans));
        long long sum=0;
        for(int i=n;i>=0;--i) {
            if(ans[i]==0) {
                int t=i,k=0;
                while(t) {
                    b[k]=t%2;
                    k++;
                    t/=2;
                }
                for(int j=0;j<k;++j) {
                    b[j]=!b[j];
                    ans[i]+=b[j]*pow(2,j);
                }
                ans[ans[i]]=i;
                sum+=ans[i]^i;
            }
        }
        printf("%I64d\n",sum*2);
        for(int i=0;i<=n;i++) {
            scanf("%d",&a);
            if(i==0) {
                printf("%d",ans[a]);
            }
            else
                printf(" %d",ans[a]);
        }
        printf("\n");
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章