using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
static Dictionary<string,List<List<string>>> R = new Dictionary<string,List<List<string>>>();
static void cykParse(List<string> w)
{
int n = w.Count;
SortedDictionary<int, SortedDictionary<int, SortedSet<string>>> T = new SortedDictionary<int, SortedDictionary<int, SortedSet<string>>>();
for (int j = 0 ; j < n ; j++)
{
foreach (KeyValuePair<string,List<List<string>>> x in R)
{
string lhs = x.Key;
List<List<string>> rule = x.Value;
foreach (List<string> rhs in rule)
{
if(rhs.Count == 1 && rhs[0] == w[j]){
if(!T.ContainsKey(j)){
T.Add(j, new SortedDictionary<int, SortedSet<string>>());
}
if(!T[j].ContainsKey(j)){
T[j].Add(j, new SortedSet<string>());
}
T[j][j].Add(lhs);
}
}
}
for(int i = j ; i >= 0 ; i--)
{
for(int k = i ; k <= j ; k++)
{
foreach (KeyValuePair<string,List<List<string>>> x in R)
{
string lhs = x.Key;
List<List<string>> rule = x.Value;
foreach (List<string> rhs in rule)
{
if(rhs.Count == 2 &&
T.ContainsKey(i) &&
T[i].ContainsKey(k) &&
T[i][k].Contains(rhs[0]) &&
T.ContainsKey(k + 1) &&
T[k + 1].ContainsKey(j) &&
T[k + 1][j].Contains(rhs[1]))
{
if(!T.ContainsKey(i)){
T.Add(i, new SortedDictionary<int, SortedSet<string>>());
}
if(!T[i].ContainsKey(j)){
T[i].Add(j, new SortedSet<string>());
}
T[i][j].Add(lhs);
}
}
}
}
}
}
if(T.ContainsKey(0) && T[0].ContainsKey(n - 1) && T[0][n - 1].Count != 0){
Console.Write("True\n");
}else{
Console.Write("False\n");
}
}
public static void Main(string[] args){
R.Add("NP", new List<List<string>>{
new List<string>{"Det", "Nom"}
});
R["Nom"]= new List<List<string>>{
new List<string>{"AP", "Nom"},
new List<string>{"book"},
new List<string>{"orange"},
new List<string>{"man"}
};
R["AP"] = new List<List<string>>{
new List<string>{"Adv", "A"},
new List<string>{"heavy"},
new List<string>{"orange"},
new List<string>{"tall"}
};
R["Det"] = new List<List<string>>{
new List<string>{"a"}
};
R["Adv"] = new List<List<string>>{
new List<string>{"very"},
new List<string>{"extremely"}
};
R["A"] = new List<List<string>>{
new List<string>{"heavy"},
new List<string>{"orange"},
new List<string>{"tall"},
new List<string>{"muscular"}
};
List<string> w = new List<string>{"a", "very", "heavy", "orange", "book"};
cykParse(w);
}
}