📌  相关文章
📜  通过将每个节点包含在 N 元树的一个段中,每个节点可能的最大和

📅  最后修改于: 2021-09-17 16:09:11             🧑  作者: Mango

给定一个包含N 个节点的 N 元树和一个表示节点权重的数组权重 [ ] ,该权重可以是正数负数,每个节点的任务是打印包括当前节点在内的一系列节点可能的最大和.

例子:

Input: N = 7
weight[] = [-8, 9, 7, -4, 5, -10, -6]
N-Ary tree:
                -8
               /   \
              9      7
            /  \    / 
          -4    5 -10
          /
        -6
Output: 13 14 13 10 14 3 4

Explanations:
Node -8: [-8 + 9 + 7 + 5] = 13
Node 9: [9 + 5] = 14
Node 3: [7 + (-8) + 9 + 5] = 13
Node 4: [-4 + 9 + 5] = 10
Node: [5 + 9] = 14
Node 6: [-10 + 7 + (-8) + 9 + 5] = 3
Node 7: [-6 + (-4) + 9 + 5] = 4

Input: N = 6
weight[] = [2, -7, -5, 8, 4, -10]
N-Ary tree:
                 2
               /   \
             -7    -5
             / \     \
            8   4    -10
Output: 7 7 2 8 7 -8

方法:这个问题可以通过应用两个 DFS 使用 Dp on Trees 技术解决。

  • 应用第一个 DFS 来存储每个节点可能的最大总和,方法是将它们包含在具有各自后继的序列中。将最大可能总和存储在dp1[] 中。大批。
  • 可以通过以下方式获得第一个 DFS 中每个节点的最大可能值:
  • 执行第二个Dfs以更新 dp1[] 中每个节点的最大总和,方法是将它们也包含在它们的祖先的序列中。每个节点的 dp2[] 中存储的最大值是所需的答案。
  • 可以通过以下方式获得第二个 DFS 中每个节点的最大可能值:

请参阅图示说明以更好地理解:

下面是上述方法的实现:

C++
// C++ program to calculate the maximum
// sum possible for every node by including
// it in a segment of the N-Ary Tree
#include 
using namespace std;
 
// Stores the maximum
// sum possible for every node
// by including them in a segment
// with their successors
int dp1[100005];
 
// Stores the maximum
// sum possible for every node
// by including them in a segment
// with their ancestors
int dp2[100005];
 
// Store the maximum sum
// for every node by
// including it in a
// segment with its successors
void dfs1(int u, int par,
          vector g[],
          int weight[])
{
 
    dp1[u] = weight[u];
    for (auto c: g[u]) {
        if (c != par) {
            dfs1(c, u, g, weight);
            dp1[u] += max(0, dp1);
        }
    }
}
 
// Update the maximum sums
// for each node by including
// them in a sequence with
// their ancestors
void dfs2(int u, int par,
          vector g[],
          int weight[])
{
    // Condition to check,
    // if current node is not root
    if (par != 0) {
        int maxSumAncestors = dp2[par]
                              - max(0, dp1[u]);
        dp2[u] = dp1[u] + max(0,
                              maxSumAncestors);
    }
    for (auto c: g[u]) {
        if (c != par) {
            dfs2(c, u, g, weight);
        }
    }
}
 
// Add edges
void addEdge(int u, int v, vector g[])
{
    g[u].push_back(v);
    g[v].push_back(u);
}
 
// Function to find the maximum
// answer for each node
void maxSumSegments(vector g[],
                    int weight[],
                    int n)
{
 
    // Compute the maximum sums
    // with successors
    dfs1(1, 0, g, weight);
 
    // Store the computed maximums
    for (int i = 1; i <= n; i++) {
        dp2[i] = dp1[i];
    }
 
    // Update the maximum sums
    // by including their
    // ancestors
    dfs2(1, 0, g, weight);
}
 
// Print the desired result
void printAns(int n)
{
    for (int i = 1; i <= n; i++) {
        cout << dp2[i] << " ";
    }
}
 
// Driver Program
int main()
{
 
    // Number of nodes
    int n = 6;
    int u, v;
 
    // graph
    vector g[100005];
 
    // Add edges
    addEdge(1, 2, g);
    addEdge(1, 3, g);
    addEdge(2, 4, g);
    addEdge(2, 5, g);
    addEdge(3, 6, g);
    addEdge(4, 7, g);
 
    // Weight of each node
    int weight[n + 1];
    weight[1] = -8;
    weight[2] = 9;
    weight[3] = 7;
    weight[4] = -4;
    weight[5] = 5;
    weight[6] = -10;
    weight[7] = -6;
 
    // Compute the max sum
    // of segments for each
    // node
    maxSumSegments(g, weight, n);
 
    // Print the answer
    // for every node
    printAns(n);
 
    return 0;
}


Python3
# Python3 program to calculate the maximum
# sum possible for every node by including
# it in a segment of the N-Ary Tree
  
# Stores the maximum
# sum possible for every node
# by including them in a segment
# with their successors
dp1 = [0 for i in range(100005)]
  
# Stores the maximum sum possible
# for every node by including them
# in a segment with their ancestors
dp2 = [0 for i in range(100005)]
  
# Store the maximum sum for every
# node by including it in a
# segment with its successors
def dfs1(u, par, g, weight):
  
    dp1[u] = weight[u]
     
    for c in g[u]:
        if (c != par):
            dfs1(c, u, g, weight)
            dp1[u] += max(0, dp1)
         
# Update the maximum sums
# for each node by including
# them in a sequence with
# their ancestors
def dfs2(u, par, g, weight):
 
    # Condition to check,
    # if current node is not root
    if (par != 0):
        maxSumAncestors = dp2[par] - max(0, dp1[u])
        dp2[u] = dp1[u] + max(0, maxSumAncestors)
     
    for c in g[u]:
        if (c != par):
            dfs2(c, u, g, weight)
             
# Add edges
def addEdge(u, v, g):
 
    g[u].append(v)
    g[v].append(u)
 
# Function to find the maximum
# answer for each node
def maxSumSegments(g, weight, n):
  
    # Compute the maximum sums
    # with successors
    dfs1(1, 0, g, weight)
  
    # Store the computed maximums
    for i in range(1, n + 1):
        dp2[i] = dp1[i]
     
    # Update the maximum sums
    # by including their
    # ancestors
    dfs2(1, 0, g, weight)
 
# Print the desired result
def printAns(n):
 
    for i in range(1, n):
        print(dp2[i], end = ' ')
         
# Driver code
if __name__=='__main__':
     
    # Number of nodes
    n = 7
    u = 0
    v = 0
  
    # Graph
    g = [[] for i in range(100005)]
  
    # Add edges
    addEdge(1, 2, g)
    addEdge(1, 3, g)
    addEdge(2, 4, g)
    addEdge(2, 5, g)
    addEdge(3, 6, g)
    addEdge(4, 7, g)
  
    # Weight of each node
    weight=[0 for i in range(n + 1)]
    weight[1] = -8
    weight[2] = 9
    weight[3] = 7
    weight[4] = -4
    weight[5] = 5
    weight[6] = -10
    weight[7] = -6
  
    # Compute the max sum
    # of segments for each
    # node
    maxSumSegments(g, weight, n)
  
    # Print the answer
    # for every node
    printAns(n)
 
# This code is contributed by pratham76


输出:
13 14 13 10 14 3