The outer for loop of the last loop should run umap.size()
number of times but the loop is running for only one time.
It's kind of magic to me. Initially, it gives the expected result, but as I comment (q.push(b); s.insert(b);
) the two lines present in the last loop and uncomment those two, after this, on compiling and running code the loop runs only one time.
Please help, I am stuck with a day!
I got stuck on leetcode, then I tried on my personal computer but the problem persists. I am running the code on g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0.
#include<bits/stdc++.h>
using namespace std;
int main() {
vector<vector<int>> pre = {{1,0},{2,0},{1,2},{3,2},{7,2},{4,3},{5,4},{6,5},{7,6}};
unordered_map <int, vector<int>> umap;
for (auto a : pre) {
umap[a[1]].push_back(a[0]);
}
queue<int> q;
unordered_set <int> s;
unordered_map <int, int> memo;
int i;
for (auto a : umap) {
cout << a.first << " ";
if (a.first >= 0) {
for(auto b : umap[i] ) {
if (!s.count(b)) {
q.push(b);
s.insert(b);
}
}
}
}
return 1;
}
Excepted output 6 5 4 3 0 2 actual result 6