給定的問題是http://www.spoj.com/problems/TOPOSORT/ 輸出格式就顯得尤爲重要:爲什麼我的邏輯無法正確運行SPOJ TOPOSORT?
Print "Sandro fails." if Sandro cannot complete all his duties on the list.
If there is a solution print the correct ordering,
the jobs to be done separated by a whitespace.
If there are multiple solutions print the one, whose first number is smallest,
if there are still multiple solutions, print the one whose second number is smallest, and so on.
我在做什麼通過逆轉的邊緣即,如果作業的作業B之前完成是簡單地做DFS,有一個從有向邊B到A。我通過對我創建的鄰接表進行排序並存儲沒有任何約束的節點來維護順序,以便以後按照正確的順序打印它們。有兩個標誌陣列使用,一個用於標記發現節點,另一個用於標記已探索所有鄰居的節點。
現在我的解決方案是http://www.ideone.com/QCUmKY(其中重要的功能是訪問函數),並且在運行正確的10個案例之後給出WA,所以它真的很難弄清楚我在哪裏做錯了,因爲它運行所有測試用例這是我手工完成的。
DFS拓撲排序次在這裏。我寫了一個非常優化的版本,它仍然超時。如果您有更多優化的建議,請發表評論。但是你可能需要使用@templatetypedef建議的算法。我的代碼:http://ideone.com/M3A3x3 – sukunrt