Better implementation - TOURMAP

For this question, how can I make this

[1] better.
I have made a set of unique strings and simultaneously counted the occurrence of each string. For the two strings which occur once, one of them will be my starting city and other end will be the edning one. Using parent, I am making the path.
Almost all the codes I can see with AC, almost same thing is done using two loops in the end.