Advertisement
VladNitu

ProjectSelection(Pathfinder)_Vlad

Jan 24th, 2023
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. class ProjectSelection {
  2.  
  3. public static
  4. /**
  5. * You should implement this method
  6. *
  7. * @param projects List of projects, you can ignore list.get(0)
  8. * @return A set of feasible projects that yield the maximum possible profit.
  9. */
  10. int maximumProjects(List<Project> projects) {
  11. // TODO
  12. int n = projects.size();
  13. List<Node> nodes = new ArrayList<>();
  14. Node[] nodesArr = new Node[n + 1];
  15.  
  16. for (int i = 1; i <= n; ++i)
  17. {
  18. nodesArr[i] = new Node(i);
  19. nodes.add(nodesArr[i]);
  20. }
  21.  
  22. Node source = new Node(-1);
  23. Node sink = new Node(-2);
  24.  
  25. nodes.add(source);
  26. nodes.add(sink);
  27.  
  28. Integer allPossibleProfits = 0;
  29.  
  30. for (Project project: projects) {
  31. int profit = project.getRevenue() - project.getCost();
  32. if (profit > 0) {// link to source as it generates profit
  33. source.addEdge(nodesArr[project.getId()], profit);
  34. allPossibleProfits += profit;
  35. }
  36. else { // link to sink as it costs (profit < 0; cost = -profit)
  37. nodesArr[project.getId()].addEdge(sink, - profit);
  38. }
  39. }
  40.  
  41. for (Project task: projects)
  42. for (Integer subtaskId: task.getRequirements())
  43. nodesArr[task.getId()].addEdge(nodesArr[subtaskId], Integer.MAX_VALUE / 2);
  44.  
  45.  
  46. Graph G = new Graph(nodes, source, sink);
  47. int allCosts = MaxFlow.maximizeFlow(G);
  48. return allPossibleProfits - allCosts;
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement