在无向树中寻找最长路径
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)的最大长度值,尽管最长路径的端点是正确的(至少在我尝试过的测试用例上)。我尝试在这里实现以下算法:
算法:
- 从任意节点运行DFS查找最远的叶节点。标记节点t
- 运行另一个DFS查找离t最远的节点 你在第2步找到的路径是树中最长的路径。
一些测试用例:第一:
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.
在我看来,一个问题是你应该在调用递归函数返回时立即递减count。
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;
}
}
相关文章:
- QT在错误的班级中寻找空位
- 如何将更多文件夹添加到c++include路径
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- C++A*算法并不总是在路径中具有目标节点
- 正在寻找C++不可变的hashset/hashmap
- 从函数角度看ID到文件路径的内部与外部映射
- boost xml parsingl将xml的路径作为变量发送
- 对于MacOS上的G++,如何添加默认的include目录/usr/local/include和默认的库搜索路径/usr
- 如何使用cppcheck处理半相对包含路径
- 在C++中设置基于操作系统的文件路径
- 基于编译器选项的编译二进制路径
- 按边长度递归搜索图中所有可行路径
- 使用变量值作为 PlaySound 中的路径
- 在一个有权无向图中寻找某一长度的所有路径
- 使用BFS算法寻找最短路径
- 寻找数和为最大值的路径
- 如何应用泛洪算法寻找一个加权二维矩阵在指定的源和目的位置之间的最优路径
- 在无向树中寻找最长路径
- 在图中寻找第二个最短路径(带回溯)
- 寻找遍历图中所有顶点的路径的更好算法是什么?