Codeforces 519B Using Vectors vs Some Other Container

Viewed 42

To solve 519B I created three vectors that each hold different numbers and occurrences of those numbers for each line. These vectors are also sorted.

eg if the line was 1 1 3 2, the vector would store <1, 2>, <2, 1>, <3, 1>

From there, I would compare one pair from one vector with the pair from the next vector to find the missing number.

This passes most test cases until there are a large number of numbers in each line. I actually saw the answer for this question, but it uses a different method to find the answer. However, I would like to know if there is a way to solve the question with "my way." I read online that using maps and other containers could yield a faster result, but I'm skeptical that using another container would really make that big of a difference. Any thoughts?

#include <iostream>
#include <vector>
#include <algorithm>

int has(std::vector<std::pair<int, int>> &error, int i) {
    for (int j = 0; j < error.size(); j++) {
        if (error[j].first == i) {
            return j;
        }
    }

    return -1;
}

std::vector<std::pair<int, int>> generate(int n) {
    int temp;
    std::vector<std::pair<int, int>> tempVec;

    for (int i = 0; i < n; i++) {
        std::cin >> temp;
        int pos = has(tempVec, temp);
        if (pos != -1) {
            tempVec[pos].second++;
        } else {
            tempVec.push_back(std::make_pair(temp, 1));
        }
    }

    return tempVec;
}

bool sortPair(const std::pair<int, int> &a, const std::pair<int, int> &b) {
    return a.first < b.first;
}

int main() {
    int n, temp;
    std::cin >> n;

    std::vector<std::pair<int, int>> a = generate(n), b = generate(n - 1), c = generate(n - 2);
    std::sort(a.begin(), a.end(), sortPair);
    std::sort(b.begin(), b.end(), sortPair);
    std::sort(c.begin(), c.end(), sortPair);

    bool found = false;

    for (int i = 0; i < n - 1; i++) {
        if (a[i] != b[i]) {
            found = true;
            std::cout << a[i].first << std::endl;
            break;
        }
    }

    if (!found) {
        std::cout << a[n - 1].first << std::endl;
    }

    bool found2 = false;

    for (int i = 0; i < n - 2; i++) {
        if (b[i] != c[i]) {
            found2 = true;
            std::cout << b[i].first << std::endl;
            break;
        }
    }

    if (!found2) {
        std::cout << b[n - 2].first << std::endl;
    }
}
0 Answers
Related