Algorithm
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
int const N = 2e5 + 10;
int n, k;
map<int, bool> exist;
queue<int> q;
stack<int> res;
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#endif
scanf("%d %d", &n, &k);
for(int i = 0, tmp; i < n; ++i) {
scanf("%d", &tmp);
if(exist.count(tmp) > 0 && exist[tmp])
continue;
exist[tmp] = true;
while(q.size() >= k)
exist[q.front()] = false, q.pop();
q.push(tmp);
}
while(!q.empty())
res.push(q.front()), q.pop();
printf("%d\n", int(res.size()));
while(!res.empty())
printf("%d ", res.top()), res.pop();
puts("");
return 0;
}
Copy The Code &
Try With Live Editor
Input
7 2
1 2 3 2 1 3 2
1 2 3 2 1 3 2
Output
2
2 1
2 1
Demonstration
Codeforcess Solution B2. Social Network (hard version)-Solution in C, C++, Java, Python,Codeforcess Solution