I have Time Limit for 10 tests. (1.042 seconds)
Here is the task:
Intersection of many
(Time: 1 sec. Memory: 16 MB)
Two unordered sets of integers are given (maybe with repetitions). To issue without repetition in ascending order all those numbers that are found in both sets.
Input data. The first line of the input file INPUT.TXT contains two integers N and M (1 ≤ N, M ≤ 300 000) - the number of elements of the first and second sets, respectively. The following lines contain first the N numbers of the first set, and then the M numbers of the second set. Numbers are separated by spaces or line breaks. Each of these numbers falls in the range from 0 to 105.
Output. In the output file OUTPUT.TXT you need to write in ascending order without repeating all the numbers that are included in both the first and the second set. Separate numbers with one space. If there are no such numbers, the output file should remain empty.
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int a, b; cin >> a>> b; vector <int> f; vector <int> s; vector <int> ans; for (int i = 0; i < a; i++) { int x; cin >> x; f.push_back(x); } for (int i = 0; i < b; i++) { int x; cin >> x; s.push_back(x); } sort(f.begin(), f.end()); sort(s.begin(), s.end()); int pred = f[0]; for (int i = 1; i < f.size(); i++) { if (f[i] == pred) { f.erase(f.begin() + i); i--; } else pred = f[i]; } pred = s[0]; for (int i = 1; i < s.size(); i++) { if (s[i] == pred) { s.erase(s.begin() + i); i--; } else pred = s[i]; } int n=0; for(int i=0;i<f.size();i++) for (int j = n; j < s.size(); j++) { //if (f[i] == pred) { break; n = j + 1; } if (f[i] < s[j]) { break; n = j + 1; } else if (f[i] == s[j]) { ans.push_back(f[i]); n = j + 1; break; } } for (int i = 0; i < ans.size(); i++) { cout << ans[i] << " "; } return 0; }
f.erase(f.begin() + i);? Why explicitly delete items? Your approach is correct, but a waste of time toerasekills everything. Remove nafig alleraseand just do not save the same elements inans. - AnT