加载中...

OI题解|find your present(2)


信息奥赛题解|find your present(2)


🚀 题目浏览

【题目描述】

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.

【输入】

The input file will consist of several cases, you need to terminate your program when $n=0$.

Each case will be presented by an integer $n\ (1\le n\lt 1000000\text{, and }n\text{ 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.

【输出】

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

【输入样例】

5
1 1 3 2 2
3
1 2 1
0

【输出样例】

3
2

【提示】

Use scanf in “stdio.h” to avoid Time Limit Exceeded.

【原题链接】

https://vjudge.net/problem/HDU-2095


☘️ 题解分析

法一:利用 set.findset.erase,在 log(n) 的复杂度内完成查找和删除

法二:利用 「异或」运算(本质是不进位加法),消除所有偶数个相同的数,留下唯一出现1次的数字。


🧑🏻‍💻 C++ 代码

法一:set

#include<bits/stdc++.h>

using namespace std;
typedef long long LL;
const int N = 1e6 + 10;
int n, tmp;

int main() {
    while (scanf("%d", &n) != EOF && n != 0) {
        // 创建一个set
        set<int> s;
        for (int i = 1; i <= n; i++) {
            scanf("%d", &tmp);
            // 当前set中找不到该元素,就加入set
            if (s.find(tmp) == s.end())
                s.insert(tmp);
            else  // 当前set可以找到该元素,将其消除
                s.erase(tmp);
        }
        for (auto t: s) printf("%d\n", t);
    }

    return 0;
}

法二:异或和

#include<bits/stdc++.h>

using namespace std;
typedef long long LL;
const int N = 1e6 + 10;
int n, tmp;

int main() {
    while (scanf("%d", &n) != EOF && n != 0) {
        // 输出异或和
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            scanf("%d", &tmp);
            sum = sum ^ tmp;
        }
        printf("%d\n", sum);
    }

    return 0;
}

文章作者: Rickyの水果摊
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Rickyの水果摊 !
  目录