LOJ#6087. 毒瘤题

版权声明:转载请注明 https://blog.csdn.net/qq_33831360/article/details/88606913

小江在找水题时发现了这样一道题:在集合中找出 k (k≤2)个出现了奇数次的正整数 a。
小江:这不是 sort 的水题吗。
然后他就用暴力水过了这题。
但是这里,为了避免暴力碾标算的情况,本题卡内存(逃

 在知乎上看过类似的题

k=1时,因为a^a=0,偶数个a异或为0,数列的异或和就是答案

k=2时,设答案为a,b,数列的异或为t = a^b,如果t的某个二进制位为1,说明a,b的这一位不同,将这位为1和0的数分别求异或和就可以得到a,b。这需要扫两次,然而我们没有空间把数列存下来,所以只能多消耗时间,把第1位为1/0的分别求异或和,第2位为1/0的分别求异或和,第3.、4......位都算出来。

#include <iostream>
#include <cstdio>

using namespace std;

void read(int &x) {
	char c;
	while ((c=getchar())<'0' || c>'9');
	x = c-'0';
	while ((c=getchar())>='0' && c<='9') x = x*10+c-'0';
}

int a[32],b[32];

int main() {
    int n,k,x;
    read(n); read(k);
	if (k == 1) {
		for (int i = 1; i <= n; i++)
		  read(x),a[0] ^= x;
		printf("%d",a[0]);
	} else {
		for (int i = 1; i <= n; i++) {
			read(x);
			for (int j = 0; j <= 30; j++)
			  if (x&(1<<j)) a[j] ^= x;
			  else b[j] ^= x;
		}
		for (int i = 1; i <= 30; i++)
		  if (a[i] && b[i]) {
		  	 if (a[i] > b[i]) swap(a[i],b[i]);
		  	 printf("%d %d",a[i],b[i]);
		  	 return 0;
		  } 
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_33831360/article/details/88606913