codekofi
← All problems

Problem 62

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1struct Feed {
2
3 int clock = 0;
4 map<int, vector<pair<int, int>>> wrote;
5 map<int, set<int>> follows;
6
7 void post(int who, int what) {
8 wrote[who].push_back({clock, what});
9 clock++;
10 }
11
12 vector<int> recent(int who) {
13
14 set<int> sources = follows[who];
15 sources.insert(who);
16
17 priority_queue<tuple<int, int, int, int>> heap;
18
19 for (int from : sources) {
20
21 const auto& list = wrote[from];
22
23 if (list.empty()) {
24 continue;
25 }
26
27 int last = list.size() - 1;
28
29 heap.push({list[last].first, list[last].second, from, last});
30 }
31
32 vector<int> out;
33
34 while (!heap.empty() && (int)out.size() < 10) {
35
36 auto [when, what, from, at] = heap.top();
37 heap.pop();
38
39 out.push_back(what);
40
41 if (at > 0) {
42 const auto& list = wrote[from];
43 heap.push({list[at - 1].first, list[at - 1].second,
44 from, at - 1});
45 }
46 }
47
48 return out;
49 }
50};
51
52string render(const vector<int>& ids) {
53
54 string out = "[";
55
56 for (int i = 0; i < (int)ids.size(); i++) {
57
58 if (i) {
59 out += ",";
60 }
61
62 out += to_string(ids[i]);
63 }
64
65 return out + "]";
66}
67
68vector<string> solution(const vector<string>& ops,
69 const vector<int>& who,
70 const vector<int>& what) {
71
72 Feed feed;
73 vector<string> ans;
74
75 int n = ops.size();
76
77 for (int i = 0; i < n; i++) {
78
79 if (ops[i] == "post") {
80 feed.post(who[i], what[i]);
81 ans.push_back("null");
82
83 } else if (ops[i] == "follow") {
84 feed.follows[who[i]].insert(what[i]);
85 ans.push_back("null");
86
87 } else if (ops[i] == "unfollow") {
88 feed.follows[who[i]].erase(what[i]);
89 ans.push_back("null");
90
91 } else {
92 vector<int> recent = feed.recent(who[i]);
93 ans.push_back(render(recent));
94 }
95 }
96
97 return ans;
98}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.