Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Task10;
- import java.util.*;
- class Edge{
- int to, weight;
- Edge(int t, int w){ this.to = t; this.weight = w; }
- }
- class Node{
- int heurisitcValue, price, id;
- Node(){
- this.price = 0; this.id = -1; this.id = 0;
- }
- }
- class Graph{
- int nodes;
- ArrayList<Edge>[] adj;
- Node[] nodesContainer;
- boolean[] visited;
- @SuppressWarnings("unchecked")
- Graph(int t){
- this.nodes = t;
- this.nodesContainer = new Node[nodes];
- this.visited = new boolean[nodes];
- adj = (ArrayList<Edge>[])new ArrayList[nodes];
- for(int i=0;i<t;i++) {
- adj[i] = new ArrayList<Edge>();
- this.nodesContainer[i] = new Node();
- }
- }
- void addEdge(int from, int to, int weight) {
- adj[from].add(new Edge(to,weight));
- }
- int findMin(int s, int d) {
- if(adj[s].size() == 0 && s != d) {
- updated = true;
- nodesContainer[s].price = Integer.MAX_VALUE;
- nodesContainer[s].heurisitcValue = Integer.MAX_VALUE;
- return -3;
- }
- if(s == d) {
- return -2;
- }
- int id = -1 , val = Integer.MAX_VALUE, weight = 0;
- for(int i=0;i<adj[s].size();i++) {
- Edge e = adj[s].get(i);
- if(!visited[e.to]) {
- int tempPrice = e.weight + nodesContainer[e.to].heurisitcValue;
- if(tempPrice < val) {
- id = e.to;
- val = tempPrice;
- weight = e.weight;
- }
- if(tempPrice == val) id = Math.min(id, e.to);
- }
- }
- if(id == -1) {
- return -1;
- }
- else {
- visited[s] = true;
- nodesContainer[id].price = val;
- int prevHeuristic = nodesContainer[s].heurisitcValue;
- nodesContainer[s].heurisitcValue = Math.min(nodesContainer[s].heurisitcValue + weight, val);
- if(prevHeuristic != nodesContainer[s].heurisitcValue) {
- updated = true;
- }
- // else debug();
- return id;
- }
- }
- void debug() {
- System.out.println("TUKA");
- }
- void reset() {
- for(int i=0;i<nodes;i++) visited[i] = false;
- }
- boolean updated = true;
- void findPath(int s, int t) {
- int nextNode = s, prevNode = 0;
- while(updated) {
- nextNode = s;
- updated = false;
- for(int i=0;i<nodes;i++) {
- prevNode = nextNode;
- nextNode = findMin(nextNode,t);
- if(nextNode < 0) {
- System.out.println(prevNode);
- break;
- }
- System.out.print(prevNode+",");
- }
- reset();
- }
- }
- }
- public class Naloga10 {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- Graph g = new Graph(5004);
- int totalNodes = 0;
- int m = sc.nextInt();
- for(int i=0;i<m;i++) {
- int f = sc.nextInt(), t = sc.nextInt(), w = sc.nextInt();
- totalNodes = Math.max(Math.max(f, t), totalNodes);
- g.addEdge(f,t,w);
- }
- g.nodes = totalNodes;
- g.findPath(sc.nextInt(), sc.nextInt());
- sc.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement