Advertisement
daskalot

Untitled

Jan 12th, 2019
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. package Task10;
  2.  
  3. import java.util.*;
  4. class Edge{
  5. int to, weight;
  6. Edge(int t, int w){
  7. this.to = t;
  8. this.weight = w;
  9. }
  10. }
  11. class Node{
  12. int heurisitcValue;
  13. int price;
  14. Node(){
  15. heurisitcValue = 0;
  16. price = 0;
  17. }
  18. }
  19. class Graph{
  20. int nodes;
  21. ArrayList<Edge>[] adj;
  22. Node[] nodesContainer;
  23. boolean[] visited;
  24. @SuppressWarnings("unchecked")
  25. Graph(int t){
  26. this.nodes = t;
  27. this.nodesContainer = new Node[nodes];
  28. this.visited = new boolean[nodes];
  29. adj = (ArrayList<Edge>[])new ArrayList[nodes];
  30. for(int i=0;i<t;i++) {
  31. this.adj[i] = new ArrayList<Edge>();
  32. this.nodesContainer[i] = new Node();
  33. }
  34. }
  35. void addEdge(int from, int to, int weight) {
  36. adj[from].add(new Edge(to,weight));
  37. }
  38. int findMin(int s, int t) {
  39. int r = -1, w = 0;
  40. int val = Integer.MAX_VALUE;
  41. for(int i=0;i<adj[s].size();i++) {
  42. Edge temp = adj[s].get(i);
  43. if(!visited[temp.to]) {
  44. int tempPrice = temp.weight + nodesContainer[temp.to].heurisitcValue;
  45. if(val == Integer.MAX_VALUE) {
  46. val = tempPrice;
  47. w = temp.weight;
  48. r = temp.to;
  49. }
  50. if(tempPrice < val) {
  51. val = tempPrice;
  52. w = temp.weight;
  53. r = temp.to;
  54. }
  55. }
  56. }
  57. //Temp node is either without neighbours or left neighbours left to visit
  58. if(r==-1) {
  59.  
  60. return r;
  61. }
  62. visited[r] = true;
  63. nodesContainer[r].price = val;
  64. nodesContainer[s].heurisitcValue = Math.min(nodesContainer[s].heurisitcValue + w, nodesContainer[r].price);
  65. return r;
  66. }
  67. void findPath(int s, int t) {
  68. int nextNode = s;
  69. int prevNode = nextNode;
  70. for(int i=0;i<nodes;i++) {
  71. prevNode = nextNode;
  72. System.out.println(prevNode+" ");
  73. nextNode = findMin(nextNode,t);
  74. if(nextNode == t) {
  75. break;
  76. }
  77. }
  78. }
  79. }
  80. public class Naloga10 {
  81. public static void main(String[] args) {
  82. Scanner sc = new Scanner(System.in);
  83. Graph g = new Graph(5000);
  84. int totalNodes = 0;
  85. int m = sc.nextInt();
  86. for(int i=0;i<m;i++) {
  87. int f = sc.nextInt(), t = sc.nextInt(), w = sc.nextInt();
  88. f--;
  89. t--;
  90. totalNodes = Math.max(Math.max(f, t), totalNodes);
  91. g.addEdge(f,t,w);
  92. }
  93. g.nodes = totalNodes;
  94. sc.close();
  95. }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement