Problem Statement
You are given an undirected tree with n vertices numbered 0 through n-1.
For each i between 0 and n-2, inclusive, the vertices (i+1) and pre[i] are connected by an edge.
We ensure pre[i] < i+1, so the edges are guaranteed to form a tree.
A cycle graph is an undirected graph with n vertices and n edges in which the edges form a single cycle through all vertices. Formally, a graph with n vertices and n edges is a cycle graph if there exists a permutation p[0], p[1],..., p[n-1] of its vertices such that the n edges are the edges (p[0],p[1]), (p[1],p[2]), (p[2],p[3]), ..., (p[n-2],p[n-1]), and (p[n-1],p[0]).
You want to transform the given tree into an arbitrary cycle graph by adding and/or removing edges. Removing the edge (i+1,pre[i]) costs costE[i]. Each vertex x has an associated weight costV[x]. The cost of adding a new edge (x,y) is costV[x]+costV[y]. The edges added in this way cannot be removed. Note that all the edges are undirected.
You are given the following int[]s:
A cycle graph is an undirected graph with n vertices and n edges in which the edges form a single cycle through all vertices. Formally, a graph with n vertices and n edges is a cycle graph if there exists a permutation p[0], p[1],..., p[n-1] of its vertices such that the n edges are the edges (p[0],p[1]), (p[1],p[2]), (p[2],p[3]), ..., (p[n-2],p[n-1]), and (p[n-1],p[0]).
You want to transform the given tree into an arbitrary cycle graph by adding and/or removing edges. Removing the edge (i+1,pre[i]) costs costE[i]. Each vertex x has an associated weight costV[x]. The cost of adding a new edge (x,y) is costV[x]+costV[y]. The edges added in this way cannot be removed. Note that all the edges are undirected.
You are given the following int[]s:
- The int[] costV with n elements that contains the weight of each vertex. Remember that these weights are used to compute the costs of adding new edges.
- The int[] pre with n-1 elements that describes the shape of the tree.
- The int[] costE with n-1 elements: the costs of removing the edges described by pre.
Definition
- Class:
- TreeAndCycle
- Method:
- minimize
- Parameters:
- int[], int[], int[]
- Returns:
- int
- Method signature:
- int minimize(int[] costV, int[] pre, int[] costE)
- (be sure your method is public)
Constraints
- n will be between 3 and 100, inclusive.
- costV will contain exactly n elements.
- pre will contain exactly n-1 elements.
- For each valid i, 0 <= pre[i] < i+1 holds.
- costE will contain exactly n-1 elements.
- Elements of costV and costE will be between 1 and 10,000, inclusive.
Examples
{7,2,5,8}{0,1,2}{6,4,3}Returns: 15
This graph is a path with edges (0,1),(1,2),(2,3). An optimal solution is to add edge (0,3) to make it a cycle. The cost is costV[0] + costV[3] = 15.{100,5,9,8}{0,0,0}{6,2,2}Returns: 32
An optimal solution is to remove edge (0,3), and add edges (1,3), (2,3).{10,20,30,40,50,60,70,80,90}{0,1,2,2,3,4,5,7}{5,15,25,35,45,55,65,75}Returns: 205