Advertisement
teodor_dalavera

Градови - 0% - Само најкраток пат

Dec 23rd, 2017
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.54 KB | None | 0 0
  1. package Cities;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.*;
  7.  
  8. class Graph<E> {
  9.  
  10.     int num_nodes;
  11.     GraphNode<E> adjList[];
  12.  
  13.     @SuppressWarnings("unchecked")
  14.     public Graph(int num_nodes, String list) {
  15.         this.num_nodes = num_nodes;
  16.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  17.         for (int i = 0; i < num_nodes; i++)
  18.             adjList[i] = new GraphNode<E>(i, list);
  19.     }
  20.  
  21.     @SuppressWarnings("unchecked")
  22.     public Graph(int num_nodes) {
  23.         this.num_nodes = num_nodes;
  24.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  25.         for (int i = 0; i < num_nodes; i++)
  26.             adjList[i] = new GraphNode<E>(i, null);
  27.     }
  28.  
  29.     int adjacent(int x, int y) {
  30.         // proveruva dali ima vrska od jazelot so
  31.         // indeks x do jazelot so indeks y
  32.         return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
  33.     }
  34.  
  35.     void addEdge(int x, int y, float tezina) {
  36.         // dodava vrska od jazelot so indeks x do jazelot so indeks y so tezina
  37.         if (adjList[x].containsNeighbor(adjList[y])) {
  38.             adjList[x].updateNeighborWeight(adjList[y], tezina);
  39.         } else
  40.             adjList[x].addNeighbor(adjList[y], tezina);
  41.     }
  42.  
  43.     void deleteEdge(int x, int y) {
  44.         adjList[x].removeNeighbor(adjList[y]);
  45.     }
  46.  
  47.     /*************************** KRUSKAL ***********************************************************************/
  48.     // Metoda koja generira niza od site rebra vo grafot
  49.     public Edge[] getAllEdges() {
  50.         int totalEdges = 0;
  51.         for (int i = 0; i < this.num_nodes; i++) {
  52.             // za sekoe teme go dodavame brojot na sosedi koi gi ima
  53.             totalEdges += this.adjList[i].getNeighbors().size();
  54.         }
  55.  
  56.         // System.out.println("METODA: Imame vk "+totalEdges+" rebra");
  57.  
  58.         Edge[] edges = new Edge[totalEdges];
  59.         int index = 0;
  60.         for (int i = 0; i < this.num_nodes; i++) {
  61.             for (int j = 0; j < this.adjList[i].getNeighbors().size(); j++) {
  62.                 int index1 = this.adjList[i].getIndex();
  63.                 // se zemaat indeksot i tezinata na j-ot sosed na temeto i
  64.                 int index2 = this.adjList[i].getNeighbors().get(j).node
  65.                         .getIndex();
  66.                 float weight = this.adjList[i].getNeighbors().get(j).weight;
  67.                 edges[index++] = new Edge(index1, index2, weight);
  68.             }
  69.         }
  70.  
  71.         return edges;
  72.     }
  73.  
  74.     // Metoda koja gi sortira site rebra
  75.     private Edge[] sortEdges(Edge[] edges) {
  76.         for (int i = 0; i < edges.length - 1; i++) {
  77.             for (int j = i + 1; j < edges.length; j++) {
  78.                 if (edges[i].getWeight() > edges[j].getWeight()) {
  79.                     Edge tmp = edges[i];
  80.                     edges[i] = edges[j];
  81.                     edges[j] = tmp;
  82.                 }
  83.             }
  84.         }
  85.  
  86.         return edges;
  87.     }
  88.  
  89.     // Metoda koja pravi unija na dve drva
  90.     private int[] union(int u, int v, int[] vrski) {
  91.         int findWhat, replaceWith;
  92.  
  93.         if (u < v) {
  94.             findWhat = vrski[v];
  95.             replaceWith = vrski[u];
  96.         } else {
  97.             findWhat = vrski[u];
  98.             replaceWith = vrski[v];
  99.         }
  100.  
  101.         // za dvete poddrva stava ist index
  102.         // t.e. gi spojuva
  103.         for (int i = 0; i < vrski.length; i++) {
  104.             if (vrski[i] == findWhat) {
  105.                 vrski[i] = replaceWith;
  106.             }
  107.         }
  108.         return vrski;
  109.     }
  110.  
  111.     List<Edge> kruskal() {
  112.         /*
  113.          * Pomoshna niza za sledenje na kreiranite drva Ako dve teminja se del
  114.          * od isto poddrvo togash imaat ista vrednost vo nizata
  115.          */
  116.         int vrski[] = new int[this.num_nodes];
  117.  
  118.         // niza koja gi sodrzi site rebra
  119.         Edge[] edges = this.getAllEdges();
  120.         // se sortiraat rebrata spored tezinite vo neopagjacki redosled
  121.         edges = this.sortEdges(edges);
  122.  
  123.         // inicijalizacija na pomosnata niza za evidencija,
  124.         // sekoj jazel si e posebno drvo
  125.         for (int i = 0; i < this.num_nodes; i++)
  126.             vrski[i] = i;
  127.  
  128.         // lista koja kje gi sodrzi MST rebra
  129.         List<Edge> mstEdges = new ArrayList<Edge>();
  130.  
  131.         for (int i = 0; i < edges.length; i++) {
  132.             // za sekoe rebro vo sortiran redosled
  133.             Edge e = edges[i];
  134.  
  135.             if (vrski[e.getFrom()] != vrski[e.getTo()]) {
  136.                 // ako teminjata na ova rebro ne se vo isto poddrvo
  137.                 // ova rebro e MST rebro
  138.                 mstEdges.add(e);
  139.                 // sega dvete teminja treba da se vo isto poddrvo
  140.                 // t.e se pravi merge (unija) t.s. vo nizata vrski
  141.                 // za site elementi od dvete poddrva
  142.                 // go setira istiot (najmal) element od dvete poddrva
  143.                 vrski = this.union(e.getFrom(), e.getTo(), vrski);
  144.             }
  145.  
  146.             // ako sme dodale num_nodes-1 rebra moze da prestaneme
  147.             if (mstEdges.size() == (this.num_nodes - 1))
  148.                 break;
  149.         }
  150.  
  151.         return mstEdges;
  152.     }
  153.  
  154.     /*******************************************************************************************************/
  155.  
  156.     /************************ PRIM **************************************************************************/
  157.  
  158.     // Metoda koja go naogja najmaloto rebro do
  159.     // teme na neposeten sosed
  160.     private Edge getMinimalEdge(boolean[] included) {
  161.         int index1 = Integer.MAX_VALUE, index2 = Integer.MAX_VALUE;
  162.         float minweight = Float.MAX_VALUE;
  163.  
  164.         for (int i = 0; i < this.num_nodes; i++) {
  165.             if (included[i]) {
  166.                 // ako e vkluceno temeto i
  167.                 // izmini gi negovite nevkluceni sosedi
  168.                 Iterator<GraphNodeNeighbor<E>> it = adjList[i].getNeighbors()
  169.                         .iterator();
  170.                 while (it.hasNext()) {
  171.                     GraphNodeNeighbor<E> pom = it.next();
  172.                     // ako sosedot ne e poseten i ima do sega najmala tezina
  173.                     if (!included[pom.node.getIndex()]
  174.                             && pom.weight < minweight) {
  175.                         index1 = i;
  176.                         index2 = pom.node.getIndex();
  177.                         minweight = pom.weight;
  178.                     }
  179.                 }
  180.             }
  181.         }
  182.  
  183.         if (minweight < Float.MAX_VALUE) {
  184.             Edge ret = new Edge(index1, index2, minweight);
  185.             return ret;
  186.         }
  187.         return null;
  188.     }
  189.  
  190.     List<Edge> prim(int start_index) {
  191.         // lista koja kje gi sodrzi MST rebra
  192.         List<Edge> mstEdges = new ArrayList<Edge>();
  193.  
  194.         boolean included[] = new boolean[this.num_nodes];
  195.         for (int i = 0; i < this.num_nodes; i++)
  196.             included[i] = false;
  197.  
  198.         included[start_index] = true;
  199.  
  200.         for (int i = 0; i < this.num_nodes - 1; i++) {
  201.             Edge e = this.getMinimalEdge(included);
  202.             if (e == null) {
  203.                 System.out.println("Ne mozat da se povrzat site jazli");
  204.                 break;
  205.             }
  206.             included[e.getFrom()] = included[e.getTo()] = true;
  207.             mstEdges.add(e);
  208.         }
  209.  
  210.         return mstEdges;
  211.     }
  212.  
  213.     /*******************************************************************************************************/
  214.     /***************** DIJKSTRA ******************************************************************************/
  215.  
  216.     float[] dijkstra(int from) {
  217.  
  218.         /* Minimalna cena do sekoj od teminjata */
  219.         float distance[] = new float[this.num_nodes];
  220.         /* dali za temeto e najdena konecnata (minimalna) cena */
  221.         boolean finalno[] = new boolean[this.num_nodes];
  222.         for (int i = 0; i < this.num_nodes; i++) {
  223.             distance[i] = -1;
  224.             finalno[i] = false;
  225.         }
  226.  
  227.         finalno[from] = true;
  228.         distance[from] = 0;
  229.  
  230.         /*
  231.          * vo sekoj cekor za edno teme se dobiva konecna minimalna cena
  232.          */
  233.         for (int i = 1; i < this.num_nodes; i++) {
  234.             /* za site sledbenici na from presmetaj ja cenata */
  235.             Iterator<GraphNodeNeighbor<E>> it = adjList[from].getNeighbors()
  236.                     .iterator();
  237.             while (it.hasNext()) {
  238.                 GraphNodeNeighbor<E> pom = it.next();
  239.                 /* ako grankata kon sosedot nema konecna cena */
  240.                 if (!finalno[pom.node.getIndex()]) {
  241.                     /* ako ne e presmetana cena za temeto */
  242.                     if (distance[pom.node.getIndex()] <= 0) {
  243.                         distance[pom.node.getIndex()] = distance[from]
  244.                                 + pom.weight;
  245.                     }
  246.                     /* inaku, ako e pronajdena poniska */
  247.                     else if (distance[from] + pom.weight < distance[pom.node
  248.                             .getIndex()]) {
  249.                         distance[pom.node.getIndex()] = distance[from]
  250.                                 + pom.weight;
  251.                     }
  252.                 }
  253.             }
  254.  
  255.             /* najdi teme so min. cena koja ne e konecna */
  256.             boolean minit = false; /* min. ne e inicijaliziran */
  257.             int k = -1;
  258.             float minc = -1;
  259.             /* proveri gi site teminja */
  260.             for (int j = 0; j < this.num_nodes; j++) {
  261.                 if (!finalno[j] && distance[j] != -1) { /*ako cenata ne e  konecna*/
  262.                     if (!minit) { /* ako ne e inicijaliziran minimumot */
  263.                         minc = distance[k = j]; /* proglasi go ova e minimum */
  264.                         minit = true; /* oznaci deka min e inicijaliziran */
  265.                     }
  266.                     /* proveri dali e pronajdeno teme so pomala cena */
  267.                     else if (minc > distance[j] && distance[j] > 0)
  268.                         minc = distance[k = j];
  269.                 }
  270.             }
  271.             finalno[from = k] = true;
  272.         }
  273.  
  274.         return distance;
  275.  
  276.     }
  277.  
  278.     /*******************************************************************************************************/
  279.  
  280.     @Override
  281.     public String toString() {
  282.         String ret = new String();
  283.         for (int i = 0; i < this.num_nodes; i++)
  284.             ret += adjList[i] + "\n";
  285.         return ret;
  286.     }
  287.  
  288. }
  289.  
  290. class Edge{
  291.     private int fromVertex, toVertex;
  292.     private float weight;
  293.     public Edge(int from, int to, float weight){
  294.         this.fromVertex = from;
  295.         this.toVertex = to;
  296.         this.weight = weight;
  297.     }
  298.    
  299.     public int getFrom(){
  300.         return this.fromVertex;
  301.     }
  302.     public int getTo(){
  303.         return this.toVertex;
  304.     }
  305.     public float getWeight(){
  306.         return this.weight;
  307.     }
  308. }
  309.  
  310.  
  311.  
  312. class GraphNode<E> {
  313.     private int index; //index (reden broj) na temeto vo grafot
  314.     private String info;
  315.     private LinkedList<GraphNodeNeighbor<E>> neighbors;
  316.    
  317.     public GraphNode(int index, String info) {
  318.         this.index = index;
  319.         this.info = info;
  320.         neighbors = new LinkedList<GraphNodeNeighbor<E>>();
  321.     }
  322.    
  323.     public boolean containsNeighbor(GraphNode<E> o){
  324.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o,0);
  325.         return neighbors.contains(pom);
  326.     }
  327.    
  328.     public void addNeighbor(GraphNode<E> o, float weight){
  329.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o,weight);
  330.         neighbors.add(pom);
  331.     }
  332.    
  333.     public void removeNeighbor(GraphNode<E> o){
  334.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o,0);
  335.         if(neighbors.contains(pom))
  336.             neighbors.remove(pom);
  337.     }
  338.    
  339.     @Override
  340.     public String toString() {
  341.         String ret= "INFO:"+info+" SOSEDI:";
  342.         for(int i=0;i<neighbors.size();i++)
  343.         ret+="("+neighbors.get(i).node.info+","+neighbors.get(i).weight+") ";
  344.         return ret;
  345.        
  346.     }
  347.  
  348.     public void updateNeighborWeight(GraphNode<E> o, float weight){
  349.         Iterator<GraphNodeNeighbor<E>> i = neighbors.iterator();
  350.         while(i.hasNext()){
  351.             GraphNodeNeighbor<E> pom = i.next();
  352.             if(pom.node.equals(o))
  353.                 pom.weight = weight;
  354.         }
  355.            
  356.     }
  357.  
  358.     @Override
  359.     public boolean equals(Object obj) {
  360.         @SuppressWarnings("unchecked")
  361.         GraphNode<E> pom = (GraphNode<E>)obj;
  362.         return (pom.info.equals(this.info));
  363.     }
  364.  
  365.     public int getIndex() {
  366.         return index;
  367.     }
  368.  
  369.     public void setIndex(int index) {
  370.         this.index = index;
  371.     }
  372.  
  373.     public String getInfo() {
  374.         return info;
  375.     }
  376.  
  377.     public void setInfo(String a) {
  378.         this.info = a;
  379.     }
  380.  
  381.     public LinkedList<GraphNodeNeighbor<E>> getNeighbors() {
  382.         return neighbors;
  383.     }
  384.  
  385.     public void setNeighbors(LinkedList<GraphNodeNeighbor<E>> neighbors) {
  386.         this.neighbors = neighbors;
  387.     }
  388.    
  389.    
  390.    
  391. }
  392.  
  393. class GraphNodeNeighbor<E> {
  394.     GraphNode<E> node;
  395.     float weight;
  396.    
  397.     public GraphNodeNeighbor(GraphNode<E> node, float weight) {
  398.         this.node = node;
  399.         this.weight = weight;
  400.     }
  401.    
  402.     public GraphNodeNeighbor(GraphNode<E> node) {
  403.         this.node = node;
  404.         this.weight = 0;
  405.     }
  406.  
  407.     @Override
  408.     public boolean equals(Object obj) {
  409.         @SuppressWarnings("unchecked")
  410.         GraphNodeNeighbor<E> pom = (GraphNodeNeighbor<E>)obj;
  411.         return pom.node.equals(this.node);
  412.     }
  413.    
  414.    
  415.    
  416.    
  417.  
  418. }
  419.  
  420. interface Queue<E> {
  421.  
  422.     // Elementi na redicata se objekti od proizvolen tip.
  423.  
  424.     // Metodi za pristap:
  425.  
  426.     public boolean isEmpty ();
  427.         // Vrakja true ako i samo ako redicata e prazena.
  428.  
  429.     public int size ();
  430.         // Ja vrakja dolzinata na redicata.
  431.  
  432.     public E peek ();
  433.         // Go vrakja elementot na vrvot t.e. pocetokot od redicata.
  434.  
  435.     // Metodi za transformacija:
  436.  
  437.     public void clear ();
  438.         // Ja prazni redicata.
  439.  
  440.     public void enqueue (E x);
  441.         // Go dodava x na kraj od redicata.
  442.  
  443.     public E dequeue ();
  444.         // Go otstranuva i vrakja pochetniot element na redicata.
  445.  
  446. }
  447.  
  448. class LinkedQueue<E> implements Queue<E> {
  449.  
  450.     // Redicata e pretstavena na sledniot nacin:
  451.     // length go sodrzi brojot na elementi.
  452.     // Elementite se zachuvuvaat vo jazli dod SLL
  453.     // front i rear se linkovi do prviot i posledniot jazel soodvetno.
  454.     SLLNode<E> front, rear;
  455.     int length;
  456.  
  457.     // Konstruktor ...
  458.  
  459.     public LinkedQueue () {
  460.         clear();
  461.     }
  462.  
  463.     public boolean isEmpty () {
  464.         // Vrakja true ako i samo ako redicata e prazena.
  465.         return (length == 0);
  466.     }
  467.  
  468.     public int size () {
  469.         // Ja vrakja dolzinata na redicata.
  470.         return length;
  471.     }
  472.  
  473.     public E peek () {
  474.         // Go vrakja elementot na vrvot t.e. pocetokot od redicata.
  475.         if (front == null)
  476.             throw new NoSuchElementException();
  477.         return front.element;
  478.     }
  479.  
  480.     public void clear () {
  481.         // Ja prazni redicata.
  482.         front = rear = null;
  483.         length = 0;
  484.     }
  485.  
  486.     public void enqueue (E x) {
  487.         // Go dodava x na kraj od redicata.
  488.         SLLNode<E> latest = new SLLNode<E>(x, null);
  489.         if (rear != null) {
  490.             rear.succ = latest;
  491.             rear = latest;
  492.         } else
  493.             front = rear = latest;
  494.         length++;
  495.     }
  496.  
  497.     public E dequeue () {
  498.         // Go otstranuva i vrakja pochetniot element na redicata.
  499.         if (front != null) {
  500.             E frontmost = front.element;
  501.             front = front.succ;
  502.             if (front == null)  rear = null;
  503.             length--;
  504.             return frontmost;
  505.         } else
  506.             throw new NoSuchElementException();
  507.     }
  508.  
  509. }
  510.  
  511. class SLLNode<E> {
  512.     protected E element;
  513.     protected SLLNode<E> succ;
  514.  
  515.     public SLLNode(E elem, SLLNode<E> succ) {
  516.         this.element = elem;
  517.         this.succ = succ;
  518.     }
  519.  
  520.     @Override
  521.     public String toString() {
  522.         return element.toString();
  523.     }
  524. }
  525.  
  526.  
  527. public class Cities {
  528.  
  529.     public static void main(String[] args) throws IOException {
  530.  
  531.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  532.         String expr = br.readLine();
  533.         String[] exp;
  534.        
  535.         int teminja = Integer.parseInt(expr);
  536.         expr = br.readLine();
  537.         int rebra = Integer.parseInt(expr);
  538.        
  539.         Graph<Integer> g = new Graph<>(teminja);
  540.         Hashtable<String, Integer> h = new Hashtable<>();
  541.        
  542.         for(int i=0; i<rebra; i++){
  543.             expr = br.readLine();
  544.             exp = expr.split(" ");
  545.             int x = Integer.parseInt(exp[0]);
  546.             String a = exp[1];
  547.             h.put(a, x);
  548.             int y = Integer.parseInt(exp[2]);
  549.             String b = exp[3];
  550.             h.put(b,  y);
  551.             float tezina = Float.parseFloat(exp[4]);
  552.             g.adjList[x].setInfo(a);
  553.             g.adjList[y].setInfo(b);
  554.             g.addEdge(x, y, tezina);
  555.         }
  556.        
  557.         int start = h.get(br.readLine());
  558.         int end = h.get(br.readLine());
  559.        
  560.         float[] st = g.dijkstra(start);
  561.         float[] ed = g.dijkstra(end);
  562.        
  563.         float stt = st[end];
  564.         float edd = ed[start];
  565.        
  566.         System.out.println(stt + edd);
  567.        
  568.         br.close();
  569.  
  570.     }
  571.  
  572. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement