Hi, I’m trying to use dfs twice to solve the problem, but I keep getting WA and I don’t know how to solve the error. Here is my code:
#include <bits/stdc++.h>
using namespace std;
typedef stack si;
typedef vector<vector> vvi;
int main()
{
si s;
int n,a,b,ans = 0,maxDist = 0,furthestNode;
cin >> n;
vvi v;
for(int i = 0;i <= n;i++)
{
vector tmp;
v.push_back(tmp);
}
for(int i = 0;i < n-1;i++)
{
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
}
bool done = false;
bool visited[n+2] = {false};
int distances[n+2] = {0};
s.push(1);
visited[1] = true;
if(done)
{
break;
}
while(!s.empty())
{
//cout << “Not empty\n”;
int topNode = s.top();
s.pop();
for(int i = 0;i < v[topNode].size();i++)
{
int neighbor = v[topNode][i];
if(!visited[neighbor])
{
s.push(neighbor);
distances[neighbor] = distances[topNode] + 1;
if(distances[neighbor] > maxDist)
{
furthestNode = neighbor;
}
visited[neighbor] = true;
}
}
}
for(int i = 1;i <= n;i++)
{
visited[i] = false;
distances[i] = 0;
}
s.push(furthestNode);
visited[furthestNode] = true;
distances[furthestNode] = 0;
while(!s.empty())
{
//cout << “Not empty 2\n”;
int topNode = s.top();
s.pop();
for(int i = 0;i < v[topNode].size();i++)
{
//cout << “in loop\n”;
int neighbor = v[topNode][i];
if(!visited[neighbor])
{
//cout << “neighbor not visited\n”;
s.push(neighbor);
distances[neighbor] = distances[topNode] + 1;
//cout << "setting distance: " << distances[neighbor] << endl;
//cout << "topnode = " << topNode << endl;
//cout << "this neighbor = " << neighbor << endl;
if(distances[neighbor] > ans)
{
ans = distances[neighbor];
}
visited[neighbor] = true;
}
}
}
cout << ans;
}
Please help me identify the error. Thank you very much.