Crazy

Графови

Dec 19th, 2017
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.09 KB | None | 0 0
  1. import java.util.Iterator;
  2. import java.util.LinkedList;
  3. import java.io.BufferedReader;
  4. import java.io.InputStreamReader;
  5. import java.util.NoSuchElementException;
  6.  
  7. interface Stack<E> {
  8.  
  9.     // Elementi na stekot se objekti od proizvolen tip.
  10.  
  11.     // Metodi za pristap:
  12.  
  13.     public boolean isEmpty ();
  14.         // Vrakja true ako i samo ako stekot e prazen.
  15.  
  16.     public E peek ();
  17.         // Go vrakja elementot na vrvot od stekot.
  18.  
  19.     // Metodi za transformacija:
  20.  
  21.     public void clear ();
  22.         // Go prazni stekot.
  23.  
  24.     public void push (E x);
  25.         // Go dodava x na vrvot na stekot.
  26.  
  27.     public E pop ();
  28.         // Go otstranuva i vrakja elementot shto e na vrvot na stekot.
  29. }
  30.  
  31. class ArrayStack<E> implements Stack<E> {
  32.     private E[] elems;
  33.     private int depth;
  34.  
  35.     @SuppressWarnings("unchecked")
  36.     public ArrayStack (int maxDepth) {
  37.         // Konstrukcija na nov, prazen stek.
  38.         elems = (E[]) new Object[maxDepth];
  39.         depth = 0;
  40.     }
  41.  
  42.  
  43.     public boolean isEmpty () {
  44.         // Vrakja true ako i samo ako stekot e prazen.
  45.         return (depth == 0);
  46.     }
  47.  
  48.  
  49.     public E peek () {
  50.         // Go vrakja elementot na vrvot od stekot.
  51.         if (depth == 0)
  52.             throw new NoSuchElementException();
  53.         return elems[depth-1];
  54.     }
  55.  
  56.  
  57.     public void clear () {
  58.         // Go prazni stekot.
  59.         for (int i = 0; i < depth; i++)  elems[i] = null;
  60.         depth = 0;
  61.     }
  62.  
  63.  
  64.     public void push (E x) {
  65.         // Go dodava x na vrvot na stekot.
  66.         elems[depth++] = x;
  67.     }
  68.  
  69.  
  70.     public E pop () {
  71.         // Go otstranuva i vrakja elementot shto e na vrvot na stekot.
  72.         if (depth == 0)
  73.             throw new NoSuchElementException();
  74.         E topmost = elems[--depth];
  75.         elems[depth] = null;
  76.         return topmost;
  77.     }
  78. }
  79.  
  80.  
  81. class Edge{
  82.     private int fromVertex, toVertex;
  83.     private float weight;
  84.     public Edge(int from, int to, float weight){
  85.         this.fromVertex = from;
  86.         this.toVertex = to;
  87.         this.weight = weight;
  88.     }
  89.    
  90.     public int getFrom(){
  91.         return this.fromVertex;
  92.     }
  93.     public int getTo(){
  94.         return this.toVertex;
  95.     }
  96.     public float getWeight(){
  97.         return this.weight;
  98.     }
  99. }
  100.  
  101. class GraphNodeNeighbor<E> {
  102.     GraphNode<E> node;
  103.     float weight;
  104.    
  105.     public GraphNodeNeighbor(GraphNode<E> node, float weight) {
  106.         this.node = node;
  107.         this.weight = weight;
  108.     }
  109.    
  110.     public GraphNodeNeighbor(GraphNode<E> node) {
  111.         this.node = node;
  112.         this.weight = 0;
  113.     }
  114.  
  115.     @Override
  116.     public boolean equals(Object obj) {
  117.         @SuppressWarnings("unchecked")
  118.         GraphNodeNeighbor<E> pom = (GraphNodeNeighbor<E>)obj;
  119.         return pom.node.equals(this.node);
  120.     }  
  121. }
  122.  
  123. class GraphNode<E> {
  124.     private int index; //index (reden broj) na temeto vo grafot
  125.     private E info;
  126.     private LinkedList<GraphNodeNeighbor<E>> neighbors;
  127.    
  128.     public GraphNode(int index, E info) {
  129.         this.index = index;
  130.         this.info = info;
  131.         neighbors = new LinkedList<GraphNodeNeighbor<E>>();
  132.     }
  133.    
  134.     public boolean containsNeighbor(GraphNode<E> o){
  135.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o,0);
  136.         return neighbors.contains(pom);
  137.     }
  138.    
  139.     public void addNeighbor(GraphNode<E> o, float weight){
  140.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o,weight);
  141.         neighbors.add(pom);
  142.     }
  143.    
  144.     public void removeNeighbor(GraphNode<E> o){
  145.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o,0);
  146.         if(neighbors.contains(pom))
  147.             neighbors.remove(pom);
  148.     }
  149.    
  150.     @Override
  151.     public String toString() {
  152.         String ret= "INFO:"+info+" SOSEDI:";
  153.         for(int i=0;i<neighbors.size();i++)
  154.         ret+="("+neighbors.get(i).node.info+","+neighbors.get(i).weight+") ";
  155.         return ret;
  156.        
  157.     }
  158.  
  159.     public void updateNeighborWeight(GraphNode<E> o, float weight){
  160.         Iterator<GraphNodeNeighbor<E>> i = neighbors.iterator();
  161.         while(i.hasNext()){
  162.             GraphNodeNeighbor<E> pom = i.next();
  163.             if(pom.node.equals(o))
  164.                 pom.weight = weight;
  165.         }
  166.            
  167.     }
  168.  
  169.     @Override
  170.     public boolean equals(Object obj) {
  171.         @SuppressWarnings("unchecked")
  172.         GraphNode<E> pom = (GraphNode<E>)obj;
  173.         return (pom.info.equals(this.info));
  174.     }
  175.  
  176.     public int getIndex() {
  177.         return index;
  178.     }
  179.  
  180.     public void setIndex(int index) {
  181.         this.index = index;
  182.     }
  183.  
  184.     public E getInfo() {
  185.         return info;
  186.     }
  187.  
  188.     public void setInfo(E info) {
  189.         this.info = info;
  190.     }
  191.  
  192.     public LinkedList<GraphNodeNeighbor<E>> getNeighbors() {
  193.         return neighbors;
  194.     }
  195.  
  196.     public void setNeighbors(LinkedList<GraphNodeNeighbor<E>> neighbors) {
  197.         this.neighbors = neighbors;
  198.     }
  199.        
  200. }
  201.  
  202. class Graph<E> {
  203.  
  204.     int num_nodes;
  205.     GraphNode<E> adjList[];
  206.  
  207.     @SuppressWarnings("unchecked")
  208.     public Graph(int num_nodes, E[] list) {
  209.         this.num_nodes = num_nodes;
  210.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  211.         for (int i = 0; i < num_nodes; i++)
  212.             adjList[i] = new GraphNode<E>(i, list[i]);
  213.     }
  214.  
  215.     @SuppressWarnings("unchecked")
  216.     public Graph(int num_nodes) {
  217.         this.num_nodes = num_nodes;
  218.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  219.         for (int i = 0; i < num_nodes; i++)
  220.             adjList[i] = new GraphNode<E>(i, null);
  221.     }
  222.  
  223.     int adjacent(int x, int y) {
  224.         // proveruva dali ima vrska od jazelot so
  225.         // indeks x do jazelot so indeks y
  226.         return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
  227.     }
  228.  
  229.     void addEdge(int x, int y, float tezina) {
  230.         // dodava vrska od jazelot so indeks x do jazelot so indeks y so tezina
  231.         if (adjList[x].containsNeighbor(adjList[y])) {
  232.             adjList[x].updateNeighborWeight(adjList[y], tezina);
  233.         } else
  234.             adjList[x].addNeighbor(adjList[y], tezina);
  235.     }
  236.  
  237.     void deleteEdge(int x, int y) {
  238.         adjList[x].removeNeighbor(adjList[y]);
  239.     }
  240.    
  241.     // Funkcija za prebaruvanje na index na jazel so dadeno info vo listata na sosednost vo grafot
  242.     int searchIndex(String key)
  243.     {
  244.         for(int i=0;i<num_nodes;i++){
  245.             Iterator<GraphNodeNeighbor<E>> it = adjList[i].getNeighbors().iterator();
  246.             while (it.hasNext()) {
  247.                 GraphNodeNeighbor<E> pom = it.next();
  248.                 if(pom.node.getInfo().equals(key))
  249.                     return pom.node.getIndex();
  250.                
  251.             }
  252.        }
  253.        return -1;
  254.     }
  255.  
  256.  
  257.     float min_path(int from, int to)
  258.     {
  259.        
  260.         float[] odDo = dijkstra(from,to);
  261.         System.out.println();
  262.         float[] doOd = dijkstra(to,from);
  263.         System.out.println();
  264.  
  265.         return odDo[to] + doOd[from];
  266.     }
  267.    
  268.     float[] dijkstra(int from, int to) {
  269.  
  270.         int prv = from;
  271.         /* Minimalna cena do sekoe od teminjata */
  272.         float distance[] = new float[this.num_nodes];
  273.         /* dali za temeto e najdena konecnata (minimalna) cena */
  274.         int previous[] = new int[this.num_nodes];
  275.         boolean finalno[] = new boolean[this.num_nodes];
  276.         for (int i = 0; i < this.num_nodes; i++) {
  277.             distance[i] = -1;
  278.             finalno[i] = false;
  279.             previous[i] = Integer.MIN_VALUE;
  280.         }
  281.  
  282.         finalno[from] = true;
  283.         distance[from] = 0;
  284.  
  285.         /*
  286.          * vo sekoj cekor za edno teme se dobiva konecna minimalna cena
  287.          */
  288.         for (int i = 1; i < this.num_nodes; i++) {
  289.             /* za site sledbenici na from presmetaj ja cenata */
  290.             Iterator<GraphNodeNeighbor<E>> it = adjList[from].getNeighbors().iterator();
  291.             while (it.hasNext()) {
  292.                 GraphNodeNeighbor<E> pom = it.next();
  293.                 /* ako grankata kon sosedot nema konecna cena */
  294.                 if (!finalno[pom.node.getIndex()]) {
  295.                     /* ako ne e presmetana cena za temeto */
  296.                     if (distance[pom.node.getIndex()] <= 0) {
  297.                         distance[pom.node.getIndex()] = distance[from]
  298.                                 + pom.weight;
  299.                         previous[pom.node.getIndex()] = from;
  300.                     }
  301.                     /* inaku, ako e pronajdena poniska */
  302.                     else if (distance[from] + pom.weight < distance[pom.node
  303.                             .getIndex()]) {
  304.                         distance[pom.node.getIndex()] = distance[from]
  305.                                 + pom.weight;
  306.                         previous[pom.node.getIndex()] = from;
  307.  
  308.                     }
  309.                 }
  310.             }
  311.  
  312.             /* najdi teme so min. cena koja ne e konecna */
  313.             boolean minit = false; /* min. ne e inicijaliziran */
  314.             int k = -1;
  315.             float minc = -1;
  316.             /* proveri gi site teminja */
  317.             for (int j = 0; j < this.num_nodes; j++) {
  318.                 if (!finalno[j]&&distance[j] != -1) { /*ako cenata ne e  konecna*/
  319.                     if (!minit) { /* ako ne e inicijaliziran minimumot */
  320.                         minc = distance[k = j]; /* proglasi go ova e minimum */
  321.                         minit = true; /* oznaci deka min e inicijaliziran */
  322.                     }
  323.                     /* proveri dali e pronajdeno teme so pomala cena */
  324.                     else if (minc > distance[j]&&distance[j] > 0)
  325.                         minc = distance[k = j];
  326.                 }
  327.             }
  328.            
  329.             finalno[from = k] = true;
  330.         }
  331.         ArrayStack<E> S = new ArrayStack<>(1000);
  332.         int u = to;
  333.         while (previous[u] != Integer.MIN_VALUE) {
  334.             S.push(adjList[u].getInfo());
  335.             u = previous[u];
  336.            
  337.         }
  338.  
  339.        
  340.         System.out.print(adjList[prv].getInfo() + " ");
  341.         while (!S.isEmpty()) {
  342.             System.out.print(S.pop() + " ");
  343.         }
  344.  
  345.  
  346.         return distance;
  347.  
  348.     }
  349.  
  350.     ArrayStack<E> dijkstra2(int from, int to) {
  351.  
  352.         /* Minimalna cena do sekoe od teminjata */
  353.         float distance[] = new float[this.num_nodes];
  354.         /* dali za temeto e najdena konecnata (minimalna) cena */
  355.         boolean finalno[] = new boolean[this.num_nodes];
  356.         int previous[] = new int[this.num_nodes];
  357.         ArrayStack<E> S = new ArrayStack<>(this.num_nodes);
  358.         for (int i = 0; i < this.num_nodes; i++) {
  359.             distance[i] = -1;
  360.             finalno[i] = false;
  361.             previous[i] = Integer.MIN_VALUE;
  362.         }
  363.  
  364.         finalno[from] = true;
  365.         distance[from] = 0;
  366.  
  367.         /*
  368.          * vo sekoj cekor za edno teme se dobiva konecna minimalna cena
  369.          */
  370.         for (int i = 1; i < this.num_nodes; i++) {
  371.  
  372.             /* za site sledbenici na from presmetaj ja cenata */
  373.             Iterator<GraphNodeNeighbor<E>> it = adjList[from].getNeighbors().iterator();
  374.             while (it.hasNext()) {
  375.                 GraphNodeNeighbor<E> pom = it.next();
  376.                
  377.                
  378.                
  379.                 /* ako grankata kon sosedot nema konecna cena */
  380.                 if (!finalno[pom.node.getIndex()]) {
  381.                     /* ako ne e presmetana cena za temeto */
  382.                     if (distance[pom.node.getIndex()] <= 0) {
  383.                         distance[pom.node.getIndex()] = distance[from]
  384.                                 + pom.weight;
  385.                         previous[pom.node.getIndex()] = from;
  386.                     }
  387.                     /* inaku, ako e pronajdena poniska */
  388.                     else if (distance[from] + pom.weight < distance[pom.node
  389.                             .getIndex()]) {
  390.                         distance[pom.node.getIndex()] = distance[from]
  391.                                 + pom.weight;
  392.                         previous[pom.node.getIndex()] = from;
  393.  
  394.                     }
  395.                 }
  396.             }
  397.  
  398.             /* najdi teme so min. cena koja ne e konecna */
  399.             boolean minit = false; /* min. ne e inicijaliziran */
  400.             int k = -1;
  401.             float minc = -1;
  402.             /* proveri gi site teminja */
  403.             for (int j = 0; j < this.num_nodes; j++) {
  404.                 if (!finalno[j]&&distance[j] != -1) { /*ako cenata ne e  konecna*/
  405.                     if (!minit) { /* ako ne e inicijaliziran minimumot */
  406.                         minc = distance[k = j]; /* proglasi go ova e minimum */
  407.                         minit = true; /* oznaci deka min e inicijaliziran */
  408.                     }
  409.                     /* proveri dali e pronajdeno teme so pomala cena */
  410.                     else if (minc > distance[j]&&distance[j] > 0)
  411.                         minc = distance[k = j];
  412.                 }
  413.             }
  414.            
  415.             finalno[from = k] = true;
  416.         }
  417.        
  418.  
  419.         return  S;
  420.  
  421.     }
  422.  
  423.    
  424.    
  425.    
  426.     @Override
  427.     public String toString() {
  428.         String ret = new String();
  429.         for (int i = 0; i < this.num_nodes; i++)
  430.             ret += adjList[i] + "\n";
  431.         return ret;
  432.     }
  433.  
  434. }
  435.  
  436. public class Cities {
  437.  
  438.     public static void main(String[] args) throws Exception{   
  439.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  440.         int n_nodes = Integer.parseInt(br.readLine());
  441.        
  442.         String grad[] = new String[n_nodes];
  443.         Graph<String> g = new Graph<String>(n_nodes,grad);
  444.        
  445.         int n_edges = Integer.parseInt(br.readLine());
  446.        
  447.         int x,y; float tezina;
  448.         String xInfo, yInfo, pom[];
  449.         for(int i=0;i<n_edges;i++)
  450.         {
  451.             pom = br.readLine().split(" ");
  452.             x = Integer.parseInt(pom[0]);
  453.             xInfo = pom[1];
  454.             y = Integer.parseInt(pom[2]);
  455.             yInfo = pom[3];
  456.             g.adjList[x].setInfo(xInfo);
  457.             g.adjList[y].setInfo(yInfo);
  458.             tezina = Float.parseFloat(pom[4]);
  459.             g.addEdge(x,y,tezina);                  
  460.         }
  461.        
  462.         String start = br.readLine();
  463.         String end = br.readLine();
  464.         br.close();
  465.        
  466.         int from = g.searchIndex(start);
  467.         int to = g.searchIndex(end);    
  468.        
  469.         float min_p = g.min_path(from,to);
  470.         System.out.println(min_p);
  471.     }
  472.  
  473. }
Add Comment
Please, Sign In to add comment