Under construction

Still being built. Things may change

Tree

Time limit2sMemory limit1024 MB

Summary
Given a tree with integers on its nodes, pick two non-empty connected subgraphs with no shared node and no connecting edge, maximizing the total of their node values.
Level

Medium6 of 10

Topics
Tree, Dynamic programming
Solved
No attempts yet

Problem

A tree T=(V,E)T = (V, E) has NN nodes. Each node has one integer written on it, and the integers can be negative. Find two subgraphs Ta=(Va,Ea)T_a = (V_a, E_a) and Tb=(Vb,Eb)T_b = (V_b, E_b) of TT that satisfy the following conditions.

  • Va≠∅V_a \ne \emptyset, Vb≠∅V_b \ne \emptyset
  • TaT_a and TbT_b are each connected graphs.
  • Va∩Vb=∅V_a \cap V_b = \emptyset
  • No edge in EE connects a node in VaV_a with a node in VbV_b.
  • The sum of the integers on the nodes in VaV_a plus the sum of the integers on the nodes in VbV_b is maximized.

The figure below shows an example. T=({0,1,2,3,4,5,6},{(0,1),(0,2),(2,3),(2,4),(4,6),(5,6)})T = (\{0,1,2,3,4,5,6\}, \{(0, 1), (0,2), (2, 3), (2,4), (4,6), (5,6)\}).

The number on each node is its node number, and the value inside the node is the integer written on it. Several choices of TaT_a and TbT_b satisfy the conditions. Taking Va={0,2,3},Vb={5,6}V_a=\{0,2,3\}, V_b=\{5,6\} gives the maximum total of {3+(−1)+4}+{5+3}=14\{3+(-1)+4\} + \{5+3\} = 14. No other choice gives a value greater than 1414.

Function to implement

You need to write the following function.

long long findSum( int N, int C[], int Node1[], int Node2[] );

This function is called exactly once. The input is passed as arguments, and the return value is the answer. NN is the number of nodes. The nodes are numbered from 00 to N−1N-1. For 0≤i≤N−10 \le i \le N-1, the node numbered ii has the value C[i]C[i]. For 0≤i≤N−20 \le i \le N-2, the node numbered Node1[i]Node1[i] and the node numbered Node2[i]Node2[i] are joined by an edge.

Constraints

  • −109≤Ci≤109-10^9 \le C_i \le 10^9
  • 3≤N≤500 0003 \le N \le 500\,000

Examples1

  1. Example 1

    Input
    7
    3 -5 -1 4 2 5 3
    0 1
    0 2
    2 3
    2 4
    4 6
    5 6
    
    Expected output
    14