Advertisement
VladNitu

AD isAQuest BellmanFord Sol1

Jan 12th, 2023 (edited)
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. public static double solve(int n, int m, int k, int g, Node[] V, Set<Edge> E) {
  2.         double[][] dp = new double[k + 1][n + 1];
  3.         // dp[i][j] = min cost to reach 'j'-th node and having left `i` collobarators
  4.         for (int j = 1; j <= n; ++j) {
  5.           Node node = V[j];
  6.           for (int i = 0; i <= k; ++i)
  7.             dp[i][node.getId()] = Double.MAX_VALUE / 2;
  8.         }
  9.        
  10.         for (int i = 0; i <= k; ++i)
  11.             dp[i][V[1].getId()] = 0;
  12.        
  13.      
  14.         for (int node_idx = 1; node_idx <= n; ++node_idx) {
  15.           Node node = V[node_idx];
  16.          
  17.           for (Edge edge: E)
  18.             if (edge.from == node) // optimise later
  19.               {
  20.                 dp[k][edge.to.getId()] = Math.min(dp[k][edge.to.getId()] , dp[k][edge.from.getId()] + edge.cost);
  21.                
  22.                 for (int j = k - 1; j >= 0; --j)  
  23.                     dp[j][edge.to.getId()] = Math.min(dp[j][edge.to.getId()],
  24.                     Math.min(dp[j][edge.from.getId()] + edge.getCost(), dp[j + 1][edge.from.getId()] + edge.getCost() / 2.0));
  25.  
  26.               }
  27.         }
  28.        
  29.         // after using all `k` colaborators, min cost of reaching `g`
  30.         double ans = dp[0][V[g].getId()];
  31.          
  32.         if (ans !=  Double.MAX_VALUE / 2)
  33.           return ans;
  34.         else return -1;
  35.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement