首页 > 代码库 > hdu 5014(贪心+异或 西安网络赛)

hdu 5014(贪心+异或 西安网络赛)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5014

Number Sequence

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 681    Accepted Submission(s): 321
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
2014 ACM/ICPC Asia Regional Xi‘an Online 

思路: 网上已经有很多解题报告了,解法都差不多,给定一个数n,求这n+1个数与另外n+1个数相匹配求最大的异或值之和;
            可以发现规律: 从n开始遍历到0,让每个值都找到另一个“互补”的值,比如 :n=9,那么就有10个数,最大的是9,其二进制表示为1001,那么它就应该与0110匹配~
           (一定得从最大值n开始遍历,才符合贪心的正确性)
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <cstdio>
#include <cmath>
const int N=1e5+100;
using namespace std;
int hash[N];
int a[N];

int main()
{
    int n;
    while(cin>>n)
    {
      for(int i=1;i<=n+1;i++)
      {
        scanf("%d",&a[i]);
      }
      memset(hash,-1,sizeof(hash));
      for(int i=n;i>=0;i--) //将n个数从大到小排列进行位处理,使得“互补”,这样异或值才是最大的;
      {
       if(hash[i]>-1)continue;
       int sum=0,cnt=1,s=i;
       while(s)
       {
         int t=(s&1)^1;
         sum+=t*cnt;
         cnt*=2;
         s/=2;
       }

       hash[i]=sum;
       hash[sum]=i;
      }
      printf("%I64d\n",(long long )n*n+n);
      for(int i=1;i<=n+1;i++)
      {
        if(i==1)printf("%d",hash[a[i]]);
        else printf(" %d",hash[a[i]]);
      }
      printf("\n");
    }
    return 0;
}




hdu 5014(贪心+异或 西安网络赛)