I'm trying to solve a standard interview question. I've a vector where each element is a vector itself of ints. V[0] is employee 0 and the vector of ints in v[0] is the number of employees reporting to him, say 2,3,5. Now if v[2] has 7 then indirectly 7 reports to employee 0 through 2. The question is to find a function that takes in two ints a and b and the vector of dependencies and say if a reports to b, directly or indirectly.
Here's the BFS logic
bool dependencyList(int a, int b, std::vector<std::vector<int>>& v){
std::queue<int> Q;
std::vector<int> D;
std::unordered_map<int, int> M;
for(auto it = v[b].begin(); it!= v[b].end(); it++){
Q.push(*it);
D.push_back(*it);
M[*it] = 1;
}
while(!Q.empty()){
int num = Q.front();
for(auto it = v[num].begin(); it != v[num].end(); it++){
if(M.find(*it) == M.end()){
D.push_back(*it);
M[*it] =1;
Q.push(*it);
}
}
Q.pop();
}
for(auto it= D.begin(); it!= D.end(); it++){
if(*it == a) return true;
}
return false;
}
Here's the driver code
int main() {
std::vector<int> v0;
v0.push_back(2);
v0.push_back(3);
v0.push_back(7);
std::vector<int> v1;
v1.push_back(4);
v1.push_back(9);
v1.push_back(11);
std::vector<int> v2;
v2.push_back(3);
v2.push_back(5);
std::vector<int> v3;
v3.push_back(8);
v3.push_back(6);
std::vector<std::vector<int>> v;
v.push_back(v0);
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
bool check = dependencyList(6,0,v);
std::cout<<check<<std::cout;
return 0;
}
Here's the error that I get
invalid operands to binary expression ('std::__1::basic_ostream<char>' and 'ostream' (aka 'basic_ostream<char>'))
std::cout<<check<<std::cout;
~~~~~~~~~~~~~~~~^ ~~~~~~~~~
Aucun commentaire:
Enregistrer un commentaire