rendered paste body#include <iostream>#include <map>#include <set>#include <string>using namespace std;#ifdef DBG#define PDBG(X) { cout<<X<<endl; }#else #define PDBG(X) #endiftypedef map<int, set<int> > Adj;Adj Graph;map<string, int> NodeIndex;set<int> Visited;int NodeLen, root, steps, maxVal;void findMax (int parent, int child){ set<int>::iterator iter; PDBG("Parent :"<<parent<<" child :"<<child); if(Visited.find(child) != Visited.end() ) { PDBG(child<<" repeats"); return; } if(Graph[child].find(child) != Graph[child].end()) return; //Check if No visited, except parent loves child for(iter = Visited.begin(); iter != Visited.end(); iter++ ) { if(*iter != parent && Graph[*iter].find(child)!= Graph[*iter].end()) { PDBG("Child "<<child<<" loves "<<*iter); return; } } // check that the child does not love anybody in the Visited set // If it loves the root, then finish the loop for (iter = Graph[child].begin(); iter != Graph[child].end(); iter++) { if (*iter != root && Visited.find(*iter) != Visited.end()) { PDBG("Child "<<child<<" loves Visited at "<<*iter<<" with root "<<root); return; } } if (Graph[child].find(root) != Graph[child].end()) { // Only connects to root, Finalize if (maxVal < steps+1) { maxVal = steps+1; PDBG("\t Value Set :"<<maxVal) } return; } Visited.insert(child); for (set<int>::iterator iter= Graph[child].begin(); iter!= Graph[child].end(); iter++) { steps++; findMax(child, *iter); steps--; } Visited.erase(child);}int main(){ int n; cin>>n; NodeLen = 1; for (int i=0; i<n; i++) { string lhs, rhs; int li, ri; cin>>lhs>>rhs; if ( (li = NodeIndex[lhs]) == 0) li = (NodeIndex[lhs] = NodeLen++); if ( (ri = NodeIndex[rhs]) == 0) ri = (NodeIndex[rhs] = NodeLen++); Graph[li].insert(ri); } maxVal = 0; for (root = 1; root < NodeLen; root++) { steps = 1; if(Graph[root].find(root) != Graph[root].end()) continue; Visited.insert (root); PDBG("Root :"<<root); for (set<int>::iterator iter = Graph[root].begin(); iter != Graph[root].end(); iter++) { findMax(root, *iter); } Visited.erase(root); } if(maxVal>2) cout<<maxVal<<endl; else cout<<0<<endl; return 0;}