package index;

import java.util.HashSet;

public class INode {
	HashSet<Integer> E;
	INode L = null,R = null;
	
	public INode(HashSet<Integer> _E) {
		E = new HashSet<Integer>();
		E.addAll(_E);
	}
	public INode(HashSet<Integer> _E, INode _L, INode _R) {
		E = new HashSet<Integer>();
		E.addAll(_E);
		L = _L;
		R = _R;
	}
	
	@Override
	public String toString() {
		return E.toString();
	}
	
	public double UB(double[] w) {
		double res = 0;
		Double P = null;
		Double maxN = null;
		// compute P and maximum Negative
		for(int i: E) {
			if (w[i] >= 0){ // positive -> add it up
				if (null == P) P = 0.0;
				P += w[i];
			} else { // negative -> take max
				if (null == maxN){ 
					maxN = w[i];
				}
				else {
					if (maxN < w[i]) 
						maxN = w[i];
				}
			}
		}
		double l = (null == L)?0.0:L.UB(w);
		double r = (null == R)?0.0:R.UB(w);
		
		if (null != P) { 
			// if there is a positive connector 
			// return the connected score
			res = P + l + r;
		} else { // the connector is negative
			if (maxN == null) {
				return Math.max(l, r);
			} else if ((maxN + l < 0) || (maxN + r < 0)) {
				res = Math.max(l, r);
			} else {
				res = maxN + l + r;
			}
		}
		return res;
	}
}
