Search code examples
algorithmgraphtopological-sort

sorting algorithm for the following?


So, I am trying to solve the following problem:

http://codeforces.com/contest/510/problem/B


Solution

  • I would solve it this way:

    1. Create a graph G where each vertex represents a letter from the alphabet.
    2. Insert a directed edge from v1 to v2 into G iff there exist two words in the given sequence such that w1 = prefix v1 suffix1, w2 = prefix v2 suffix2 and w1 precedes w2 in the given sequence. You should figure out how to make this step efficient. I believe it can be done in O(sum over a length of each word)
    3. Return true if G can be sorted topologicaly.