This page is still under construction.

Parts of this page are still being built. What you see may change.

Yin and Yang

Time limit2sMemory limit128 MB

Summary
On a tree with each edge colored black or white, count paths that split at an internal vertex into two legs each having equal numbers of black and white edges.
Level

Hard9 of 10

Topics
Tree, Divide and conquer, Prefix sum, Hash map
Solved
No attempts yet

Problem

Farmer John is planning his morning walk on the farm. The farm is structured like a tree: it has NN barns (1≤N≤100,0001 \le N \le 100{,}000) connected by N−1N-1 edges, so he can reach any barn from any other. Farmer John wants to choose a path that starts and ends at two different barns and never traverses any edge twice. Worried that his path might be a little long, he also wants to pick a "rest stop" barn on this path that is distinct from both the start and the end.

Along each edge is a herd of cows, either of the Charolais (white hair) or the Angus (black hair) variety. Being a wise man, Farmer John wants to balance the forces of yin and yang on his walk. To do so, he wants a path such that he passes an equal number of Charolais herds and Angus herds both on the way from the start to the rest stop and on the way from the rest stop to the end.

Farmer John is curious how many different "balanced" paths he can choose. Two paths are considered different only if they consist of different sets of edges; a path is counted only once even if several valid rest-stop locations along it make it balanced.

Please determine the number of paths Farmer John can choose.

Input

  • Line 1: The integer NN (1≤N≤100,0001 \le N \le 100{,}000).
  • Lines 2 to NN: Three integers aia_i, bib_i, and tit_i, giving the two barns that edge ii connects (1≤ai,bi≤N1 \le a_i, b_i \le N). tit_i is 00 if the herd along that edge is Charolais (white) and 11 if it is Angus (black).

Output

  • Line 1: One integer, the number of balanced paths Farmer John can choose.

Hint

In the sample there are 77 barns and 66 edges. The edges 1–2, 2–4, and 2–5 carry Charolais herds. No path of length 22 can hold a suitable rest stop, so only paths of length 44 need be considered. The only path with a suitable rest stop is 3–1–2–5–7, with the rest stop at barn 22.

Examples4

  1. Example 1

    Input
    7
    1 2 0
    3 1 1
    2 4 0
    5 2 0
    6 3 1
    5 7 1
    
    Expected output
    1
    
  2. Example 2

    Input
    1
    
    Expected output
    0
    
  3. Example 3

    Input
    2
    1 2 0
    
    Expected output
    0
    
  4. Example 4

    Input
    5
    1 2 0
    2 3 1
    3 4 1
    4 5 0
    
    Expected output
    1