Filip_Markoski

[ADSy] - Poseta / Travel

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