Advertisement
fensa08

#APS Lab 3/10

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