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

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →