Hangzhou Electric 2095
find your present(2)
Link to the original question: http://acm.hdu.edu.cn/showproblem.php?pid=2095
analysis
The general idea of the question is to find the only number that appears odd times in a set of numbers and output it. (The input of the title
can be satisfied) The first thing I thought about violence is to solve it violently, but unfortunately it timed out. Later, I learned from the big brother algorithm and found that it is XOR operation, so the following focuses on my own XOR operation Some understanding.
Brute force method (timeout)
#include<iostream>
using namespace std;
typedef struct tra{
int number;
int num;
}tracker[500000];
//还有一点需要注意一下,就是如果struct后面没有那个tra可能会报错,出现annonymous type with no linkage used to declare variable的报错(如果有人看这个暴力算法的话的叨叨)
int n,a[1000000];
tracker b;
int main(){
int i,j,f;
while(scanf("%d",&n)!=EOF&&n){
for(i=0;i<n;i++){
cin>>a[i];
}
for(i=0;i<n;i++){
f=0;
for(j=0;j<i;j++){
if(b[j].number==a[i]){
b[j].num+=1;
f=1;break;
}
}
if(!f){
b[j].number=a[i];b[j].num =1;
}
}
for(i=0;i<(n+1)/2;i++){
if(b[i].num %2!=0){
cout<<b[i].number<<endl;
}
}
}
return 0;
}
Bitwise exclusive OR operation (^)
Here is the reference source of the XOR and shift operators.
Definition: For the same bits (only 1 and 0) of the binary numbers of two numbers , the same is 0 (both are 1 or both are 0), and the difference is 1 (0^1)
- 0^any number = any number
- 1^Any number = any number inverted
- Any number^self=0
The above is the basic operation rules, the following are some special but correct usage
- ((a^b) ^b)=a
- The following methods can be used to replace a and b without the third variable.
For example, a=10100001, b=00000110
a = a^b; //a=10100111
b = b^a; //b=10100001
a = a^b; //a=00000110
Analyzing the above question, it can be seen that other numbers appear even times, so after multiple XORs, it must be 0 without affecting the final result. Only one number that appears odd times is the answer. code show as below:
Code
#include<iostream>
using namespace std;
int main(){
int i,n,t,a;
while(scanf("%d",&n)!=EOF&&n){
a=0;
for(i=0;i<n;i++){
scanf("%d",&t);
a^=t;
}
cout<<a<<endl;
}
return 0;
}
The point worth noting is the problem of scanf and cin . In the code where scanf is used twice, cin will report an error, time limit exceeded. The reason is because scanf is a formatted input and cin is an input stream. You need to store the data in the buffer first. Then take it to the variable, printf and cout are the same.