Under construction

Still being built. Things may change

Balanced Tree Path

Time limit2sMemory limit2048 MB

Summary
Count the paths in a tree whose node labels, read in path order, form a balanced bracket string.
Level

Medium6 of 10

Topics
Tree, DFS, Stack, String
Solved
No attempts yet

Problem

Each node of a tree is labeled with one of the characters ()[]{}. A path is a sequence of one or more nodes in which no node repeats and every pair of adjacent nodes is joined by an edge. A path is balanced if the characters of its nodes, concatenated in order, form a balanced string.

A string is balanced by these rules:

  • The empty string is balanced.
  • If ss is balanced, then (s)(s), [s][s], and {s}\{s\} are balanced.
  • If aa and bb are balanced, then the concatenation abab is balanced.

Count the balanced paths in the whole tree.

Input

The first line contains an integer nn (2≤n≤5⋅1032 \le n \le 5 \cdot 10^3).

The second line contains a string of nn characters, each one of ()[]{}.

Each of the next n−1n-1 lines contains two integers uu and vv (1≤u<v≤n1 \le u < v \le n), meaning that nodes uu and vv are connected by an edge. The graph is a tree.

Output

Print a single integer: the number of balanced paths.

Examples3

  1. Example 1

    Input
    4
    ()()
    1 2
    2 3
    3 4
    
    Expected output
    4
    
  2. Example 2

    Input
    4
    [[]]
    1 2
    2 3
    3 4
    
    Expected output
    2
    
  3. Example 3

    Input
    6
    ([]{})
    1 2
    2 3
    3 4
    4 5
    5 6
    
    Expected output
    4