现在,我得到一张无序火车票的清单,我需要弄清楚从哪里开始,在哪里停下来并使用"所有"四处旅行的门票。我被允许不止一次去一个城市(这取决于我的门票)。那么我怎样才能找到这个tavel问题的算法(伪代码)呢?
我在想找到起点和终点,但我不知道如何找到可以使用所有门票的路线。这就是我所做的:
HashMap<String, List of tickets> outgoing = new HashMap<String, List of tickets>();
HashMap<String, Integer> incoming = new HashMap<String, Integer >();
For each ticket (t) in List {
String start == t. origin
String end == t.destination
If outGoing.contains(t) {
outGoing.get(start).add(t);
incoming.get(end)++;
Else
outGoing.put(start, EmptyList.add(t));
inComing.put(end, 1);
}
}
For each outGoing.Entry<String, List of tickets > entry: outGoing.entrySet()
{
String startingCity == “”;
String endingCity == “”;
String city = entry.getKey();
If outGoing. get(city). size > inComing.get(city); {
city == startingCity;
}
If outGoing. get(city). size < inComing.get(city); {
city == endingCity;
}
}
If (startingCity == “” && endingCity == “”) {
//Start anywhere, because it is a cycle.
} else {
//sort from startingCity to endingCity
}
答案 0 :(得分:0)
由于所有故障单都定义了起源和目的地,并且由于您需要使用所有故障单,因此您正在寻找Eulerian Path。
存在这种路径的条件是:
http://www.graph-magics.com/articles/euler.php中描述了一种有效的算法。