Checking if a list of strings can be chained

后端 未结 8 796
庸人自扰
庸人自扰 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-01-31 23:53

    Isn't that similar to the infamous traveling salesman problem?

    If you have n strings, you can construct a graph out of them, where each node corresponds to one string. You construct the edges the following way:

    • If string (resp. node) a and b are chainable, you introduce an edge a -> b with weight 1.
    • For all unchainable strings (resp. nodes) a and b, you introduce an edge a -> b with weight n.

    Then, all your strings are chainable (without repetition) if and only if you can find an optimal TSP route in the graph whose weight is less than 2n.

    Note: Your problem is actually simpler than TSP, since you always can transform string chaining into TSP, but not necessarily the other way around.

提交回复
热议问题