using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication9 { class AncientTree { List p = null; List h = null; List weight = null; List sumWeightUp = null; public AncientTree(int[] p, int[] w) { if (p.Length != w.Length) { throw new Exception(); } int n = p.Length; this.p = new List(p); this.weight = new List(w); this.h = new List(n); this.sumWeightUp = new List(n); for (int i = 0; i < n; ++i) { h.Add(-1); sumWeightUp.Add(-1); } Action precalc = null; precalc = (int v) => { if (h[v] >= 0) return; if (p[v] == -1) { h[v] = 0; sumWeightUp[v] = w[v]; } else { precalc(p[v]); h[v] = h[p[v]] + 1; sumWeightUp[v] = sumWeightUp[p[v]] + w[v]; } }; for (int i = 0; i < n; ++i) precalc(i); precalc = null; } public void Add(int p, int weight) { int v = this.p.Count; this.p.Add(p); this.weight.Add(weight); int sumUp = weight; int h = 0; if (p != -1) { sumUp += this.h[p] + 1; sumUp += sumWeightUp[p]; } sumWeightUp.Add(sumUp); this.h.Add(h); } public int getH(int v) { return h[v]; } public int getW(int v) { return weight[v]; } public int getP(int v) { return p[v]; } public int getWeightUp(int v) { return sumWeightUp[v]; } public void print() { Console.WriteLine("P\tH\tW\tSumW"); for (int i = 0; i < p.Count; ++i) Console.WriteLine("{0}\t{1}\t{2}\t{3}", p[i], h[i], weight[i], sumWeightUp[i]); } } class Program { static void Main(string[] args) { int[] p = { 1, -1, 1, 1, 2, 3, 0, 0 }; int[] w = { 4, 5, 8, 74, 45, 1, 2, 5 }; AncientTree tr = new AncientTree(p, w); tr.Add(5, 15); tr.print(); } } }