Checking if a list of strings can be chained

后端 未结 8 789
庸人自扰
庸人自扰 2021-01-31 23:45

Question

Implement a function bool chainable(vector v), which takes a set of strings as parameters and returns true if they

8条回答
  •  心在旅途
    2021-02-01 00:00

    As phimuemue pointed out, this is a graph problem. You have a set of strings (vertices), with (directed) edges. Clearly, the graph must be connected to be chainable -- this is easy to check. Unfortunately, the rules beyond this are a little unclear:

    If strings may be used more than once, but links can't, then the problem is to find an Eulerian path, which can be done efficiently. An Eulerian path uses each edge once, but may use vertices more than once.

    // this can form a valid Eulerian path
    yard
    dog
    god
    glitter
    
    yard -> dog -> god -> dog -> glitter
    

    If the strings may not be used more than once, then the problem is to find a Hamiltonian path. Since the Hamiltonian path problem is NP-complete, no exact efficient solution is known. Of course, for small n, efficiency isn't really important and a brute force solution will work fine.

    However, things are not quite so simple, because the set of graphs that can occur as inputs to this problem are limited. For example, the following is a valid directed graph (in dot notation) (*).

    digraph G {
        alpha -> beta;
        beta -> gamma;
        gamma -> beta;
        gamma -> delta;
    }
    

    However, this graph cannot be constructed from strings using the rules of this puzzle: Since alpha and gamma both connect to beta, they must end with the same character (let's assume they end with 'x'), but gamma also connects to delta, so delta must also start with 'x'. But delta cannot start with 'x', because if it did, then there would be an edge alpha -> delta, which is not in the original graph.

    Therefore, this is not quite the same as the Hamiltonian path problem, because the set of inputs is more restricted. It is possible that an efficient algorithm exists to solve the string chaining problem even if no efficient algorithm exists to solve the Hamiltonian path problem.

    But... I don't know what that algorithm would be. Maybe someone else will come up with a real solution, but in the mean time I hope someone finds this answer interesting.

    (*) It also happens to have a Hamiltonian path: alpha -> beta -> gamma -> delta, but that's irrelevant for what follows.

提交回复
热议问题