在无向树中寻找最长路径

Finding longest path in an undirected tree

本文关键字:路径 寻找      更新时间:2023-10-16

我试图在无向树(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)的最大长度值,尽管最长路径的端点是正确的(至少在我尝试过的测试用例上)。我尝试在这里实现以下算法:

算法:

  1. 从任意节点运行DFS查找最远的叶节点。标记节点t
  2. 运行另一个DFS查找离t最远的节点
  3. 你在第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;
    } 
}