Answers to: TR1 - Editorialhttps://discuss.codechef.com/questions/4269/tr1-editorial<h1>PROBLEM LINKS</h1>
<p><a href="http://www.codechef.com/problems/TR1/">Practice</a><br>
<a href="http://www.codechef.com/MAY10/problems/TR1/">Contest</a></p>
<h1>DIFFICULTY</h1>
<p>EASY</p>
<p><strong>Solution</strong>: Tree traversal <strong>Complexity</strong>: O(N) </p>
<h1>EXPLANATION</h1>
<p>Consider the rooted tree T, with the 1 as the root. Now the required node C for a pair (A,B) is the lowest common ancestor of A and B in this tree. Direct implementation of a text book algorithm leads to a O(N^2logN) or a O(N^2) solution to the problem depending on whether its O(logN) lca or O(1) lca algorithm. Since N <= 1e4, and there are 25 test cases, we need something better than O(N^2) to pass.</p>
<p>Consider a non-leaf node u in the tree. Now we have to compute the number of pairs of nodes whose lca is u. Let u have k children c1,c2,...,ck. Now the subtree rooted at each child c _ i is independent. For all combinations of vertices (a,b) with a in c _ i and b in c _ j , i ! = j , have u as their lca. So we must find 2 * (|c1| * |c2| + |c1| * |c3| + .. |c1| * |ck| + |c2| * |c3| + |c2| * c4 + ... + |ck| * |ck-1|) , ie. all C(k,2) combinations of |c _ i|s where |c _ i| represents the number of nodes in the subtree rooted at c _ i. The two factor is because each pair (a,b) appears in the matrix twice as (a,b) and (b,a).</p>
<p>Now to compute this, there are multiple approaches:</p>
<p>1.The sum is equal to (sum of |c _ i|)^2 minus sum of |c _ i|^2</p>
<p>An alternate and neater approach to compute this sum is to keep the partial sum of c _ i's until a point and to multiply the next c value to the present partial sum. ie.</p>
<p>long long partialsum = 0 , res = 0;<br>
for ( int i=1;i<=k;i++ )<br>
{<br>
res += partialsum * C[i];<br>
partialsum += C[i];<br>
}<br>
</p>
<p>res * 2 is the required sum. Now all the pairs of the form (u,some node in subtree rooted at u) are not considered as we are only considering the pairs among the children of u. So we must add twice the size of subtree rooted at u (excluding u) to the solution. (u,u) also appears in the matrix, so this is another entry for Im(u). So Im(u) = res * 2 + 2 * (size of subtree rooted at u) + 1. </p>
<p><strong>Note:</strong> If partialsum is initialized to 1, then the subtree term can be ignored completely, since the size of subtree rooted at u excluding u is equal to sum of |c _ i|s.</p>
<p>Once the Im values are calculated, the required sum S can easily be computed. </p>enMon, 21 Jan 2019 22:20:41 -0000