using System.Collections.Generic;
public static string GetSExpression(string s){
bool[,] graph = new bool [26,26];
HashSet<char> nodes = new HashSet<char>();
for(int i=1;i<s.Length;i+=6){
int x = s[i]-'A', y = s[i+2]-'A';
foreach(char node in nodes){
bool[] visited = new bool[26];
if(IsCycle(node, graph, visited))
if(numOfRoots==0) return "E3";
if(numOfRoots>1) return "E4";
if(root==' ') return "E5";
return GetExpressionHelper(root, graph);
private static bool IsCycle(char node, bool[,] graph, bool[] visited){
visited[node-'A'] = true;
if(IsCycle((char)(i+'A'), graph, visited))
private static string GetExpressionHelper(char root, bool[,] graph){
string left = "", right = "";
left = GetExpressionHelper((char)(i+'A'), graph);
right = GetExpressionHelper((char)(j+'A') ,graph);
return "("+root+left+right+")";
public static void Main()
Console.WriteLine(GetSExpression("(A,B) (A,C) (B,G) (C,H) (E,F) (B,D) (C,E)"));