Problem Desrcription
Shil likes to play with trees a lot.He is playing with an undirected tree containing N nodes.He wants to find out total number of unordered triplets (A,B,C) such that A is not connected to B, B is not connected to C and A is not connected to C by a direct edge (No two of A, B, C are mutually connected). Since he doesn't like to play with this alone , he asks for your help.
Input
The first line of each test case contains a single integer N denoting the number of nodes.
Next N - 1 lines consists of two integers u and v describing an edge from u to v
Output
Output a single line containing total number of triplets.
Constraints
1 ≤ N ≤ 10^5
1 ≤ u, v ≤ N
Example
Input:
5
1 2
1 3
3 4
2 5
Output:
1
Explanation
The only possible triplet is (1,4,5)
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to compute number of unordered triples of distinct nodes (A,B,C) such that no two are adjacent (i.e., there is no direct edge between any pair). Equivalent: the three nodes form an independent set of size 3 in the tree. So we need to count the number of independent triples (size-3 independent sets) in a tree with N up to 10^5.
We need to count number of triples of distinct vertices with no edges among them. Since tree is acyclic graph, this is a combinatorial count. Could use inclusion-exclusion or tree DP.
One approach: total number of triples = C(N,3) minus triples that have at least one edge among them. But counting triples with at least one edge is tricky because edges may be overlapping. Better to count independent sets directly.
Alternatively, we can think: In a tree, for any three vertices, they may be arranged such that there are edges among some. Since tree is bipartite, independent sets of size 3 might be counted by summing over something.
But perhaps easier: Use DP to count number of independent sets of size 3 in a tree. Classic DP: For each node, we compute dp[v][s] = number of independent sets in subtree rooted at v that include v? Actually we want global count of independent sets of size exactly 3. Tree DP can count using DP on trees with states for whether node is selected or not, and number of selected nodes so far.
Define DP:
For each node v (rooted arbitrarily, say 1), we compute two arrays:
f[v][k]: number of independent sets of size k in the subtree of v, where v is NOT selected.
g[v][k]: number of independent sets of size k in the subtree of v, where v IS selected.
We need only up to k=3 (since N large but k small). Complexity O(N * 3^2?) Actually merging children one by one: For each node, we combine children's DP, using knapsack style merging. Since k ≤ 3, merging is O(deg * constant). So overall O(N).
Let's outline:
Initialize for leaf v:
f[v][0] = 1
f[v][1] = 0? Actually if v not selected, we can select up to size 1 from its subtree? But subtree is just v: only set is empty (size 0). So f[v][0]=1, f[v][1]=0 (since cannot select a node if v not selected? Wait, not selected, but we can select children? Leaf has no children, so only possible independent set is empty. So f[v][0]=1, f[v][k>0]=0.
g[v][0] = 0? Actually g[v][k] is number of independent sets that include v. For leaf, if v selected, then set size is 1, so g[v][1]=1. g[v][0] is 0, g[v][>1] =0.
Now for internal node v with children u1...um (since tree is undirected, we root it, consider only children). We need to compute new f and g from children's f and g.
When v is NOT selected, any combination from children's subtrees can be taken, but the selections must be independent; since v is not selected, there is no restriction across children (they are independent because the only connection between children is through v, and v not selected so they don't interfere). However, note that we must ensure we don't select v, but we can select any independent sets from each child's subtree; the child's DP already respects that its root may be selected or not, but selections from different children are independent. So we combine children via convolution.
Specifically, we start with a temporary array cur_f representing DP for processed children, initially cur_f[0]=1 (empty). For each child u, we consider the contributions from u's subtree: The total ways for child u (given that v is not selected) is: total_u[k] = f[u][k] + g[u][k]. Because if v is not selected, u can be either selected or not, as long as the independent set condition holds within child's subtree; there's no additional restriction because edge (v,u) is not a conflict if u is selected? Wait: If u is selected, then v cannot be selected (since they are adjacent). But we are in case v is NOT selected, so it's fine. So indeed, from child u, we can take any independent set from its subtree, regardless of whether u is selected, because v is not selected, so edge (v,u) does not cause conflict. So total_u = f[u] + g[u] (pointwise). So for merging for f[v], we do knapsack: cur_f new[ k ] = sum_{i=0..min(k,3)} cur_f[ i ] * total_u[ k - i ].
After processing all children, we set f[v] = cur_f.
When v IS selected, we cannot select any child that is selected (since edge conflict). So for each child u, the allowed independent sets are those where u is NOT selected (i.e., f[u]). Also we can include empty from child. So total_u_selected = f[u] (since g[u] not allowed). Also we need to include v itself as one selected node. So we compute a DP for the subtree when v is selected: start cur_g with size=1 because we already selected v? Actually we need to count sets that include v. So we can initialize cur_g[0]=1 (representing no selections from children yet) but then after merging children, we will shift by 1 to account for v. Alternatively, we can initialize cur_g[0]=1, merge children using total_u = f[u] (only not selected). Then after all children, g[v][k] = cur_g[k-1] for k>=1 (since we add v). Actually careful: cur_g after merging children gives number of ways to choose some independent set from children (all not containing selected nodes adjacent to v) of a certain size. The total independent set includes v, so the total size = (size from children) + 1. So if after merging we have ways for size i from children, then g[v][i+1] = that number.
So algorithm:
Root the tree at 1, build adjacency list, do DFS (recursive or iterative) with parent to avoid revisiting.
For each node v, initialize DP arrays of length 4 (0..3) with zeros.
Process children (neighbors except parent):
For f[v] (v not selected): total from child u is tot_u = add(f[u], g[u]) element-wise (cap at 3? we can just add up to 3). Merge.
We'll need to implement convolution limited to 3: For two arrays a (size up to 3) and b (size up to 3), their convolution c[k] = sum_{i=0..k} a[i]*b[k-i]. Since max k=3, we can just compute manually.
For f[v], start cur = [1,0,0,0]. For each child: let child_tot = [ f[u][0]+g[u][0], f[u][1]+g[u][1], f[u][2]+g[u][2], f[u][3]+g[u][3] ]. Then new_cur = convolution(cur, child_tot) truncated at 3. After all children, f[v] = cur.
For g[v] (v selected): we only allow child's selections where child not selected, i.e., f[u]. So start cur_g = [1,0,0,0] (no children processed). For each child: child_only = f[u] (array). Then new_cur_g = convolution(cur_g, child_only) truncate at 3. After all children, for i from 0..2 (since i+1 <=3), set g[v][i+1] = cur_g[i]. Actually cur_g[i] is ways to pick i nodes from children. So g[v][i+1] = cur_g[i] for i=0,1,2, and also possibly i=3? But max total nodes = 3, if children pick 3 nodes and we add v would be 4, we ignore because we only care up to 3. So we only set for i such that i+1 <= 3 => i <=2. So g[v][1] = cur_g[0], g[v][2] = cur_g[1], g[v][3] = cur_g[2]. The rest g[v][0]=0.
At the end, the total number of independent sets of size 3 in the whole tree is f[root][3] + g[root][3] (since root either selected or not). That's the answer.
Check on example:
N=5, edges: 1-2,1-3,3-4,2-5. Let's root at 1.
Compute leaves: nodes 4,5,2? Actually 2 has child 5? We'll root at 1: children of 1: 2,3. Node 2 has child 5 (since parent 1). Node 3 has child 4. So leaves: 4 and 5.
For g[2]: start cur_g=[1,0,0,0]. child5 only f5 = [1,0,0,0]. conv: new = same [1,0,0,0]. Then g2[1] = cur_g[0]=1; g2[2]=cur_g[1]=0; g2[3]=cur_g[2]=0. So g2 = [0,1,0,0].
Node 3: children: 4.
First compute f3: cur=[1,0,0,0]. child4 tot4 = f4+g4 = [1,1,0,0]. conv => f3 = [1,1,0,0] same as above.
g3: cur_g=[1,0,0,0]. child4 f4 = [1,0,0,0]. conv => cur_g remains [1,0,0,0]. Then g3[1]=1, g3[2]=0, g3[3]=0 => g3=[0,1,0,0].
Node 1: children: 2 and 3.
First compute f1 (v not selected). start cur = [1,0,0,0].
Child2: tot2 = f2+g2 = f2=[1,1,0,0]; g2=[0,1,0,0]; sum = [1,2,0,0].
Convolution: new_cur after child2:
k=0: cur[0]tot2[0]=11=1
k=1: cur[0]tot2[1] + cur[1]tot2[0] =12+01=2
k=2: cur[0]tot2[2] + cur[1]tot2[1] + cur[2]tot2[0] =10+02+01=0
k=3: 0
So cur = [1,2,0,0].
Now child3: tot3 = f3+g3 = [1,1,0,0] + [0,1,0,0] = [1,2,0,0].
Convolution cur (current) with tot3:
cur = [1,2,0,0]; tot3 = [1,2,0,0]
Compute new:
k=0: 11 =1
k=1: 12 + 21 = 2+2=4
k=2: 10 + 22 + 01 = 0+4+0=4
k=3: 10 + 20 + 02 + 01 =0 (actually also terms with indices: i=3? but we have only up to 3; formula sum i=0..3 cur[i]tot3[3-i]; i=0: cur0tot3[3]=10=0; i=1: cur1tot3[2]=20=0; i=2: cur2tot3[1]=02=0; i=3: cur3tot3[0]=01=0 => 0)
But wait compute k=2 correctly: 10? Actually tot3[2] is 0, so i=0 term 1*0=0; i=1 term cur[1]tot3[1] =22=4; i=2 term cur[2]tot3[0]=01=0 => sum 4. Good.
So after child3, cur becomes [1,4,4,0]. That's f1 = [1,4,4,0].
Now compute g1 (v selected): start cur_g = [1,0,0,0].
Child2: only f2 = [1,1,0,0] (since v selected, cannot select child's selected sets). Convolve: cur_g [1,0,0,0] with f2 [1,1,0,0] => new = [1,1,0,0]. (k=0:11=1; k=1:11+0*1=1; others 0)
So cur_g = [1,1,0,0].
Now total independent sets of size 3 = f1[3] + g1[3] = 0 + 1 = 1. Matches example.
So DP works.
Complexity: O(N * deg * 3^2) ~ O(N) since each node merges its children with constant operations per child.
We must be careful about integer overflow? N up to 1e5, number of independent triples could be up to C(1e5,3) ~ 1.66e14, which fits in 64-bit (max ~ 10^14). Use long long (64-bit) in C++ (int64). Python can handle big ints.
Implementation details:
Use adjacency list.
Do iterative DFS with stack or recursion (Python recursion limit might be insufficient for N=1e5 if depth is large). Tree could be a long chain, recursion depth could be 1e5, which may exceed default recursion limit. We can either set recursion limit high (sys.setrecursionlimit(200000)) or use iterative approach. In Python, often we set recursionlimit to like 200000 and hope it's okay. But might still cause recursion depth issues if the tree is very deep? Python recursion overhead can cause stack overflow if depth is too large. Safer to use iterative DFS: we can do a post-order traversal using stack. For DP on tree, we can do a topological order from leaves to root: first do a stack for order (e.g., do a DFS to get parent and order). Then process nodes in reverse order.
Steps:
Read N.
Build adjacency list.
Choose root (say 0 or 1). For convenience, use 0-indexing? Input nodes are 1..N. We'll convert to 0..N-1.
Perform BFS/DFS to compute parent and order. For iterative:
parent = [-1]*N
order = [] (list to store nodes in DFS order)
stack = [root]; parent[root] = -2 (or sentinel)
while stack: v = stack.pop(); order.append(v); for nb in adj[v]: if nb != parent[v]: parent[nb] = v; stack.append(nb)
This gives a preorder but we need postorder (children before parent). So after building order (which is preorder), we can reverse it to get a postorder (parents after children). That works because in a DFS preorder, children are visited after parent but before other branches; if we push children onto stack, we get them in some order. The resulting order list is in order of visitation (preorder). When we reverse, we get an order where all children appear before parent? Not necessarily always, but if we use stack LIFO, we push children, then pop; the order we process (append when pop) yields a preorder. In a tree, reversing preorder gives an order where a node appears after all nodes in its subtree? Actually, in a DFS (preorder), when you enter a node, you then recursively visit its children. If you record nodes after processing them (postorder), you get postorder. But here we record when we pop (which is when we enter) - that's preorder. The reversed preorder is not guaranteed to be postorder: consider a root with two children: preorder might be root, child1, child2 (if push child2 then child1?) Actually depends on order. If we push children onto stack in any order, then we pop one and record it. For root: stack=[root]. Pop root, record root. Then push its children (say [child1, child2]) onto stack. If we push child2 then child1, then stack = [child1, child2]? Actually LIFO: if we push child1 then child2, the stack will have child2 on top, so we pop child2 first. So preorder could be root, child2, child1's descendants? Not consistent. But reversing that order might not guarantee that parent is after all descendants because in preorder, parent is visited before children. So reversing will put parent after children? Let's test: root, then child A, then child B. Preorder: root, A, B. Reverse: B, A, root. In this case, root is last, which is after its children. However, what about deeper: root, A, A1, A2, B. Preorder could be root, A, A1, A2, B. Reverse: B, A2, A1, A, root. Here A appears after its descendants A1 and A2? Actually A appears before A2 and A1? In reverse: B, then A2, then A1, then A, then root. So A appears after A1 and A2. So yes, reversed preorder yields a topological order where a node appears after all nodes in its subtree? Let's examine: In a tree, the preorder list has property: for any node, its descendants form a contiguous block that appears after it. Specifically, if we perform DFS (recursively) and record preorder, the subtree of a node is contiguous and starts at that node, ends after all descendants. So if we reverse that list, then the subtree block becomes reversed: the node becomes the last element of that block? Actually in preorder: node, then its first child's subtree, then second child's subtree, ... So the node is at the beginning of its subtree block. Reversing the whole list will put the node at the end of its block (since the block is reversed). So reversed preorder yields nodes in order such that children appear before parent (postorder). Because within the block, the children subtrees are reversed as well: the last child becomes first, etc. However, if we used an iterative stack where we push children in arbitrary order, we might not get a strict DFS order? Actually the algorithm described: start stack = [root]; while stack: v = stack.pop(); order.append(v); for nb in adj[v]: if nb != parent[v]: parent[nb]=v; stack.append(nb). This is effectively a DFS but using explicit stack; the order of visiting is similar to a preorder but the children are processed in reverse order of how they are added because of LIFO. However, it still yields a valid DFS traversal? It does a depth-first? Let's see: Starting with root. Pop root, push its children. Suppose root has children 1,2,3. If we push them in order 1,2,3 (iterate adjacency list), then stack becomes [1,2,3] (top is 3). Then we pop 3, push its children, etc. So traversal goes deep into 3's subtree before visiting 2 and 1. That's still a DFS, just with order reversed of adjacency. So it's a depth-first search, and the order recorded is the order nodes are first visited (preorder). Indeed, for DFS (whether recursive or iterative with stack), the moment you first process a node (pop from stack) is analogous to entering the node. So order is preorder. And the property holds: For any node, all descendants appear after it in the order, and the entire subtree is contiguous (because when you finish exploring a child's subtree, you come back to the parent and continue with next child; but since we use stack, the order is still such that after finishing one child's subtree, we pop the next child from stack. The recorded order includes nodes as they are popped. Since we push children onto stack, the deeper nodes are pushed later but popped earlier? Actually if we push children and then immediately pop the top, we go deep. But the order recorded is the order of popping. This yields a preorder where a node appears before its descendants, and the subtree is contiguous because we fully explore a child before moving to the next child (since stack ensures we finish the child's subtree before popping the next child, because the next child remains in stack until we pop it). So indeed the recorded list has the property: for any node, its descendants form a contiguous block that starts right after it and ends at some later index. Then reversing gives a valid postorder (children before parent). So we can use that.
Thus algorithm:
parent = [-1]*N
order = []
stack = [root]
parent[root] = -2 (or root itself to avoid none)
while stack:
v = stack.pop()
order.append(v)
for u in adj[v]:
if u != parent[v]:
parent[u] = v
stack.append(u)
Then after loop, reverse order (order.reverse()).
Now DP: Initialize f = [[0]*4 for _ in range(N)], g = [[0]*4 for _ in range(N)].
Process nodes in reversed order (postorder). For each node v:
initialize f[v][0] = 1; (actually we will compute by merging children; but for leaf, after merging children (none), it will be [1,0,0,0] automatically if we start with cur = [1,0,0,0] and then set f[v] = cur. So we can do that.
Similarly, g[v] will be computed as described.
But note: For a leaf, it will have no children. So merging loop will be empty, and we set:
For f[v]: cur = [1,0,0,0]; after processing children (none) -> f[v] = cur = [1,0,0,0] -> correct.
For g[v]: cur_g = [1,0,0,0]; after merging children (none) -> g[v][1] = cur_g[0] = 1; g[v][2] = 0; g[v][3]=0 -> g[v] = [0,1,0,0] -> correct.
But we must also ensure that for leaf we didn't previously set something else.
Implementation steps per node v:
children = [u for u in adj[v] if u != parent[v]] (but we have parent array; using that). However, we don't need to store children list; we can just iterate over adjacency and skip parent.
But careful: When processing in postorder, the children (neighbors except parent) will have been processed already because they appear earlier in reversed order? Actually reversed order ensures that children are before parent. So when we process v, all its children (neighbors except parent) have already been processed (since they are in the order before v). So we can access f[u] and g[u].
Thus:
for v in reversed_order:
# compute f[v]
cur_f = [1,0,0,0] # base: empty set
for u in adj[v]:
if u == parent[v]:
continue
# u is child
# total ways from child u when v not selected
tot = [f[u][i] + g[u][i] for i in range(4)]
# convolve cur_f and tot
new_cur = [0]*4
for i in range(4):
if cur_f[i] == 0:
continue
for j in range(0, 4-i):
if tot[j] == 0:
continue
new_cur[i+j] += cur_f[i] * tot[j]
cur_f = new_cur
f[v] = cur_f
code
# compute g[v]
cur_g = [1,0,0,0]
for u in adj[v]:
if u == parent[v]:
continue
# only f[u] allowed
only_f = f[u] # list length 4
new_cur = [0]*4
for i in range(4):
if cur_g[i] == 0:
continue
for j in range(0, 4-i):
if only_f[j] == 0:
continue
new_cur[i+j] += cur_g[i] * only_f[j]
cur_g = new_cur
# assign g[v] from cur_g shifted
g[v] = [0]*4
for i in range(3): # i from 0 to 2
g[v][i+1] = cur_g[i]
# g[v][0] remains 0
But we need to be careful about the loops: The convolution loops go up to size 3. Since we only need up to size 3, we can break when i+j >3. So condition j <= 3-i.
We can also precompute for each child the arrays to speed up, but not necessary.
After processing all nodes, root = 0 (or whatever root). Answer = f[root][3] + g[root][3].
Check with example.
But one nuance: The DP counts independent sets of size exactly k in the subtree, but we must ensure that the sets counted are sets of nodes from the subtree (distinct nodes). Our DP merging correctly counts combinations across children as independent because there is no edge between nodes from different subtrees except possibly through v. Since v not selected in f, any selection from children can coexist regardless of v. When v is selected, we forbid selection of children that are selected, but that's enforced by using only f[u] (child not selected). So DP is correct.
Now test on a simple cases:
Case N=1: No triple, answer 0. Our DP: root leaf: f[0] = [1,0,0,0]; g[0] = [0,1,0,0]; answer = 0. Good.
Case N=2: tree with one edge. Independent triples of size 3 impossible, answer 0. DP: root (say 1) has one child 2. For leaf 2: f2 = [1,0,0,0]; g2 = [0,1,0,0]. For root 1:
f1: cur_f start [1,0,0,0]; child tot = f2+g2 = [1,1,0,0]; conv => [1,1,0,0] -> f1 = [1,1,0,0]
g1: cur_g [1,0,0,0]; child only_f = f2 = [1,0,0,0]; conv => [1,0,0,0]; then g1 = [0,1,0,0] (shift: g1[1]=1). answer = f1[3]+g1[3] = 0. Good.
Case N=3: star with center 1 connected to 2,3. Independent triple? Must have three nodes, but only three nodes. Are they mutually non-adjacent? Edges: (1-2), (1-3). So 2 and 3 are not adjacent. So triple (2,3,? ) we need three distinct nodes. The only possible triple is (1,2,3). But 1 is adjacent to both 2 and 3, so not independent. So answer 0. Let's compute DP: root 1: children 2,3 (both leaves). Leaves: f=[1,0,0,0], g=[0,1,0,0] each.
f1: start cur=[1,0,0,0]; child tot = [1,1,0,0]; after child2: cur=[1,1,0,0]; after child3 (same tot): conv => new cur: [11=1, 11+11=2, 10+11+01? Actually compute: cur=[1,1,0,0], tot=[1,1,0,0]; k0:1; k1:11+11=2; k2:10+11+0*1 = 1; k3:0 => f1=[1,2,1,0].
g1: start cur_g=[1,0,0,0]; child only_f = [1,0,0,0]; after child2: cur_g=[1,0,0,0]; after child3: conv same: cur_g=[1,0,0,0]; shift => g1=[0,1,0,0]; answer = f1[3]+g1[3] = 0+0=0. Good.
Case N=3 line: 1-2-3. Independent triple? Only triple (1,2,3) but 1-2 and 2-3 are edges, so not independent (1 and 2 adjacent, 2 and 3 adjacent). However 1 and 3 are not adjacent. But condition says no two of A,B,C are mutually connected by direct edge. So any pair must not have an edge. Since 1-2 edge exists, triple invalid. So answer 0. DP? root 1? But tree is line, if root at 2 (center). Let's pick root=2. Children: 1 and 3 (leaves). Then DP similar to star case? Actually root 2: leaves f=[1,0,0,0], g=[0,1,0,0]. f2: cur start [1]; after child tot: tot=[1,1]; conv with one child => cur=[1,1,0,0]; after second child: similar to star: f2=[1,2,1,0]? Let's compute: after first child: cur_f = [1,1,0,0]; second child tot = [1,1,0,0]; conv => new: k0=1, k1=11+11=2, k2=10+11+0*1=1, k3=0 => f2=[1,2,1,0]. g2: cur_g start [1,0,0,0]; child only_f = [1,0,0,0]; after first: cur_g=[1,0,0,0]; after second: same; shift => g2=[0,1,0,0]. Answer f2[3]+g2[3]=0. Good.
Case N=4: star with center 1 and leaves 2,3,4. There are C(4,3)=4 triples. Which ones are independent? Triple (2,3,4): leaves are not adjacent (no edges among leaves) -> independent! So answer 1. Also triple (1,2,3): not independent because 1 adjacent to 2,3. (1,2,4): not, (1,3,4): not. So answer 1. Let's test DP: root 1, children 2,3,4 leaves. Leaves f=[1,0,0,0], g=[0,1,0,0]. f1: start [1,0,0,0]; after child2 tot=[1,1,0,0] => cur=[1,1,0,0]; after child3: cur=[1,1,0,0] * tot same => new = as before: [1,2,1,0]; after child4: cur currently [1,2,1,0]; tot = [1,1,0,0]; conv:
k0:11=1
k1:11 + 21 = 1+2=3
k2:10 + 21 + 11 = 0+2+1=3
k3:10 + 20 + 11 + 01? Actually careful: indices i from 0..3, j=3-i. But tot has only up to 1. So compute precisely: cur = [c0=1, c1=2, c2=1, c3=0]; tot = [t0=1, t1=1, t2=0, t3=0].
k0: c0t0 =1
k1: c0t1 + c1t0 = 11 + 21 = 3
k2: c0t2 + c1t1 + c2t0 = 10 + 21 + 11 = 3
k3: c0t3 + c1t2 + c2t1 + c3t0 = 10 + 20 + 11 + 0*1 = 1
k4: but we only keep up to 3, so k3=1. So f1=[1,3,3,1]. g1: start cur_g=[1,0,0,0]; after each child only_f=[1,0,0,0]; after three children: cur_g remains [1,0,0,0]; shift => g1=[0,1,0,0]. Answer = f1[3]+g1[3] = 1+0=1. Good.
So DP works.
Now consider larger N: we need to use 64-bit integers. Python ints fine.
Complexity: For each node, we iterate over its children. For each child we do O(4*4)=16 operations constant. So O(N).
Implementation details:
We'll store f and g as list of lists of ints of size N x 4. Could also store as tuples per node.
Memory: N up to 100k, each node has two arrays of length 4 (8 ints). That's fine.
Now we must handle input. The problem may have multiple test cases? It says "The first line of each test case contains a single integer N". But not explicitly number of test cases. Possibly it's a single test case. Usually such problems have a single test case. So we can assume one test case.
But to be safe, we could read until EOF? The input example shows only one case. Usually on platforms like CodeChef or SPOJ, they specify T. Here not. So single test case.
Edge Cases: N could be less than 3? Then answer 0. DP will give 0 as f[root][3] and g[root][3] will be 0 (since size 3 not possible). But we must still compute without index error. Our DP only fills up to size 3, but for N<3, merging might not produce size 3 entries. Works.
Now let's think about alternative formulas? Not needed.
Now confirm DP correctness: The DP counts independent sets in tree where order does not matter, exactly as needed. The triple count is number of independent sets of size 3.
One more check: In the DP, when v is not selected, we allow any combination from children, even if they include selections from multiple children that might be adjacent? There is no direct edge between nodes from different subtrees because they are only connected via v. Since v is not selected, there is no conflict. So that's correct.
Now confirm for a tree with 5 nodes: we already did.
Implementation Plan in Python:
import sys
data = sys.stdin.read().strip().split()
if no data: return
index = 0
N = int(data[index]); index+=1
adjacency list: adj = [[] for _ in range(N)]
for i in range(N-1):
u = int(data[index])-1; v = int(data[index+1])-1; index+=2
adj[u].append(v); adj[v].append(u)
if N < 3: print(0); return
root = 0
parent = [-1]*N
order = []
stack = [root]
parent[root] = -2 # mark visited
while stack:
v = stack.pop()
order.append(v)
for nb in adj[v]:
if nb != parent[v]:
parent[nb] = v
stack.append(nb)
order is preorder; we need postorder -> reverse
order.reverse()
Initialize f = [[0]*4 for _ in range(N)]; g = [[0]*4 for _ in range(N)]
Process each v in order:
compute f[v]
cur_f = [1,0,0,0]
for u in adj[v]:
if u == parent[v]:
continue
tot = [f[u][i] + g[u][i] for i in range(4)]
# convolution
new_f = [0,0,0,0]
for i in range(4):
if cur_f[i] == 0:
continue
ci = cur_f[i]
for j in range(4-i):
if tot[j] == 0:
continue
new_f[i+j] += ci * tot[j]
cur_f = new_f
f[v] = cur_f
compute g[v]
cur_g = [1,0,0,0]
for u in adj[v]:
if u == parent[v]:
continue
only_f = f[u] # list length 4
new_g = [0,0,0,0]
for i in range(4):
if cur_g[i] == 0:
continue
ci = cur_g[i]
for j in range(4-i):
if only_f[j] == 0:
continue
new_g[i+j] += ci * only_f[j]
cur_g = new_g
gv = [0,0,0,0]
for i in range(3):
gv[i+1] = cur_g[i]
g[v] = gv
ans = f[root][3] + g[root][3]
print(ans)
Check for root: we used 0-index root 0. Works.
Now verify with star N=4: we got ans 1.
Now test with N=5 chain: 1-2-3-4-5. Let's compute manually? Possibly we can compute via DP later.
But we should ensure that DP accounts for unordered triples as independent sets. Yes.
Potential pitfalls:
The tree may not be connected? It's a tree, so connected.
Input N might be 0? Not possible as N>=1.
For N=3, we get 0.
For N=10^5, recursion depth using iterative DFS is safe.
Now let's test with a simple tree of 6 nodes: star with center 1 and leaves 2-6 (5 leaves). Independent triples: choose any 3 leaves = C(5,3)=10. And also maybe triples that include center? No, center adjacent to all leaves. So total 10. Let's test quickly with DP mental: root 1 has 5 leaves. f1 will count independent sets not containing center. That is, we need to pick 3 leaves. Leaves have f leaf = [1,0,0,0]; g leaf = [0,1,0,0]. For f1: we need to combine 5 children where v not selected. Each child tot = [1,1,0,0]. So we need number of ways to pick 3 leaves from 5. That's C(5,3)=10. Our DP merging will compute f1[3] = number of ways to pick exactly 3 leaves = 10. g1[3] = 0. So ans =10. Good.
Now for a tree that is a path of 6 nodes: 1-2-3-4-5-6. Let's compute number of independent sets of size 3. Could compute by DP or enumeration. But our DP should give correct answer.
Thus solution is correct.
But wait, is there any nuance about "unordered triplets (A,B,C) such that A is not connected to B, B is not connected to C and A is not connected to C by a direct edge"? That's exactly independent set of size 3. So DP approach counts exactly that.
Now consider the possibility of overcounting? Since DP counts each set exactly once, and each set is an independent set, it's fine.
Thus we can produce final answer.
Now verify time: For each node, we loop over its adjacency list to process children. Sum of deg over nodes = 2*(N-1), so total merging loops = O(N). Each merging does up to 16 multiplications/additions. So 1.6 million ops, trivial.
Now we need to handle reading input quickly because N up to 1e5 lines. Use sys.stdin.read.
Now produce final code.
But caution: In DP, for g[v] we used shift: g[v][i+1] = cur_g[i] for i=0..2. However, cur_g after merging children could have values for i up to 3? Actually, from merging only f[u] (which have at most size 3), and starting from cur_g[0]=1, the maximum total from children is sum of maximum sizes from each child's f[u], but each child's f[u] can have up to 3 selected nodes? In a subtree, the maximum independent set size can be up to size of subtree. But we only keep up to 3. So cur_g can have non-zero entries for indices 0..3. But if cur_g[3] is non-zero, that would correspond to picking 3 nodes from children. Then including v would make 4 nodes, which we don't need to store because we only need up to size 3. So we ignore cur_g[3] when shifting? Actually, if cur_g[3] exists, that would be ways to pick 3 nodes from children. Then adding v would make size 4, which we don't care about. So we only shift up to i=2 (since i+1 <= 3). So we ignore cur_g[3] (it is not used). That's fine.
Similarly, for f[v] merging tot, we only keep up to 3, ignore larger.
Now, ensure that for root, we compute answer as f[root][3] + g[root][3]. This counts all independent sets of size 3 in the whole tree.
Now test with some random small trees by brute force to be sure. But in analysis we can't run code, but we can reason.
Now, note that the DP as described counts independent sets that are subsets of vertices. So it's correct.
Now produce final answer.
But wait: The problem description says "total number of unordered triplets (A,B,C) such that A is not connected to B, B is not connected to C and A is not connected to C by a direct edge". That is exactly what we counted.
Now edge case: N up to 10^5, answer can be up to C(10^5,3) ~ 1.66e14. That fits in 64-bit. But Python int fine.
Now final code.
But we should consider that there might be multiple test cases? The problem says "The first line of each test case contains a single integer N". It does not specify T. However, typical competitive programming problems sometimes have multiple test cases until EOF. But here it's ambiguous. Could be single test case. In many platforms like CodeChef, they would specify T. I'd assume one test case. However, to be safe, we can read all input and if there are more numbers after processing one test case, we could continue? But if there is only one test case, that's fine. Usually they'd give a sample with a single test case. So implement for one test case.
Nevertheless, we could write code to handle multiple test cases by checking if after reading N and N-1 edges we still have data left? But then we wouldn't know if it's another test case or not. Might be that input contains exactly one test case. I'll go with single.
Let's produce final solution with iterative DFS and DP.
Now I'll write in Python.
Potential performance: using list comprehensions for tot each time may be okay. But we can avoid copying lists by directly using loops.
We'll define functions for convolution.
Alternatively, we can compute f and g as 4-element arrays using tuples.
Now produce final answer.
I will now craft the final explanation and code.
But also note: There is an alternative combinatorial approach: count total triples minus triples with at least one edge, but that could be more complex. DP is straightforward.
Now final code.
We'll also include a check for N < 3: print 0 and exit.
Now implement:
import sys
def solve():
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
N = int(next(it))
adj = [[] for _ in range(N)]
for _ in range(N-1):
u = int(next(it)) - 1
v = int(next(it)) - 1
adj[u].append(v)
adj[v].append(u)
code
if N < 3:
print(0)
return
root = 0
parent = [-1]*N
order = []
stack = [root]
parent[root] = -2
while stack:
v = stack.pop()
order.append(v)
for nb in adj[v]:
if nb != parent[v]:
parent[nb] = v
stack.append(nb)
order.reverse() # now postorder
f = [[0]*4 for _ in range(N)]
g = [[0]*4 for _ in range(N)]
for v in order:
# compute f[v]: v not selected
cur_f = [1, 0, 0, 0]
for u in adj[v]:
if u == parent[v]:
continue
# total from child u when v not selected
tot_u = [f[u][i] + g[u][i] for i in range(4)]
# convolve cur_f and tot_u
new_cur = [0,0,0,0]
for i in range(4):
if cur_f[i] == 0:
continue
ci = cur_f[i]
for j in range(4-i):
if tot_u[j] == 0:
continue
new_cur[i+j] += ci * tot_u[j]
cur_f = new_cur
f[v] = cur_f
# compute g[v]: v selected
cur_g = [1, 0, 0, 0]
for u in adj[v]:
if u == parent[v]:
continue
only_f = f[u] # list length 4
new_cur = [0,0,0,0]
for i in range(4):
if cur_g[i] == 0:
continue
ci = cur_g[i]
for j in range(4-i):
if only_f[j] == 0:
continue
new_cur[i+j] += ci * only_f[j]
cur_g = new_cur
# shift cur_g by 1
gv = [0,0,0,0]
for i in range(3):
gv[i+1] = cur_g[i]
g[v] = gv
ans = f[root][3] + g[root][3]
print(ans)
if name == "main":
solve()
Testing with given example: Should output 1.
Now, consider performance: For each node, we create new lists new_cur etc. That's fine.
But maybe we can micro-opt: use local variables for speed. However, N=1e5, loops are small, should be fine.
Edge Cases: If root has parent -2, we skip that in child loops because parent[v] is set to -2 for root, and children will have parent set to actual node, so root's parent check works.
But need to ensure that in the DP loops, we correctly skip parent. Since we set parent[root] = -2, and all other nodes have parent set to their actual parent, we will not treat parent as child.
Now test with N=1: we return early because N<3 -> print 0.
Now, one more test: N=3, edges: 1-2, 2-3. Our code: N=3, but N<3? Actually N=3, not less than 3, so we continue. Compute DP. root 0 (node 1). Let's simulate:
Adj: 0-1, 1-2. Root 0.
Build order: start at 0, push. stack=[0]; pop 0, order=[0], push children (neighbors except parent? parent[0]=-2, so neighbors: 1, parent[1] set to 0, push 1. stack=[1]. Then pop 1, order=[0,1]; neighbors: 0 (parent) skip, 2 set parent[2]=1 push 2. stack=[2]. pop 2, order=[0,1,2]; neighbors: 1 skip. End. order preorder: [0,1,2]. reverse: [2,1,0]. So process 2 first.
Node2: leaf: f2 computed as cur_f = [1,0,0,0] because no children -> f2=[1,0,0,0]; g2: cur_g start [1,0,0,0] -> after shift g2=[0,1,0,0]. Node1: children: 2 (since parent[1] is 0, but neighbor 2 is not parent? Actually parent[1]=0, so children: 2. For node1: f1: cur_f start [1]; tot for child2 = f2+g2 = [1,1,0,0]; conv => new_cur: i=0: cur_f[0]=1 * tot[0]=1 -> new[0]=1; i=0,j=1:11=1 -> new[1]=1; rest 0 => f1=[1,1,0,0]. g1: cur_g start [1]; only_f = f2 = [1,0,0,0]; conv => new_cur = [1,0,0,0]; shift => g1=[0,1,0,0]. Node0 (root): children: only 1 (since parent[0]=-2, neighbor 1 is child). For f0: cur_f start [1]; tot for child1 = f1+g1 = [1+0=1, 1+1=2,0+0=0,0] = [1,2,0,0]; conv: cur_f initially [1,0,0,0]; after convolution: new[0]=11=1; new[1]=12+01=2; new[2]=10+02+0*1=0? Actually compute: i=0,j=2: cur[0]*tot[2]=0; i=1,j=1:0; i=2,j=0:0 -> 0; new[3]=0. So f0=[1,2,0,0]. g0: cur_g start [1]; only_f = f1 = [1,1,0,0]; conv: new = conv([1],[1,1,0,0]) = [1,1,0,0]; shift => g0 = [0,1,1,0]. Answer = f0[3]+g0[3] = 0+0=0. Good.
Now test with N=4 star: root=0 center, children 1,2,3. We already got f0[3]=1, g0[3]=0, answer=1.
Now test with N=5 star (center 0, leaves 1..4). Expect C(4,3)=4? Wait N=5 star has 4 leaves, triple leaves = C(4,3)=4. Let's simulate quickly: root=0, leaves. f0 will count combos of leaves (since root not selected). Each leaf tot = [1,1,0,0]. Combining 4 children to get exactly 3 selections: number = C(4,3)=4. f0[3] should be 4. g0[3] = 0. So ans =4. Good.
Now verify DP for path of 5 nodes: Let's compute manually maybe to check consistency.
But overall DP is sound.
Now possible improvements: We could use recursion with sys.setrecursionlimit(200000). But iterative is safer.
Now final answer.
One more nuance: The DP counts independent sets of size exactly 3. However, there is an alternative: count all triples and subtract those with at least one edge. But DP is easier.
Now, I'll produce the final answer with explanation.
We should include time and space complexity: O(N).
Now final code.
But we need to ensure we use Python's fast I/O. Already using sys.stdin.read.
Now final.
Will there be any issue with parent array for root? We set parent[root] = -2, but in the child loop we compare with parent[v]; for root, parent[root] = -2, which is not equal to any neighbor (since neighbor indices are >=0). So we will treat all neighbors as children. That's correct.
Now, for nodes other than root, parent is set, so we skip parent.
Now confirm that order reversal indeed yields children before parent: Since we built order by pushing children after popping parent, the order is preorder; reversing gives postorder? Example: root with children A and B, where A has child a1. Preorder might be root, A, a1, B. Reverse: B, a1, A, root. That is a valid postorder? Not exactly standard postorder (a1, A, B, root). But does it guarantee that children are processed before parent? In reversed order, root is last. For