#!/usr/bin/python3 class Pipe: def __init__(self, node, state): self.node = node self.state = state class Node: def __init__(self): self.pipes = [] # None → this node is an inner node self.contents = None # min needed changes in subtree by inflow self.ocost = None self.zcost = None [N, M] = map(int, input().split()) nodes = [] for i in range(N): nodes.append(Node()) for i in range(N-1): [f, t, s] = input().split() f = int(f) - 1 t = int(t) - 1 assert s in ["O", "Z"] nodes[f].pipes.append(Pipe(nodes[t], s)) nodes[t].pipes.append(Pipe(nodes[f], s)) for n in nodes: assert(len(n.pipes) > 0) for i in range(M): [n, c] = input().split() n = int(n) - 1 assert c in ["P", "M", "E"] nodes[n].contents = c def flip(state): if state == "O": return "Z" if state == "Z": return "O" assert False def compute_cost(n, inflow, parent): # cache lookup if inflow == "O" and n.ocost is not None: return n.ocost if inflow == "Z" and n.zcost is not None: return n.zcost # we must deliver tea to programmers if n.contents == "P" and inflow == "Z": return N # n≈∞ # we must not deliver tea to managers if n.contents == "M" and inflow == "O": return N # n≈∞ cost = 0 for p in n.pipes: if p.node is not parent: keep = compute_cost(p.node, p.state if inflow == "O" else "Z", n) change = compute_cost(p.node, flip(p.state) if inflow == "O" else "Z", n) + 1 cost += min(keep, change) if inflow == "O": n.ocost = cost if inflow == "Z": n.zcost = cost return cost print(compute_cost(nodes[0], "O", None))