我正在從競爭中解決這個問題。我會在這裏簡要描述這個問題。尋找最短等待時間的路徑
一位廚師正試圖在時間T之前到達會議場所,但他希望在巴士站儘量減少等待時間。除非他在T之前到達目的地,並且在巴士站等候最少,否則他並不介意走長路線。他從第一站開始,目的地是最後一站。這裏是輸入規範...
N T M
U V S E
U V S E
... and so on
其中N是站數,T是會議時間,M是總線數。接下來的M線是巴士細節。 U是公共汽車開始的地方,V是它到達的地方。 S是開始時間,E是到達時間。所以公共汽車開始在車站,U在時刻S,在時間到達工位V E.
Constraints
2 ≤ N ≤ 50000
1 ≤ T ≤ 109
1 ≤ M ≤ 100000 (105)
1 ≤ U ≤ N
1 ≤ V ≤ N
U ≠ V
0 ≤ S < E ≤ 10
這是我已經試過了,代碼後,並在代碼解釋如下。
public int findMax(int nextStation, int rcd, int start, int end) {
int tt = start - rcd;
// If we reached destinaion, i.e the last station
// no more wait has to be done and we return the time
// required to reach here
if (nextStation == noOfStations) {
return tt;
}
// TODO : we already found a better path, so we skip this one
// if (tt > minTillNow) {
// return Integer.MAX_VALUE;
// }
List<Bus> buses = stations.get(nextStation);
// If we have not reached finalStation
// and there are no more buses from this station,
// we reached a dead end.
if (buses == null) {
return -1;
}
int temp, min = Integer.MAX_VALUE;
// If there are buses from this station, we try all
// of them
for (int i = 0; i < buses.size(); i++) {
temp = findMax(buses.get(i).v, end, buses.get(i).s, buses.get(i).e);
// Find minimum wait-time
if (temp != -1 && temp < min) {
min = temp;
}
}
// If no subtree has a path
if (min == Integer.MAX_VALUE) return -1;
// if the wait to reach here is greater than any subsequent
else if (min < tt) return tt;
else
return min;
}
我做了DFS,開始在第一站,並找到最長等待時間沿任意路徑,直到結束,然後選擇最低的所有等待沿着這樣的路徑倍。這對於給定的輸入示例很好。
Input:
5 10 5
1 2 1 2
1 5 3 4
2 4 4 5
2 5 5 6
4 5 6 7
Output:
2
但我失敗時,我提交了一些測試輸入,與「錯誤的答案」。 有人可以發現上述方法的問題嗎?這也是一個很好的方法嗎?這會是什麼複雜性?我認爲它應該是M的線性,是正確的近似值。
這是一個經典的「旅行推銷員」問題。您是否嘗試過將您的代碼與wiki上的內容進行比較? – happybuddha 2013-05-07 18:33:06
@ happybuddha-我不認爲它的旅行推銷員.. – questions 2013-05-07 18:34:56
它更像是一個揹包問題。 – Ingo 2013-05-07 18:37:35