Tree Paths

View as PDF

Submit solution

Points: 12 (partial)
Time limit: 1.0s
Java 3.0s
Memory limit: 512M

Author:
Problem type

There exists a tree with N vertices and N1 bidirectional edges. Each edge i connects vertices ui and vi and has a length of li. A path between two distinct vertices u and v is valid if v is reachable from u and the edge lengths on the path from u to v form a non-decreasing sequence. Note that a path from u to v is considered the same as a path from v to u (whether valid or not). Given the number of vertices and edges of a tree, find the number of valid paths.

Constraints

1N2×105

1ui,viN

1li109

Subtask 1 [20%]

All li are distinct.

Subtask 2 [80%]

No additional constraints.

Input Specification

The first line contains a single integer N, the number of vertices in the tree.

The next N1 lines contain 3 integers ui, vi and li, representing a bidirectional edge from ui to vi of length li.

Output Specification

Output a single integer, the number of valid paths. Please note that the answer may not fit inside a 32-bit integer.

Note: You do not need to pass all sample cases to earn points on this problem.

Sample Input 1

Copy
3
1 2 4
1 3 4

Sample Output 1

Copy
3

Explanation for Sample Output 1

The three valid paths are 12, 13 and 312. Notice that 312 and 213 are considered the same path.

Sample Input 2

Copy
5
1 2 7
1 3 2
2 4 9
2 5 5

Sample Output 2

Copy
9

Sample Input 3

Copy
10
1 2 2
1 3 4
2 4 5
2 5 3
5 6 2
5 7 1
6 8 1
6 9 5
6 10 2

Sample Output 3

Copy
30

Comments

There are no comments at the moment.