现在的位置: 首页 > 综合 > 正文

hdu2095异或

2014年09月05日 ⁄ 综合 ⁄ 共 1683字 ⁄ 字号 评论关闭

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=2095

find your present (2)

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/1024 K (Java/Others)
Total Submission(s): 14518    Accepted Submission(s): 5491

Problem Description
In the new year party, everybody will get a "special present".Now it's your turn to get your special present, a lot of presents now putting on the desk, and only one of them will be yours.Each present has a card number on it, and
your present's card number will be the one that different from all the others, and you can assume that only one number appear odd times.For example, there are 5 present, and their card numbers are 1, 2, 3, 2, 1.so your present will be the one with the card
number of 3, because 3 is the number that different from all the others.
 

Input
The input file will consist of several cases.
Each case will be presented by an integer n (1<=n<1000000, and n is odd) at first. Following that, n positive integers will be given in a line, all integers will smaller than 2^31. These numbers indicate the card numbers of the presents.n = 0 ends the input.
 

Output
For each case, output an integer in a line, which is the card number of your present.
 

Sample Input
5 1 1 3 2 2 3 1 2 1 0
 

Sample Output
3 2
Hint
Hint
use scanf to avoid Time Limit Exceeded
 

Author
8600
 

Source

异或运算

题目意思是给你一个数n(  n  < 1000000)

接下来给你n个数 每个数的大小为小于2^31

其中有且只有一个数是出现奇数次 求该数

一开始看到这个题目 想到的是打表然后发现数据很大有2^31肯定会爆栈

然后又想了一个用一个long二维数组来自定一个hash表结果MLE了

后来把long二维数组改成一维int和一维bool来模拟 虽然是大概5000k的大小但是还是MLE(题目要求是1024k)

MLE错误代码:http://paste.ubuntu.com/7219729/

然后就没辙了 后来发现异或运算

1. a ⊕ a = 0
2. a ⊕ b = b ⊕ a
3. a ⊕b ⊕ c = a ⊕ (b ⊕ c) = (a ⊕ b) ⊕ c;
4. d = a ⊕ b ⊕ c 可以推出 a = d ⊕ b ⊕ c.
5. a ⊕ b ⊕ a = b.
6.若x是二进制数0101,y是二进制数1011
则x⊕y=1110
只有在两个比较的位不同时其结果是1,否则结果为0
即“相同为0,不同为1”!
——————————————————————————————摘自百度百科

又上可以知道异或可以交换和结合 那么可以知道偶数个相同的数相互异或结果不变 所以按照题意只有一个是奇数个其他均为偶数个 所以可以直接对数据进行异或处理就好 复杂度只有O(n)

ac代码
http://paste.ubuntu.com/7219720/

抱歉!评论已关闭.