Advertisement
SashkoKlincharov

[JAVA][АПС] - Брза помош

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