AcWing_1204 错误票据(哈希、stringstream)

AcWing

1204. 错误票据

哈希很简单,问题在于读数据。两种方法。

stringstream类包含在<sstream>头文件中,用于构造字符串流对象,代替cin流读取数据。

#include <bits/stdc++.h>
using namespace std;
int n;
const int N = 100010;
int maxe = -1, mine = N;
int a[N];
int main(){
    cin >> n;
    getchar();
    string s;
    while(n --){
        getline(cin, s);
        stringstream is(s);
        int t;
        while(is >> t){
            a[t]++;
            if(t > maxe) maxe = t;
            if(t < mine) mine = t;
        }
    }
    int d, c;
    for(int i = mine; i <= maxe; i++){
        if(a[i] == 0) d = i;
        if(a[i] > 1) c = i;
    }
    cout << d << ' ' << c;
    return 0;
}

另一种更快的办法:

#include <bits/stdc++.h>
using namespace std;
int n;
const int N = 100010;
int maxe = -1, mine = N;
int a[N];
int main(){
    cin >> n;
    while(cin >> n){
        a[n]++;
        if(n > maxe) maxe = n;
        if(n < mine) mine = n;
    }
    int d, c;
    for(int i = mine; i <= maxe; i++){
        if(a[i] == 0) d = i;
        if(a[i] > 1) c = i;
    }
    cout << d << ' ' << c;
    return 0;
}