繁体   English   中英

树的子树

[英]Subtrees of a tree

我有一个有n个节点的给定树。 任务是找到给定树的子树数,其补充的出口边缘小于或等于给定数量K.

例如:如果n=3k=1

给定的树是1---2---3

那么总有效子树将是6

{}, {1}, {3}, {1,2}, {2,3}, {1,2,3}

我知道我可以枚举所有2^n树并查看有效的树,但是有一些方法更快吗? 我可以在n实现多项式时间吗? 接近O(n^3)或甚至O(n^4)会很好。

编辑:对于k = 1,该值结果为2*n

这是树上DP模式的一个相当典型的例子。 让我们通过允许指定根顶点v并以两种方式对小边界树的计数进行分层来略微概括问题:是否包括v,以及边界构成了多少边。

基本案例很简单。 没有边缘,因此有两个子树:一个包括v,另一个包括v,两者都没有边界边。 否则,让e = {v,w}成为v的边缘事件。实例看起来像这样。

|\         /|
| \   e   / |
|L v-----w R|
| /       \ |
|/         \|

递归地计算L的分层计数,其根据v和R以W为根。

包含v的子树由L中的子树组成,其包括v,加上可选的e和R中包含w的子树。 不包括v的子树由L中不包含v的子树或R中的子树(重复计算空树)组成。 这意味着我们可以通过将L的分层计数与R的分层计数进行卷积来获得分层计数。

以下是您的示例的工作原理。 我们选择root 1。

  e
1---2---3

我们选择e如图所示并递归。

1

包含-1的向量是[1],因为一个子树是{1},没有边界。 排除-1的向量是[1],因为一个子树是{},也没有边界。

2---3

我们像1所做的那样计算2和3.包含-2的向量是[1,1],因为{2,3}没有边界边,而{2}有1。 我们通过添加2的包含-2向量来获得此向量,由于新的边界边缘将[0,1]移位到包含2的向量2的卷积,包含-3向量用于3 ,[1,0]。 排除-2的向量是[1] + [1,1] - [1] = [1,1],其中[1,1]是移位的包含-3向量和排除-3向量的总和,减法是为了补偿重复计数{}。

现在,对于原始调用,为了得到包含1的向量,我们将[0,1],1的1的包含1向量移位到[1]与[1,1]的卷积,得到[ 1,2]。 要检查:{1,2,3}没有边界,{1}和{1,2}有一个边界边。 排除-1矢量是[1] + [1,2,1] - [1] = [1,2,1]。 要检查:{}没有边界,{2,3}和{3}有一个边界边,{2}有两个边界边。

这是David Eisenstat解决方案的python实现:

from sys import stdin
from numpy import *
from scipy import *

def roundup_pow2(x):
  """
  Round up to power of 2 (obfuscated and unintentionally faster :).
  """
  while x&(x-1):
    x = (x|(x>>1))+1
  return max(x,1)

def to_long(x):
    return long(rint(x))

def poly_mul(a,b):
  n = len(a) + len(b) - 1
  nr = roundup_pow2(n)
  a += [0L]*(nr-len(a))
  b += [0L]*(nr-len(b)) # pad with zeros to length n
  u = fft(a)
  v = fft(b)
  w = ifft(u*v)[:n].real             # ifft == inverse fft
  return map(to_long,w)

def pad(l,s) :
    return l+[0L]*(s-len(l))

def make_tree(l,x,y):
    l[x][y]=y
    l[x].pop(y)
    for child in l[x]:
        make_tree(l,child,x)

def cut_tree(l,x) :
    if len(l[x])==0:
        return [1L],[1L]
    y,_ = l[x].popitem()
    ai,ax=cut_tree(l,x)
    bi,bx=cut_tree(l,y)

    ci=[0L]+ai
    tmp=poly_mul(ai,bi)
    padlen=max(len(ci),len(tmp))
    ci=pad(ci,padlen)
    tmp=pad(tmp,padlen)
    ci=map(add,ci,tmp)

    cx=[0L]+bi
    padlen=max(len(cx),len(bx),len(ax))
    cx=pad(cx,padlen)
    bx=pad(bx,padlen)
    ax=pad(ax,padlen)
    tmp=pad([-1],padlen)
    cx=map(add,cx,bx)
    cx=map(add,cx,ax)
    cx=map(add,cx,tmp)

    return ci,cx



n,k = map(int,raw_input().split())
l=[{}]
for i in range(1,n+1):
    d={}
    l.append(d)
for i in range(1,n):
    x,y = map(int,raw_input().split())
    l[x][y]=y
    l[y][x]=x
make_tree(l,1,0)

i,x = cut_tree(l,1)
padlen=max(len(i),len(x))
i=pad(i,padlen)
x=pad(x,padlen)
combined=map(add,i,x)
sum=0L
for i in range(0,k+1) :
    sum+=combined[i]

print sum

让我们创建一个稍大的树,如下所示。

        1
      / | \
    2   3  \
       /    4 
      7    / \
          5   6

让我们为每个节点'a'定义函数F(a,k),其中'k'边缘从节点'a'和下面移除。 即如果从节点'a'中移除'k'边缘,则我们创建F(a,k)个子树。 (如果'a'不是root,则假定它连接到它的父级)。

例如在上面的树(F(4,1)= 2),因为我们通过删除'4'下面的2个边来创建2个树(我们假设4连接到父和子树(5)和(6)不计入F(4,1))

我们首先遍历并计算每个孩子的'F'。 然后使用孩子的F我们计算父母F.

对于所有k,叶节点的F(a,k)为'0'

对于非叶节点。

F(a,k)= SUM(F(child,k))+ Z

虽然可以递归地计算F(子,k)。

另一方面,通过找到一些孩子从k取ri边缘的所有组合来计算Z,使得SUM(ri)= k

以编程方式,这可以通过修复给定孩子的'j'边缘然后计算通过将'kj'边缘分配给其他孩子而创建的树的数量来完成。

例如在上面的树上

F(1, 3) = F(2, 3) + F(3, 3) + F(4, 3) +  // we pass k as-is to child  
      F(2,1)*F(3,1)*F(4,1) + F(2,1)*F(3,2) + F(2,1)*F(4,2) + //consume 1 edge by 2 and distribute 2 to other children
      F(2, 2)*F(3,1) + F(2,2)*F(4,1) + // consume 2 edges from node '2' and 1 for other children
      F(3,1)*F(4,2) 

如上所述,我们修复了节点2的“r”边缘,然后将“3-r”边缘分配给其他子节点。 我们继续为'1'的所有孩子做这件事。

另外,当我们从父节点分离节点时,我们创建子树。 例如,在我们计算F(1,3)的上述情况下,我们创建以下分离的树。 detached_tree + = F(2,2)+ F(3,2)+ F(4,2)
这里我们假设通过从父节点分离子节点来消耗一个边缘,并且在子节点中如果我们消耗'k-1'边缘,我们将创建F(子节点,k-1)子树。 这些树被计算并单独存储在detached_trees中。

一旦我们计算了所有节点的F(a,k)。

所有k'+'总节点的总子树是'SUM(F(root,k)) - 1'+ detached_trees。

我们在总数中添加“总节点数 - 1”。 这是因为当一个节点(根除外)与树分离时,它会创建两个缺少1个边的树。 当其中一棵树计入F(父级,1)时,另一棵树不计入任何地方,因此需要计算总数。

这是上述算法的C代码。 递归可以进一步优化。

#define MAX 51
/* We use the last entry of alist to store number of children of a given node */
#define NUM_CHILD(alist, node) (alist[node][MAX])
int alist[MAX][MAX+1] = {0};
long F[MAX][MAX]={0};
long detached_subtrees = 0;

/*
 *  We fix one of the child node for 'i' edges out of 'n', then we traverse
 *  over  the rest of the children to get 'n-i' edges, we do so recursivly.
 *  Note that if 'n' is 1, we can always build a subtree by detaching.
 */
long REST_OF_NODES_SUM(int node, int q, int n)
{
    long sum = 0, i, node2, ret = 0, nd;

    /* fix node2 and calcualte the subtree for rest of the children */
    for(nd = q; nd < NUM_CHILD(alist, node); nd++) {
            node2 = alist[node][nd];
            /* Consume 'i' edges and send 'n-i' for other children of node */
            for (i = 1; i < n ; i++) {
                    sum = REST_OF_NODES_SUM(node, nd + 1, n - i);
                    ret += (F[node2][i] * sum);
                    /* Add one for 'node2' getting detached from tree */
                    if (i == 1) { ret += sum; }
            }
            ret += F[node2][n];
            /* If only one edge is to be consumed, we detach 'node2' from the tree */
            if (n == 1) { ret++; }
    }

    return ret;
}

void get_counts(int N, int K, int node, int root)
{
    int child_node;
    int i, j, p, k;

    if (NUM_CHILD(alist, node) == 0) { return; }

    for(i = 0 ; i < NUM_CHILD(alist, node); i++) {
            child_node = alist[node][i];
            /* Do a recursive traversal of all children */
            get_counts(N, K, child_node, node);
            F[node][1] += (F[child_node][1]);
    }

    F[node][1] += NUM_CHILD(alist, node);

    for (k = 2; k <= K; k++) {
            for(p = 0; p < NUM_CHILD(alist, node); p++) {
                    child_node = alist[node][p];
                    F[node][k] += F[child_node][k];
                    /* If we remove this child, then we create subtrees in the child */
                    detached_subtrees += F[child_node][k-1];

                    /* Assume that 'child_node' is detached, find tree created by rest
                     * of children for 'k-j' edges */
                    F[node][k] += REST_OF_NODES_SUM(node, p + 1, k - 1);

                    /* Fix one child node for 'j' edges out of 'k' and traverse over the rest of
                     * children for 'k - j' edges */
                    for (j = 1; j < k ; j++) {
                            if (F[child_node][j]) F[node][k] += (F[child_node][j] * REST_OF_NODES_SUM(node, p + 1, k - j));
                    }
            }
    }
}


void remove_back_ref(int parent, int node)
{
    int c;
    for (c = 0; c < NUM_CHILD(alist, node); c++) {
            if (alist[node][c] == parent) {
                    if ((c + 1) == NUM_CHILD(alist, node)) {
                            NUM_CHILD(alist, node)--;
                            alist[node][c] = 0;
                    } else {
                            /* move last entry here */
                            alist[node][c] = alist[node][NUM_CHILD(alist, node)-1];
                            alist[node][NUM_CHILD(alist, node)-1] = 0;
                            NUM_CHILD(alist, node)--;
                    }
            }
    }
}

/* go to each child and remove back links */
void normalize(int node)
{
    int j, child;

    for (j = 0; j < NUM_CHILD(alist, node); j++) {
            child = alist[node][j];
            remove_back_ref(node, child);
            normalize(child);
    }
}

long cutTree(int N, int K, int edges_rows, int edges_columns, int** edges)
{
    int i, j;
    int node, index;
    long ret = 0;

    /* build an adjacency list from the above edges */
    for (i = 0; i < edges_rows; i++) {
            alist[edges[i][0]][NUM_CHILD(alist, edges[i][0])] = edges[i][1];
            alist[edges[i][1]][NUM_CHILD(alist, edges[i][1])] = edges[i][0];
            NUM_CHILD(alist, edges[i][0])++;
            NUM_CHILD(alist, edges[i][1])++;
    }

    /* get rid of the back links in children */
    normalize(1);
    get_counts(N, K, 1, 1);
    for (i = 1; i <= K; i++) { ret += F[1][i]; }
    /* Every node (except root) when detached from tree, will create one extra subtree. */
    ret += (N - 1);
    /* The subtrees created by detaching from parent */
    ret += detached_subtrees;
    /* Add two for empty and full tree */
    ret += 2;

    return ret;
}

main(int argc, char *argv[])
{
    int **arr;
    int ret, i, N, K, x, y;

    scanf("%d%d", &N, &K);
    arr = malloc((N - 1) * sizeof(int*));
    for (i = 0; i < (N - 1); i++) { arr[i] = malloc(2*sizeof(int)); }

    for (i = 0; i < N-1; i++) { scanf("%d%d", &x, &y); arr[i][0] = x; arr[i][1] = y; }

    printf("MAX %d ret %ld\n", MAX, cutTree(N, K, N-1, 2, arr));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM