[英]Finding longest path in an undirected tree
我試圖在無向樹( http://www.spoj.com/problems/PT07Z/ )中找到最長的路徑,並編寫了以下代碼。
#include <iostream>
#include <vector>
using namespace std;
vector< vector<int> > graph;
int q=0, m = -1; // m is for largest path and q is one of the end vertex of that path
void dfs(int i, int count, vector<bool>& v)
{
v[i] = true;
for(int j=0;j<graph[i].size();j++)
{
if(!v[graph[i][j]])
{
count++; // count is the length of the path from the starting vertex to current vertex
dfs(graph[i][j], count, v);
}
}
if(count>m)
{
m= count;
q=i;
}
count--; // decreasing count since the method return to its calling function
}
int main()
{
int n, x, i, y;
cin>>n;
graph = vector< vector<int> >(n);
vector<bool> visited(n);
vector<bool> v(n);
for(i=0;i<n-1;i++)
{
cin>>x>>y;
x--, y--;
graph[x].push_back(y);
graph[y].push_back(x);
}
dfs(0, 0, visited);
m=-1;
cout<<q<<endl;
dfs(q, 0, v);
cout<<q<<endl;
cout<<m<<endl;
}
誰能告訴我這是什么問題,因為盡管最長路徑的最終頂點正確(我嘗試過的測試用例至少),但我得到的最大路徑長度(m)值錯誤。 我試圖在這里實現以下算法:
算法:
一些測試用例:首先:
17
1 2
1 3
2 4
2 5
3 6
3 7
6 8
6 9
8 10
9 11
7 12
7 13
13 14
13 15
15 16
15 17
該測試用例的正確答案是7。
第二:
7
1 2
1 3
2 4
2 5
3 6
3 7
該測試用例的正確答案是4。
根據我的一個問題是,您應該在從調用的遞歸函數返回時立即減少計數。
for(int j=0;j<graph[i].size();j++)
{
if(!v[graph[i][j]])
{
count++;
dfs(graph[i][j], count, v);
count--;
}
或者簡單地:
for(int j=0;j<graph[i].size();j++)
{
if(!v[graph[i][j]])
dfs(graph[i][j], count+1, v);
這是因為對於graph[i]
每個鄰居,計數不應保持遞增。
只需從“ for”循環中刪除該count ++,然后刪除該count--;
並且在功能開始時保持“ count ++”。
void dfs(int i, int count, vector<bool>& v)
{
count++;
v[i] = true;
for(int j=0;j<graph[i].size();j++)
{
if(!v[graph[i][j]])
{
dfs(graph[i][j], count, v);
}
}
if(count>m)
{
m= count;
q=i;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.