Official

C - Centers Editorial by en_translator


It can be solved with the following algorithm.

  1. Prepare an empty array \(ans\).
  2. Scan the sequences in the order of \(A_1,A_2,\dots\). Here, we maintain in another array how many times each number has occurred in the part we have scanned so far. Let \(c\) be the integer that you are inspecting. If it is the second occurrence of \(c\), append \(c\) to the tail of \(ans\).
  3. Print \(ans\).

This algorithm works in a total of \(O(N)\) time, which is fast enough.

Sample code (C++) :

#include<bits/stdc++.h>

using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> cnt(n + 1), ans;
    for (int i = 0; i < 3 * n; i++) {
        int a;
        cin >> a;
        ++cnt[a];
        if (cnt[a] == 2) ans.push_back(a);
    }
    for (int i = 0; i < n; i++) {
        cout << ans[i] << (i == n - 1 ? '\n' : ' ');
    }
}

Sample code (Python) :

n = int(input())
a = list(map(int, input().split()))
cnt = [0 for _ in range(3 * n)]
ans = []
for i in a:
    cnt[i] += 1
    if cnt[i] == 2:
        ans.append(i)

print(*ans)

posted:
last update: