【问题标题】:Recursive Tree Algorithm to sum total cost of a project递归树算法总结项目的总成本
【发布时间】:2013-06-26 11:28:50
【问题描述】:

有没有人有解决这个问题的想法,但只使用通用树?

我需要对所有节点求和,但要尊重边缘值。

如果两个节点之间的边 > 1 比子树的成本最大可以乘以整个子树。

解决方案必须使用树算法

谢谢

http://oi39.tinypic.com/24buik7.jpg

【问题讨论】:

  • 到目前为止你有什么收获?
  • 在您发布的图片中是一个有向无环图 (DAG),它不是一棵树。

标签: c# .net algorithm tree binary-tree


【解决方案1】:

假设您有一个对象Node,包含它自己的cost 和一组传出edges,每个都有一个权重,您可以执行以下操作。 (注意我假设你有一个 DAG,正如 pkacprzak 所提到的,因为你发布的图片没有显示树)

class Edge
{
    public int Weight { get; set; }
    public Node Start { get; set; }
    public Node End { get set; }
}

class Node
{
    private int cost;
    private IEnumerable<Edge> edges;

    // ...

    public int Cost()
    {
        int totalCost = cost;

        foreach (var edge in edges)
        {
            totalCost += edge.Weight * edge.End.Cost();
        }

        return totalCost;
    }
}

您应该在 DAG 的源(即没有传入边的节点)上调用 Cost。如果您有多个来源,则取决于您想要实现的目标。

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 2013-02-09
    • 2015-02-09
    • 2011-02-15
    • 2022-10-06
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多