您的位置:首页 > 其它

CarrerCup-多叉树上的最长连续路径

2015-03-10 18:31 190 查看
今天在CarrerCup上看到了一个问题,好像还没有好的答复,感觉可以用树形DP来做。

题目连接:http://www.careercup.com/question?id=6285363834257408

问题原文:in a tree any root can have any number of children. Every node has an integer value. Find the maximum length on consecutive number sequence anywhere in the tree. For example if root is 2 and one child is 3, its child is 4 its child is 6 then max length
will be 3. I was able to write the code the find of one sequence but when one sequence ends and other starts I was not able to handle that case. I think its hard to do by recursion. Is there any other trick or algorithm for this??

问题翻译:在一颗多叉树上,每个节点都有一个整数值,找到一条最长的路径,路径上的节点整数值连续,路径可以从任意节点开始

分析:如果路径指的都是从父节点到子孙节点,则我们可以用树形DP来做,不妨假设对每个节点都有一个标号(如果标号不是天然存在,则一次DFS可以完成),每个节点的子孙节点都保存在一个数组中(如果不是天然存在,则与标号一起一次DFS可以完成),对于空树来说,显然长度为0,对于一棵以x为根的非空子树来说,最长路径可能有两种情况:

(1)这条最长路径以x为起点

(2)这条路径以x的一个后代为起点

对于这两种情况,我们可以对一个节点设置两个状态,f[x][0]表示以x为起点的最长路径长度,f[x][1]表示以x的后代为起点的最长路径长度,则

void TreeDP(int x)
{
f[x][0] = 1;
f[x][1] = 0;

vector<int>& v = children[x];
if(v.empty()) return;

for(int i = 0; i < v.size(); ++i){
int y = v[i];
TreeDP(y);
if(value[y] + 1 == value[x]) f[x][0] = max(f[x][0], f[y][0] + 1);
f[x][1] = max(f[x][1], max(f[y][0], f[y][1]));
}
}

现在有了每个节点的最长路径长度,且最长路径即maxlen = max(f[root][0], f[root][1]),那我们如何能将这条路径也找到呢。毫无疑问,首先要找到路径的起点,且对于这条最长连续路径的起点有f[start][0] = maxlen,所以我们遍历一遍f[][0]即可,这样有了起点,有了长度,而且路径还是连续的整数值,整条路径就可以确定了。

=============================================== 分割线 ================================================

We can solve this problem with dynamic programing on the tree.

For an empty tree, the result is 0 obviously.

For a nonempty tree with root being x, the longest consecutive path may be:

(1) starting with x

(2) starting with a descendant in the one subtree of x

We can suppose that every node has a unique id as an integer, its children is known and stored in a vector.

Now we use f[x][0] to represent the length of the longest consecutive path starting with x, and use f[x][1] to represent the length of the longest consecutive path starting with x's descendant, so the result is maxlen = max(f[root][0], f[root][1]).

Now consider the relationship between x and its children y:

if value[y]+1 == value[x], then f[x][0] = max(f[x][0], f[y][0] + 1)

meanwhile we have f[x][1] = max(f[x][1], max(f[y][0], f[y][1]))

As for the path itself, we know its length is maxlen now and we have f[start][0] = maxlen, so after iterating f[][0], we can figure out the consecutive integer sequence's start and length.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: