teodor_dalavera

Хиерархија

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