[ NOIP ] Maximum Xor Sum Problem

本文介绍了一种选择整数序列中某些元素以获得最大异或和的算法。通过从高位到低位扫描,选择合适的元素进行异或操作,最终得到最大的异或结果。

QUESTION

  Given n integers {a1, a2, ..., an}, n ≤ 100, 000. Select some, s.t. they have the maximum xor sum.

  For random numbers like 19, 44, 9, 33, they could be made into lines like:

            0  1  0  0  1  1

            1  0  1  1  0  0

            0  0  1  0  0  1

            1  0  0  0  0  1

   The algorithm is selecting the "1" "0" from high to low order ( left to right ), then from up to down.

  We need var "int ans" for storing the final answer.

  Once we find the first "1" in the column (the number we found called "x"), we let the number xor the number below which have got "1" in the same column.

  Then, we let x xor ans iff ans has "0" at the current column. And we let the number x = 0 0 0 0 0 ......( x = 0 [C++])

  Loop it in every column till the last one.

  CODE:

  

//origin code by cmd2001
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int in[10100], n, ans, x;
int main() {
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) scanf("%d", in + i);
	x = 0;
	for (int i = 31; i >= 0; i--) {
		x = 0;
		for (int j = 1; j <= n; j++) {
			if ((in[j] >> i) & 1) x = j;
		} if (x) {
			for (int j = 1; j <= n; j++) {
				if (j != x && (in[j] >> i) & 1) in[j] ^= in[x];
			}	
			if (!(ans >> i) & 1) ans ^= in[x];
			in[x] = 0;
		}
	}
	printf("%d\n", ans);
	return 0;
}

  

  

转载于:https://www.cnblogs.com/Kvar-ispw17/p/6503363.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值