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

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →