Advertisement
HXXXXJ

滑雪题

Mar 18th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.68 KB | None | 0 0
  1. // test case 1
  2. var travel = [["start","3","A"],["A","6","B"],["B","5","END"]]
  3. var point = ["A":10,"B": 10,"C":10,"END" : 10]
  4.  
  5. func getMaxScore(_ travel: [[String]], _ reward : [String: Int]) -> Int{
  6.     var map = [String: [String: Int]]()   // from : [to, cost]
  7.     var indegree = [String: Int]()
  8.     var maxScore = [String: Int]()
  9.     print(map)
  10.     var queue = [String]()
  11.     queue.append("start")
  12.    
  13.     for trip in travel{
  14.         let from = trip[0]
  15.         let to = trip[2]
  16.         let cost = Int(trip[1])!
  17.         indegree[to, default: 0] += 1
  18.         if indegree[from] == nil {
  19.             indegree[from] = 0
  20.         }
  21.         map[from, default: [String:Int]()][to] = cost
  22.     }
  23.     print(map)
  24.     var visited = [String]()
  25.     visited.append("start")
  26.    
  27.     maxScore["start"] = 0
  28.     var res = 0
  29.     while queue.count > 0 {
  30.         let cur = queue.removeFirst()
  31.        
  32.         if let toMap = map[cur]{
  33.             for (to, cost) in toMap{
  34.                 indegree[to] = indegree[to]! - 1
  35.                 if indegree[to] == 0{
  36.                     queue.append(to)
  37.                 }
  38.                
  39.                 if let score = maxScore[to]{
  40.                     maxScore[to] = max(score, maxScore[cur]! + reward[to]! - cost)
  41.                 }else{
  42.                     print(cur)
  43.                     print(maxScore)
  44.                     maxScore[to] = maxScore[cur]! +  reward[to]! - cost
  45.                    
  46.                 }
  47.                 if to == "END"{
  48.                     res = max(maxScore[to]!, res)
  49.                 }
  50.                
  51.             }
  52.         }
  53.     }
  54.     return res
  55. }
  56.  
  57.  
  58. let res = getMaxScore(travel, point)
  59. print(res)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement