• + 0 comments
    class DisjointSet:
        def __init__(self, nodes):
            self.parent = {x : x for x in nodes}
            self.rank = {x : 0 for x in nodes}
    
        def find(self, x):
            if self.parent[x] != x:
                self.parent[x] = self.find(self.parent[x])
            return self.parent[x]
    
        def add_node(self, x):
            if x not in self.parent:
                self.parent[x] = x
                self.rank[x] = 0
    
        def union(self, x, y):
            self.add_node(x)
            self.add_node(y)
    
            x_root = self.find(x)
            y_root = self.find(y)
    
            if x_root == y_root:
                return
            if self.rank[x_root] < self.rank[y_root]:
                x_root, y_root = y_root, x_root
            self.parent[y_root] = x_root
            self.rank[x_root] += self.rank[y_root]
    
    def solve(edges):
        nodes = set()    
        for u, v, color in edges:
            nodes.add(u)
            nodes.add(v)
    
        ds = DisjointSet(nodes)
        for u, v, color in edges:
    				# Two nodes can be connected through a black edge. Any other node connected through a black edge to these previous nodes will then belong to the same set of nodes all connected through black edges. A node that belongs to a black edge subset cannot be connected with another node belonging to the same or another black edge subset.
            if color == 'b':
                ds.union(u, v)
        
        subsets_sizes = {}
        for node in nodes:
            root = ds.find(node)
            subsets_sizes[root] = subsets_sizes.get(root, 0) + 1
        
        n = len(nodes)
        total_triplets = n * (n - 1) * (n - 2) // 6
        
        invalid_triplets = 0
        for size in subsets_sizes.values():
            if size >= 3:
                invalid_triplets += size * (size - 1) * (size - 2) // 6
            if size >= 2:
                invalid_triplets += size * (size - 1) // 2 * (n - size)
        
        valid_triplets = total_triplets - invalid_triplets
        return valid_triplets % (10**9 + 7)
    
    n = int(input().strip())
    edges = []
    for _ in range(n - 1):
        u, v, color = input().strip().split()
        edges.append((int(u), int(v), color))
    
    print(solve(edges))