Number Sequence(二进制)

本文探讨了一种特殊序列的问题,给出了求解序列异或和最大值的方法,并通过转换为二进制形式来找到使异或和最大的对应序列。文章包含了一个AC代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Number Sequence

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1886    Accepted Submission(s): 561
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

 

     题意:

     给出 N ,后给出 N 个数,它是一个 0 ~ N 的排列,找出一个序列对应式子异或和最大。

 

     思路:

     将数变为二进制考虑,会发现每个数都会有对应有一个 “ 使之变为该二进制位数全为 1 ” 的数。这样子就能解决问题了,总和就是化为全为 1 时候对应的十进制值,对应的数就是这个和减去这个值的得数。

 

     AC:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include <cmath>

using namespace std;

typedef long long ll;

ll num[100005];
ll num1[100005];

ll Bit (ll ans) {
    ll bb = 0;
    while (ans) {
        ++bb;
        ans /= 2;
    }
    return bb;
}

int main() {

    int n;

    while (~scanf("%d", &n)) {
        for (int i = 0; i <= n; ++i) {
            scanf("%I64d", &num[i]);
        }

        memset(num1, -1, sizeof(num1));

        ll sum = 0;
        for (ll i = n; i >= 0; --i) {
            if (num1[i] == -1) {
                ll bb = Bit(i);
                ll ans = pow(2, bb) - 1;
                sum += ans * 2;
                num1[i] = ans - i;
                num1[ans - i] = i;
            }
        }

        if (num1[0] == -1) num1[0] = 0;

        printf("%I64d\n", sum);
        for (int i = 0; i <= n; ++i) {
            printf("%I64d", num1[num[i]]);
            i == n ? printf("\n") : printf(" ");
        }
    }

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值