您的位置:首页 > 其它

ZOJ3432 Find the Lost Sock,异或运算

2011-09-01 16:24 423 查看
ZOJ上面的AC终于超过了100了



这道题有点难度,首先是输入的数据量大,最大的测试集达到1000000*2-1。其次一般人的想法是对于每一个输入,检索以前的输入是否有与之匹配的,如果有则消去,否则将输入记下来。

但是计算机里面有个非常有用的运算,就是异或了。而且异或符合交换律和结合律,假设异或记为xor,则有

A xor B xor A = A xor ( B xor A ) = A xor A xor B = B


根据以上的规律,我们可以对设置一个字符串数组,对于每一次输入,将输入的每一位和字符串数组的相应位进行异或运算,输入结束后的字符串数组就是缺失的袜子了。一下为代码。

/*******************************************************************************
* Author : Neo Fung
* Email : neosfung@gmail.com
* Last modified : 2011-09-01 16:17
* Filename : ZOJ3432 Find the Lost Sock.cpp
* Description :
* *****************************************************************************/
// ZOJ3432 Find the Lost Sock.cpp : Defines the entry point for the console application.
//

// #include "stdafx.h"

#include <stdio.h>
#include <string.h>
#include <string>

using namespace std;

int main(void)
{
int n;
char str[8],ch;
while(scanf("%d",&n)!=EOF)
{
memset(str,'\0',sizeof(str));

for(int i=0;i<n*2-1;++i)
{
getchar();
for(int j=0;j<7;++j)
{
ch=getchar();
str[j] = str[j]^ch;
}
}

printf("%s\n",str);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: