Advertisement
Filip_Markoski

[ADSx] - Desert Graph

Jan 27th, 2018
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.05 KB | None | 0 0
  1. import java.util.*;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4.  
  5.  
  6. class Edge {
  7.     private int fromVertex, toVertex;
  8.     private int weight1;
  9.     private int weight2;
  10.  
  11.     public Edge(int from, int to, int weight1, int weight2) {
  12.         this.fromVertex = from;
  13.         this.toVertex = to;
  14.         this.weight1 = weight1;
  15.         this.weight2 = weight2;
  16.     }
  17.  
  18.     public int getFrom() {
  19.         return this.fromVertex;
  20.     }
  21.  
  22.     public int getTo() {
  23.         return this.toVertex;
  24.     }
  25.  
  26.     public int getWeight1() {
  27.         return this.weight1;
  28.     }
  29.  
  30.     public int getWeight2() {
  31.         return this.weight2;
  32.     }
  33.  
  34.     public void setFrom(int from) {
  35.         this.fromVertex = from;
  36.     }
  37.  
  38.     public void setTo(int to) {
  39.         this.toVertex = to;
  40.     }
  41.  
  42.     public void setWeight1(int weight1) {
  43.         this.weight1 = weight1;
  44.     }
  45.  
  46.     public void setWeight2(int weight2) {
  47.         this.weight2 = weight2;
  48.     }
  49. }
  50.  
  51. class GraphNodeNeighbor<E> {
  52.     GraphNode<E> node;
  53.     int weight1;
  54.     int weight2;
  55.  
  56.     public GraphNodeNeighbor(GraphNode<E> node, int weight1, int weight2) {
  57.         this.node = node;
  58.         this.weight1 = weight1;
  59.         this.weight2 = weight2;
  60.     }
  61.  
  62.     public GraphNodeNeighbor(GraphNode<E> node) {
  63.         this.node = node;
  64.         this.weight1 = 0;
  65.         this.weight2 = 0;
  66.     }
  67.  
  68.     @Override
  69.     public boolean equals(Object obj) {
  70.         @SuppressWarnings("unchecked")
  71.         GraphNodeNeighbor<E> pom = (GraphNodeNeighbor<E>) obj;
  72.         return pom.node.equals(this.node);
  73.     }
  74. }
  75.  
  76. class GraphNode<E> {
  77.     private int index; //index (reden broj) na temeto vo grafot
  78.     private E info;
  79.     private LinkedList<GraphNodeNeighbor<E>> neighbors;
  80.  
  81.     public GraphNode(int index, E info) {
  82.         this.index = index;
  83.         this.info = info;
  84.         neighbors = new LinkedList<GraphNodeNeighbor<E>>();
  85.     }
  86.  
  87.     public boolean containsNeighbor(GraphNode<E> o) {
  88.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o, 0, 0);
  89.         return neighbors.contains(pom);
  90.     }
  91.  
  92.     public void addNeighbor(GraphNode<E> o, int weight1, int weight2) {
  93.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o, weight1, weight2);
  94.         neighbors.add(pom);
  95.     }
  96.  
  97.     public void removeNeighbor(GraphNode<E> o) {
  98.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o, 0, 0);
  99.         if (neighbors.contains(pom))
  100.             neighbors.remove(pom);
  101.     }
  102.  
  103.     @Override
  104.     public String toString() {
  105.         String ret = "INFO:" + info + " SOSEDI:";
  106.         for (int i = 0; i < neighbors.size(); i++)
  107.             ret += "(" + neighbors.get(i).node.info + "," + neighbors.get(i).weight1 + "," + neighbors.get(i).weight2 + ") ";
  108.         return ret;
  109.  
  110.     }
  111.  
  112.     public void updateNeighborWeight(GraphNode<E> o, int weight1, int weight2) {
  113.         Iterator<GraphNodeNeighbor<E>> i = neighbors.iterator();
  114.         while (i.hasNext()) {
  115.             GraphNodeNeighbor<E> pom = i.next();
  116.             if (pom.node.equals(o)) {
  117.                 pom.weight1 = weight1;
  118.                 pom.weight2 = weight2;
  119.             }
  120.         }
  121.  
  122.     }
  123.  
  124.     @Override
  125.     public boolean equals(Object obj) {
  126.         @SuppressWarnings("unchecked")
  127.         GraphNode<E> pom = (GraphNode<E>) obj;
  128.         return (pom.info.equals(this.info));
  129.     }
  130.  
  131.     public int getIndex() {
  132.         return index;
  133.     }
  134.  
  135.     public void setIndex(int index) {
  136.         this.index = index;
  137.     }
  138.  
  139.     public E getInfo() {
  140.         return info;
  141.     }
  142.  
  143.     public void setInfo(E info) {
  144.         this.info = info;
  145.     }
  146.  
  147.     public LinkedList<GraphNodeNeighbor<E>> getNeighbors() {
  148.         return neighbors;
  149.     }
  150.  
  151.     public void setNeighbors(LinkedList<GraphNodeNeighbor<E>> neighbors) {
  152.         this.neighbors = neighbors;
  153.     }
  154.  
  155. }
  156.  
  157. class Graph<E> {
  158.  
  159.     int num_nodes;
  160.     GraphNode<E> adjList[];
  161.  
  162.     @SuppressWarnings("unchecked")
  163.     public Graph(int num_nodes, E[] list) {
  164.         this.num_nodes = num_nodes;
  165.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  166.         for (int i = 0; i < num_nodes; i++)
  167.             adjList[i] = new GraphNode<E>(i, list[i]);
  168.     }
  169.  
  170.     @SuppressWarnings("unchecked")
  171.     public Graph(int num_nodes) {
  172.         this.num_nodes = num_nodes;
  173.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  174.         for (int i = 0; i < num_nodes; i++)
  175.             adjList[i] = new GraphNode<E>(i, null);
  176.     }
  177.  
  178.     int adjacent(int x, int y) {
  179.         // proveruva dali ima vrska od jazelot so
  180.         // indeks x do jazelot so indeks y
  181.         return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
  182.     }
  183.  
  184.     void addEdge(int x, int y, int tezina1, int tezina2) {
  185.         // dodava vrska od jazelot so indeks x do jazelot so indeks y so tezina
  186.         if (adjList[x].containsNeighbor(adjList[y])) {
  187.             adjList[x].updateNeighborWeight(adjList[y], tezina1, tezina2);
  188.         } else
  189.             adjList[x].addNeighbor(adjList[y], tezina1, tezina2);
  190.     }
  191.  
  192.     void deleteEdge(int x, int y) {
  193.         adjList[x].removeNeighbor(adjList[y]);
  194.     }
  195.  
  196.     // Funkcija za prebaruvanje na index na jazel so dadeno info vo listata na sosednost vo grafot
  197.     int searchIndex(String key) {
  198.         for (int i = 0; i < num_nodes; i++) {
  199.             Iterator<GraphNodeNeighbor<E>> it = adjList[i].getNeighbors().iterator();
  200.             while (it.hasNext()) {
  201.                 GraphNodeNeighbor<E> pom = it.next();
  202.                 if (pom.node.getInfo().equals(key))
  203.                     return pom.node.getIndex();
  204.  
  205.             }
  206.         }
  207.         return -1;
  208.     }
  209.  
  210.  
  211.     List<Edge> pustina(int oaza) {
  212.         // Vasiot kod ovde
  213.         // Moze da koristite dopolnitelni funkcii ako vi se potrebni
  214.         return prim(oaza);
  215.     }
  216.  
  217.  
  218.     /************************ PRIM **************************************************************************/
  219.  
  220.     // Metoda koja go naogja najmaloto rebro do
  221.     // teme na neposeten sosed
  222.     private Edge getMinimalEdge(boolean[] included) {
  223.         int index1 = Integer.MAX_VALUE, index2 = Integer.MAX_VALUE;
  224.         int minweight = Integer.MAX_VALUE;
  225.         int minweight1 = 0;
  226.         int minweight2 = 0;
  227.  
  228.         for (int i = 0; i < this.num_nodes; i++) {
  229.             if (included[i]) {
  230.                 // ako e vkluceno temeto i
  231.                 // izmini gi negovite nevkluceni sosedi
  232.                 Iterator<GraphNodeNeighbor<E>> it = adjList[i].getNeighbors()
  233.                         .iterator();
  234.                 while (it.hasNext()) {
  235.                     GraphNodeNeighbor<E> pom = it.next();
  236.                     // ako sosedot ne e poseten i ima do sega najmala tezina
  237.                     if (!included[pom.node.getIndex()]
  238.                             && pom.weight1 * pom.weight2 < minweight) {
  239.                         index1 = i;
  240.                         index2 = pom.node.getIndex();
  241.                         minweight = pom.weight1 * pom.weight2;
  242.                         minweight1 = pom.weight1;
  243.                         minweight2 = pom.weight2;
  244.                     }
  245.                 }
  246.             }
  247.         }
  248.  
  249.         if (minweight < Float.MAX_VALUE) {
  250.             Edge ret = new Edge(index1, index2, minweight1, minweight2);
  251.             return ret;
  252.         }
  253.         return null;
  254.     }
  255.  
  256.     List<Edge> prim(int start_index) {
  257.         // lista koja kje gi sodrzi MST rebra
  258.         List<Edge> mstEdges = new ArrayList<Edge>();
  259.  
  260.         boolean included[] = new boolean[this.num_nodes];
  261.         for (int i = 0; i < this.num_nodes; i++)
  262.             included[i] = false;
  263.  
  264.         included[start_index] = true;
  265.  
  266.         for (int i = 0; i < this.num_nodes - 1; i++) {
  267.             Edge e = this.getMinimalEdge(included);
  268.             if (e == null) {
  269.                 System.out.println("Ne mozat da se povrzat site jazli");
  270.                 break;
  271.             }
  272.             included[e.getFrom()] = included[e.getTo()] = true;
  273.             mstEdges.add(e);
  274.         }
  275.  
  276.         return mstEdges;
  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. public class Pustina {
  291.  
  292.     public static void main(String[] args) throws Exception {
  293.         String text = "4\n" +
  294.                 "4\n" +
  295.                 "0 Kairo 1 Oaza1 50 46\n" +
  296.                 "0 Kairo 2 Oaza2 50 48\n" +
  297.                 "1 Oaza1 3 Oaza3 50 45\n" +
  298.                 "2 Oaza2 3 Oaza3 40 50\n" +
  299.                 "Kairo";
  300.         //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  301.         Scanner br = new Scanner(text);
  302.         int n_nodes = Integer.parseInt(br.nextLine());
  303.  
  304.         String oazi[] = new String[n_nodes];
  305.         Graph<String> g = new Graph<String>(n_nodes, oazi);
  306.  
  307.         int n_edges = Integer.parseInt(br.nextLine());
  308.  
  309.         int x, y, tezina1, tezina2;
  310.         String xInfo, yInfo, pom[];
  311.         for (int i = 0; i < n_edges; i++) {
  312.             pom = br.nextLine().split(" ");
  313.             x = Integer.parseInt(pom[0]); //reden broj
  314.             xInfo = pom[1];
  315.             y = Integer.parseInt(pom[2]);
  316.             yInfo = pom[3]; //imeto na vtorata oaza
  317.             g.adjList[x].setInfo(xInfo);
  318.             g.adjList[y].setInfo(yInfo);
  319.             tezina1 = Integer.parseInt(pom[4]);
  320.             tezina2 = Integer.parseInt(pom[5]);
  321.             g.addEdge(x, y, tezina1, tezina2);   //se dodava rebro so informacii dolzina i temperatura
  322.             g.addEdge(y, x, tezina1, tezina2);
  323.         }
  324.  
  325.         String oaza = br.nextLine();
  326.  
  327.         System.out.println(g);
  328.  
  329.  
  330.         List<Edge> pateki = g.pustina(g.searchIndex(oaza)); //gi sodrzi site rebra
  331.         int dolzina = 0;
  332.         int i, j, tmp;
  333.  
  334.         // Sortiranje na vrskite za pecatenje
  335.         for (i = 0; i < n_nodes - 1; i++) {
  336.             if (pateki.get(i).getFrom() > pateki.get(i).getTo()) {
  337.                 tmp = pateki.get(i).getFrom();
  338.                 pateki.get(i).setFrom(pateki.get(i).getTo());
  339.                 pateki.get(i).setTo(tmp);
  340.             }
  341.         }
  342.  
  343.         for (i = 0; i < n_nodes - 2; i++)
  344.             for (j = i + 1; j < n_nodes - 1; j++)
  345.                 if ((pateki.get(i).getFrom() > pateki.get(j).getFrom()) || ((pateki.get(i).getFrom() == pateki.get(j).getFrom()) && (pateki.get(i).getTo() > pateki.get(j).getTo()))) {
  346.                     tmp = pateki.get(i).getFrom();
  347.                     pateki.get(i).setFrom(pateki.get(j).getFrom());
  348.                     pateki.get(j).setFrom(tmp);
  349.  
  350.                     tmp = pateki.get(i).getTo();
  351.                     pateki.get(i).setTo(pateki.get(j).getTo());
  352.                     pateki.get(j).setTo(tmp);
  353.  
  354.                     tmp = pateki.get(i).getWeight1();
  355.                     pateki.get(i).setWeight1(pateki.get(j).getWeight1());
  356.                     pateki.get(j).setWeight1(tmp);
  357.  
  358.                     tmp = pateki.get(i).getWeight2();
  359.                     pateki.get(i).setWeight2(pateki.get(j).getWeight2());
  360.                     pateki.get(j).setWeight2(tmp);
  361.  
  362.                 }
  363.  
  364.         ListIterator<Edge> it = pateki.listIterator();
  365.  
  366.         while (it.hasNext()) {
  367.             Edge e = it.next();
  368.             dolzina += e.getWeight1();
  369.             System.out.println(g.adjList[e.getFrom()].getInfo() + " " + g.adjList[e.getTo()].getInfo() + " " + e.getWeight1() + " " + e.getWeight2());
  370.         }
  371.  
  372.         System.out.println(dolzina);
  373.     }
  374.  
  375. }
  376. /**
  377.  * Пустина Задача 3 (0 / 0)
  378.  * Некоја група на авантуристи сакаат да патуваат низ пустината Сахара, поминувајќи низ поважните оази кои се сметаат како атракција во неа.
  379.  * Патувањето низ пустина може да биде многу опасно поради долгите патеки кои треба да се поминат низ високи температури. Затоа авантуристите
  380.  * сакаат да го испланираат патувањето многу внимателно. Еден од клучните фактори за патување е да се патува од една оаза до друга поминувајќи
  381.  * патека низ предел кој има што помала должина и што помала средна температура. Треба да им помогнете на авантуристите за да го испланираат
  382.  * патувањето, така што да може да ги поминат сите оази (атракции), минимизирајќи ја вкупната должина на тие патеки, и патувајќи по што е можно
  383.  * помала средна температура. Ако постојат повеќе вакви патувања низ сите оази со иста вкупна минимална должина, треба да се избере најмалото
  384.  * по средна температура. Да се напише алгоритам кој ќе им помогне на авантуристите кои тргнуваат од својата почетна оаза да си го испланираат
  385.  * патувањето, така што на излез ќе се вратат патеките кои треба да се поминат за да се оптимизира вкупната должина.
  386.  * <p>
  387.  * Влез: Во првиот ред од влезот е даден број на оази во пустината n. Во вториот ред од влезот е даден бројот на патеки m. Во следните m редови
  388.  * се дадени патеките во облик: реден број на прва оаза, име на прва оаза, реден број на втора оаза, име на втора оаза, должина на патеката,
  389.  * средна температура на патеката. Во последниот ред е дадено името на оазата од која се тргнува.
  390.  * <p>
  391.  * Излез: На излез треба да се испечатат патeките по кои треба да се патува и нивната вкупната должина.
  392.  * <p>
  393.  * Име на класата: Pustina
  394.  * <p>
  395.  * Делумно решение: Задачата се смета за делумно решена доколку се поминати 5 тест примери.
  396.  * <p>
  397.  * Забелешка: При реализација на задачите МОРА да се користат дадените структури, а не да користат помошни структури како низи или сл.
  398.  * <p>
  399.  * <p>
  400.  * Пример влез
  401.  * 4
  402.  * 4
  403.  * 0 Kairo 1 Oaza1 50 46
  404.  * 0 Kairo 2 Oaza2 50 48
  405.  * 1 Oaza1 3 Oaza3 50 45
  406.  * 2 Oaza2 3 Oaza3 40 50
  407.  * Kairo
  408.  * Пример излез
  409.  * Kairo Oaza1 50 46
  410.  * Oaza1 Oaza3 50 45
  411.  * Oaza2 Oaza3 40 50
  412.  * 140
  413.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement