Cut the Tree


Problem Statement :


There is an undirected tree where each vertex is numbered from 1 to n, and each contains a data value. The sum of a tree is the sum of all its nodes' data values. If an edge is cut, two smaller trees are formed. The difference between two trees is the absolute value of the difference in their sums.

Given a tree, determine which edge to cut so that the resulting trees have a minimal difference between them, then return that difference.


The minimum absolute difference is .

Note: The given tree is always rooted at vertex .

Function Description

Complete the cutTheTree function in the editor below.

cutTheTree has the following parameter(s):

int data[n]: an array of integers that represent node values
int edges[n-1][2]: an 2 dimensional array of integer pairs where each pair represents nodes connected by the edge
Returns

int: the minimum achievable absolute difference of tree sums
Input Format

The first line contains an integer , the number of vertices in the tree.
The second line contains  space-separated integers, where each integer  denotes the  data value, .
Each of the  subsequent lines contains two space-separated integers  and  that describe edge  in tree .



Solution :



title-img


                            Solution in C :

In  C  :






#include <stdio.h>
#include <stdlib.h>

int N, E;
int first_edge[101000];
int edges[201000][2];
int score[101000];
int cache[201000][2];

int cmp_ints(const void *a, const void *b)
{
	return *(const int *)a - *(const int *)b;
}

int get_scoresum(int edge, int side)
{
	if (cache[edge][side] != 0)
		return cache[edge][side];
	int u = edges[edge][side];
	int scoresum = score[u];
	for (int e = first_edge[u]; e < E && edges[e][0] == u; ++e) {
		int v = edges[e][1];
		if (v == edges[edge][1-side])
			continue;
		scoresum += get_scoresum(e, 1);
	}
	cache[edge][side] = scoresum;
	return scoresum;
}

int main(void)
{
	scanf("%d", &N);
	for (int u = 1; u <= N; ++u)
		scanf("%d", &score[u]);
	for (int i = 0; i < N-1; ++i) {
		int u, v;
		scanf("%d %d", &u, &v);
		edges[E][0] = u;
		edges[E][1] = v;
		E += 1;
		edges[E][0] = v;
		edges[E][1] = u;
		E += 1;
	}
	qsort(edges, E, sizeof edges[0], cmp_ints);
	for (int e = E-1; e >= 0; --e)
		first_edge[edges[e][0]] = e;

	int best_cut = 1234567890;
	for (int e = 0; e < E; ++e) {
		int t1 = get_scoresum(e, 0);
		int t2 = get_scoresum(e, 1);
		int cut = abs(t1 - t2);
		if (cut < best_cut)
			best_cut = cut;
	}
	printf("%d\n", best_cut);

	return 0;
}
                        


                        Solution in C++ :

In  C++  :





#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <limits>
#include <cstring>
#include <string>
using namespace std;
 
#define pairii pair<int, int>
#define llong long long
#define pb push_back
#define sortall(x) sort((x).begin(), (x).end())
#define INFI  numeric_limits<int>::max()
#define INFLL numeric_limits<llong>::max()
#define INFD  numeric_limits<double>::max()
#define FOR(i,s,n) for (int (i) = (s); (i) < (n); (i)++)
#define FORZ(i,n) FOR((i),0,(n))

const int MAXN = 100005;
int w[MAXN];
vector<int> adj[MAXN];
set<int> v;
int n, res, total;

struct Node {
    Node() {
        pr = NULL;
        w = 0;
    }
    Node* pr;
    vector<Node*> cl;
    int w;
    int idx;
};

Node* root;

void build(Node* nd) {
    int idx = nd->idx;
    v.insert(idx);
    nd->w += w[idx];
    for (int x:adj[idx]) {
        if (v.find(x) == v.end()) {
            Node* u = new Node;
            u->pr = nd;
            u->idx = x;
            nd->cl.pb(u);
            build(u);
            nd->w += u->w;
        }
    }
}

void dfs(Node* nd) {
    int idx = nd->idx;
    if (nd->pr != NULL) {
        res = min(res, abs(total-2*nd->w));
    }
    for (Node* u : nd->cl) {
        dfs(u);
    }
}

void solve() {
    scanf("%d", &n);
    FORZ(i,n) scanf("%d", w+i);
    FORZ(i,n-1) {
        int a,b;
        scanf("%d %d", &a, &b);
        a--; b--;
        adj[a].pb(b);
        adj[b].pb(a);
    }
    root = new Node;
    root->idx = 0;
    build(root);
    total = root->w;
    res = INFI;
    dfs(root);
    printf("%d\n", res);
}
 
int main() {
#ifdef DEBUG
    freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
#endif
    solve();
    return 0;
}
                    


                        Solution in Java :

In  Java :







import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class Solution {
	static InputStream is;
	static PrintWriter out;
	static String INPUT = "";
	
	static void solve()
	{
		int n = ni();
		int[] a = na(n);
		int[] from = new int[n-1];
		int[] to = new int[n-1];
		for(int i = 0;i < n-1;i++){
			from[i] = ni()-1;
			to[i] = ni()-1;
		}
		int[][] g = packU(n, from, to);
		int[][] pars = parents3(g, 0);
		int[] par = pars[0], ord = pars[1];
		int[] dp = new int[n];
		for(int i = n-1;i >= 0;i--){
			int cur = ord[i];
			dp[cur] = a[cur];
			for(int e : g[cur]){
				if(par[cur] != e){
					dp[cur] += dp[e];
				}
			}
		}
		
		int ret = 999999999;
		for(int i = 1;i < n;i++){
			ret = Math.min(ret, Math.abs(dp[i]-(dp[0]-dp[i])));
		}
		out.println(ret);
	}
	
	public static int[][] parents3(int[][] g, int root) {
		int n = g.length;
		int[] par = new int[n];
		Arrays.fill(par, -1);

		int[] depth = new int[n];
		depth[0] = 0;

		int[] q = new int[n];
		q[0] = root;
		for(int p = 0, r = 1;p < r;p++){
			int cur = q[p];
			for(int nex : g[cur]){
				if(par[cur] != nex){
					q[r++] = nex;
					par[nex] = cur;
					depth[nex] = depth[cur] + 1;
				}
			}
		}
		return new int[][] { par, q, depth };
	}
	
	static int[][] packU(int n, int[] from, int[] to) {
		int[][] g = new int[n][];
		int[] p = new int[n];
		for(int f : from)
			p[f]++;
		for(int t : to)
			p[t]++;
		for(int i = 0;i < n;i++)
			g[i] = new int[p[i]];
		for(int i = 0;i < from.length;i++){
			g[from[i]][--p[from[i]]] = to[i];
			g[to[i]][--p[to[i]]] = from[i];
		}
		return g;
	}
	
	public static void main(String[] args) throws Exception
	{
		long S = System.currentTimeMillis();
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		
		solve();
		out.flush();
		long G = System.currentTimeMillis();
		tr(G-S+"ms");
	}
	
	private static boolean eof()
	{
		if(lenbuf == -1)return true;
		int lptr = ptrbuf;
		while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
		
		try {
			is.mark(1000);
			while(true){
				int b = is.read();
				if(b == -1){
					is.reset();
					return true;
				}else if(!isSpaceChar(b)){
					is.reset();
					return false;
				}
			}
		} catch (IOException e) {
			return true;
		}
	}
	
	private static byte[] inbuf = new byte[1024];
	static int lenbuf = 0, ptrbuf = 0;
	
	private static int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}
	
	private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
	
	private static double nd() { return Double.parseDouble(ns()); }
	private static char nc() { return (char)skip(); }
	
	private static String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}
	
	private static char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}
	
	private static char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}
	
	private static int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}
	
	private static int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private static long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
                    


                        Solution in Python : 
                            
In  Python3 :







from collections import deque

class Node(object):
    def __init__(self,index,value):
        self.index = index
        self.value = value
        self.children = set()
        self.parent = None
        self.value_of_subtree = 0

N = int(input())
node_at_index = [Node(index,value) for index,value in enumerate(map(int,input().split()))]
for a, b in (map(int,input().split()) for _ in range(N-1)):
    node_at_index[a-1].children.add(node_at_index[b-1])
    node_at_index[b-1].children.add(node_at_index[a-1])

root = node_at_index[0]
ordered_nodes = [root]
q = deque([root])
while q:
    n = q.popleft()
    for c in n.children:
        c.children.remove(n)
        c.parent = n
        q.append(c)
        ordered_nodes.append(c)
ordered_nodes.reverse()
'at this point, ordered_nodes are ordered from leaf to root'
        
for n in ordered_nodes:
    n.value_of_subtree = n.value + sum(c.value_of_subtree for c in n.children)
    
total = root.value_of_subtree
best = N * 2000
for n in ordered_nodes:
    for c in n.children:
        tree_a = c.value_of_subtree
        tree_b = total - tree_a
        dif = abs(tree_a - tree_b)
        if dif < best:
            best = dif
            
print(best)
                    


View More Similar Problems

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →