For this problem, here is my code:
#include <bits/stdc++.h>
using namespace std;
vector<int> tree[101];
bool visited[101];
int n, ans=-1;
int search(int node, int target){
if(visited[node]) return -1;//checks if the node was already visited
visited[node]=true;//since it visited it, set it to true
if(node==target)return target;//found the target, so return the value
for(auto next:tree[node]){
if(search(next,target)){//recursively checks all the neighbors of a node
return target;
}
}
for(auto& ok:visited)ok=false;//sets every visit back to normal
return -1; returns this a default because nothing was found
}
int main(){
ifstream fin("factory.in");
ofstream fout("factory.out");
fin >> n;
for(int i=0;i<n-1;i++){
int a,b;
fin >> a >> b;
tree[a].push_back(b);
}
for(int i=1;i<n+1;i++){//this is the target node
for(int j=1;j<n+1;j++){//checks if every node can get to the target node
if(i!=j)ans=max(ans,search(j,i));//Think there is something wrong here but not sure
}
}
fout << ans << "\n";
}
This code works for all test cases except for the last two. I’ve tried rewriting the search function but nothing worked. Can anybody help me find any issues that may lead to this? Thanks!