Advertisement
Guest User

Untitled

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