Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.24 KB | None | 0 0
  1. import java.util.*;
  2. class Graph<E> {
  3.  
  4. int num_nodes;
  5. GraphNode<E> adjList[];
  6.  
  7. @SuppressWarnings("unchecked")
  8. public Graph(int num_nodes, E[] list) {
  9. this.num_nodes = num_nodes;
  10. adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  11. for (int i = 0; i < num_nodes; i++)
  12. adjList[i] = new GraphNode<E>(i, list[i]);
  13. }
  14.  
  15. @SuppressWarnings("unchecked")
  16. public Graph(int num_nodes) {
  17. this.num_nodes = num_nodes;
  18. adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  19. for (int i = 0; i < num_nodes; i++)
  20. adjList[i] = new GraphNode<E>(i, null);
  21. }
  22.  
  23. int adjacent(int x, int y) {
  24. // proveruva dali ima vrska od jazelot so
  25. // indeks x do jazelot so indeks y
  26. return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
  27. }
  28.  
  29. void addEdge(int x, int y, float tezina) {
  30. // dodava vrska od jazelot so indeks x do jazelot so indeks y so tezina
  31. // i obratno
  32. if (adjList[x].containsNeighbor(adjList[y])) {
  33. adjList[x].updateNeighborWeight(adjList[y], tezina);
  34. adjList[y].updateNeighborWeight(adjList[x], tezina);
  35. } else{
  36. adjList[x].addNeighbor(adjList[y], tezina);
  37. adjList[y].addNeighbor(adjList[x], tezina);
  38. }
  39. }
  40.  
  41. void deleteEdge(int x, int y) {
  42. adjList[x].removeNeighbor(adjList[y]);
  43. adjList[y].removeNeighbor(adjList[x]);
  44. }
  45.  
  46. /*************************** KRUSKAL ***********************************************************************/
  47.  
  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. totalEdges /= 2; //bidejki e nenasocen graf, sekoe rebro se javuva kaj dve teminja
  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. if(index2>index1) //bidejki grafot e nenasocen, da ne go zemame sekoe rebro dva pati
  68. edges[index++] = new Edge(index1, index2, weight);
  69. }
  70. }
  71.  
  72. return edges;
  73. }
  74.  
  75. // Metoda koja gi sortira site rebra
  76. private void sortEdges(Edge[] edges) {
  77. for (int i = 0; i < edges.length - 1; i++) {
  78. for (int j = i + 1; j < edges.length; j++) {
  79. if (edges[i].getWeight() > edges[j].getWeight()) {
  80. Edge tmp = edges[i];
  81. edges[i] = edges[j];
  82. edges[j] = tmp;
  83. }
  84. }
  85. }
  86.  
  87. }
  88.  
  89. //Metoda koja pravi unija na dve drva
  90. private void 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. }
  97. else{
  98. findWhat = vrski[u];
  99. replaceWith = vrski[v];
  100. }
  101.  
  102. //za dvete poddrva stava ist index
  103. //vo vrski t.e. gi spojuva
  104. for(int i=0; i<vrski.length; i++){
  105. if(vrski[i] == findWhat){
  106. vrski[i] = replaceWith;
  107. }
  108. }
  109. }
  110.  
  111. List<Edge> kruskal() {
  112. /*
  113. * Pomoshna niza za sledenje na kreiranite drva
  114. * Ako dve teminja se del od isto poddrvo
  115. * togash imaat ista vrednost vo nizata
  116. */
  117. int vrski[] = new int[this.num_nodes];
  118.  
  119. // niza koja gi sodrzi site rebra
  120. Edge[] edges = this.getAllEdges();
  121. // se sortiraat rebrata spored tezinite vo neopagjacki redosled
  122. this.sortEdges(edges);
  123.  
  124. // inicijalizacija na pomosnata niza za evidencija,
  125. // sekoj jazel si e posebno drvo
  126. for (int i = 0; i < this.num_nodes; i++)
  127. vrski[i] = i;
  128.  
  129. // lista koja kje gi sodrzi MST rebra
  130. List<Edge> mstEdges = new ArrayList<Edge>();
  131.  
  132. for(int i=0; i<edges.length; i++){
  133. //za sekoe rebro vo sortiran redosled
  134. Edge e = edges[i];
  135.  
  136. if(vrski[e.getFrom()] != vrski[e.getTo()]){
  137. //ako teminjata na ova rebro ne se vo isto poddrvo
  138. //ova rebro e MST rebro
  139. mstEdges.add(e);
  140. //sega dvete teminja treba da se vo isto poddrvo
  141. //t.e se pravi merge (unija) t.s. vo nizata vrski
  142. //za site elementi od dvete poddrva
  143. //go setira istiot (najmal) element od dvete poddrva
  144. //vrski = this.union(e.getFrom(), e.getTo(), vrski);
  145. this.union(e.getFrom(), e.getTo(), vrski);
  146. }
  147.  
  148. //ako sme dodale num_nodes-1 rebra moze da prestaneme
  149. if(mstEdges.size()==(this.num_nodes-1))
  150. break;
  151. }
  152.  
  153. return mstEdges;
  154. }
  155.  
  156. /*******************************************************************************************************/
  157. /************************ PRIM **************************************************************************/
  158.  
  159. //Metoda koja go naogja najmaloto rebro do
  160. //teme na neposeten sosed
  161. private Edge getMinimalEdge(boolean[] included){
  162. int index1 = Integer.MAX_VALUE, index2 = Integer.MAX_VALUE;
  163. float minweight = Float.MAX_VALUE;
  164.  
  165. for(int i=0;i<this.num_nodes;i++){
  166. if(included[i]){
  167. //ako e vkluceno temeto i
  168. //izmini gi negovite nevkluceni sosedi
  169. Iterator<GraphNodeNeighbor<E>> it = adjList[i].getNeighbors().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()]&&pom.weight<minweight){
  174. index1 = i;
  175. index2 = pom.node.getIndex();
  176. minweight = pom.weight;
  177. }
  178. }
  179. }
  180. }
  181.  
  182. if(minweight<Float.MAX_VALUE){
  183. Edge ret = new Edge(index1, index2, minweight);
  184. return ret;
  185. }
  186. return null;
  187. }
  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 sekoe 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().iterator();
  236. while (it.hasNext()) {
  237. GraphNodeNeighbor<E> pom = it.next();
  238. /* ako grankata kon sosedot nema konecna cena */
  239. if (!finalno[pom.node.getIndex()]) {
  240. /* ako ne e presmetana cena za temeto */
  241. if (distance[pom.node.getIndex()] <= 0) {
  242. distance[pom.node.getIndex()] = distance[from]
  243. + pom.weight;
  244. }
  245. /* inaku, ako e pronajdena poniska */
  246. else if (distance[from] + pom.weight < distance[pom.node
  247. .getIndex()]) {
  248. distance[pom.node.getIndex()] = distance[from]
  249. + pom.weight;
  250. }
  251. }
  252. }
  253.  
  254. /* najdi teme so min. cena koja ne e konecna */
  255. boolean minit = false; /* min. ne e inicijaliziran */
  256. int k = -1;
  257. float minc = -1;
  258. /* proveri gi site teminja */
  259. for (int j = 0; j < this.num_nodes; j++) {
  260. if (!finalno[j] && distance[j] != -1) { /*ako cenata ne e konecna*/
  261. if (!minit) { /* ako ne e inicijaliziran minimumot */
  262. minc = distance[k = j]; /* proglasi go ova e minimum */
  263. minit = true; /* oznaci deka min e inicijaliziran */
  264. }
  265. /* proveri dali e pronajdeno teme so pomala cena */
  266. else if (minc > distance[j] && distance[j] > 0)
  267. minc = distance[k = j];
  268. }
  269. }
  270. finalno[from = k] = true;
  271. }
  272.  
  273. return distance;
  274.  
  275. }
  276.  
  277. /*******************************************************************************************************/
  278.  
  279. @Override
  280. public String toString() {
  281. String ret = new String();
  282. for (int i = 0; i < this.num_nodes; i++)
  283. ret += adjList[i] + "\n";
  284. return ret;
  285. }
  286.  
  287. }
  288. class GraphNode<E> {
  289. private int index; //index (reden broj) na temeto vo grafot
  290. private E info;
  291. private LinkedList<GraphNodeNeighbor<E>> neighbors;
  292.  
  293. public GraphNode(int index, E info) {
  294. this.index = index;
  295. this.info = info;
  296. neighbors = new LinkedList<GraphNodeNeighbor<E>>();
  297. }
  298.  
  299. public boolean containsNeighbor(GraphNode<E> o){
  300. GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o,0);
  301. return neighbors.contains(pom);
  302. }
  303.  
  304. public void addNeighbor(GraphNode<E> o, float weight){
  305. GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o,weight);
  306. neighbors.add(pom);
  307. }
  308.  
  309. public void removeNeighbor(GraphNode<E> o){
  310. GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o,0);
  311. if(neighbors.contains(pom))
  312. neighbors.remove(pom);
  313. }
  314.  
  315. @Override
  316. public String toString() {
  317. String ret= "INFO:"+info+" SOSEDI:";
  318. for(int i=0;i<neighbors.size();i++)
  319. ret+="("+neighbors.get(i).node.info+","+neighbors.get(i).weight+") ";
  320. return ret;
  321.  
  322. }
  323.  
  324. public void updateNeighborWeight(GraphNode<E> o, float weight){
  325. Iterator<GraphNodeNeighbor<E>> i = neighbors.iterator();
  326. while(i.hasNext()){
  327. GraphNodeNeighbor<E> pom = i.next();
  328. if(pom.node.equals(o))
  329. pom.weight = weight;
  330. }
  331.  
  332. }
  333.  
  334. @Override
  335. public boolean equals(Object obj) {
  336. @SuppressWarnings("unchecked")
  337. GraphNode<E> pom = (GraphNode<E>)obj;
  338. return (pom.info.equals(this.info));
  339. }
  340.  
  341. public int getIndex() {
  342. return index;
  343. }
  344.  
  345. public void setIndex(int index) {
  346. this.index = index;
  347. }
  348.  
  349. public E getInfo() {
  350. return info;
  351. }
  352.  
  353. public void setInfo(E info) {
  354. this.info = info;
  355. }
  356.  
  357. public LinkedList<GraphNodeNeighbor<E>> getNeighbors() {
  358. return neighbors;
  359. }
  360.  
  361. public void setNeighbors(LinkedList<GraphNodeNeighbor<E>> neighbors) {
  362. this.neighbors = neighbors;
  363. }
  364.  
  365.  
  366.  
  367. }
  368. class GraphNodeNeighbor<E> {
  369. GraphNode<E> node;
  370. float weight;
  371.  
  372. public GraphNodeNeighbor(GraphNode<E> node, float weight) {
  373. this.node = node;
  374. this.weight = weight;
  375. }
  376.  
  377. public GraphNodeNeighbor(GraphNode<E> node) {
  378. this.node = node;
  379. this.weight = 0;
  380. }
  381.  
  382. @Override
  383. public boolean equals(Object obj) {
  384. @SuppressWarnings("unchecked")
  385. GraphNodeNeighbor<E> pom = (GraphNodeNeighbor<E>)obj;
  386. return pom.node.equals(this.node);
  387. }
  388.  
  389.  
  390.  
  391.  
  392.  
  393. }
  394.  
  395.  
  396. class Edge{
  397. private int fromVertex, toVertex;
  398. private float weight;
  399. public Edge(int from, int to, float weight){
  400. this.fromVertex = from;
  401. this.toVertex = to;
  402. this.weight = weight;
  403. }
  404.  
  405. public int getFrom(){
  406. return this.fromVertex;
  407. }
  408. public int getTo(){
  409. return this.toVertex;
  410. }
  411. public float getWeight(){
  412. return this.weight;
  413. }
  414.  
  415. @Override
  416. public String toString() {
  417. return "("+fromVertex+","+toVertex+")="+weight+" ";
  418. }
  419.  
  420.  
  421. }
  422.  
  423. public class Paytolls {
  424.  
  425. public static void main(String[] args) {
  426. // TODO Auto-generated method stub
  427.  
  428.  
  429. Scanner sc = new Scanner(System.in);
  430. int N = Integer.parseInt(sc.nextLine());
  431. String[] pom = sc.nextLine().split(" ");
  432. int start = Integer.parseInt(pom[0])-1;
  433. int end = Integer.parseInt(pom[1])-1;
  434.  
  435. int M = Integer.parseInt(sc.nextLine());
  436.  
  437. Graph<Integer> g = new Graph<>(N);
  438. for (int i = 0; i < M; i++) {
  439.  
  440. String[] pom1 = sc.nextLine().split(" ");
  441. int x= Integer.parseInt(pom1[0])-1;
  442. int y= Integer.parseInt(pom1[1])-1;
  443. float tezina= Float.parseFloat(pom1[2]);
  444.  
  445. g.adjList[x].setInfo(x);
  446. g.adjList[y].setInfo(y);
  447.  
  448. g.addEdge(x, y, tezina);
  449. }
  450.  
  451. float[] res = g.dijkstra(start);
  452. System.out.println((int)res[end]);
  453.  
  454. }
  455.  
  456. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement