Advertisement
NHristovski

Untitled

Mar 19th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.61 KB | None | 0 0
  1. /*
  2. */
  3. package mygraph;
  4.  
  5. import java.util.ArrayList;
  6. import java.util.Collections;
  7. import java.util.HashMap;
  8. import java.util.HashSet;
  9. import java.util.Hashtable;
  10. import java.util.LinkedList;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.Objects;
  14. import java.util.PriorityQueue;
  15. import java.util.Queue;
  16. import java.util.Scanner;
  17. import java.util.Set;
  18.  
  19.  
  20. class Vertex<E extends Comparable<E>> implements Comparable<Vertex<E>>{
  21. private E data;
  22. private double minDistance;
  23. private Vertex predecessor;
  24.  
  25. public Vertex(E data){
  26. this.data = data;
  27. this.minDistance = Double.MAX_VALUE;
  28. this.predecessor = null;
  29. }
  30.  
  31. public boolean hasPredecessor(){
  32. return this.predecessor != null;
  33. }
  34.  
  35. public double getMinDistance() {
  36. return minDistance;
  37. }
  38.  
  39. public void setMinDistance(double minDistance) {
  40. this.minDistance = minDistance;
  41. }
  42.  
  43. public Vertex<E> getPredecessor() {
  44. return predecessor;
  45. }
  46.  
  47. public void setPredecessor(Vertex predecessor) {
  48. this.predecessor = predecessor;
  49. }
  50.  
  51. public E getData() {
  52. return data;
  53. }
  54.  
  55. public void setData(E data) {
  56. this.data = data;
  57. }
  58.  
  59. @Override
  60. public int compareTo(Vertex<E> v) {
  61. return Double.compare(minDistance, v.getMinDistance());
  62. }
  63.  
  64. @Override
  65. public int hashCode() {
  66. int hash = 3;
  67. hash = 29 * hash + Objects.hashCode(this.data);
  68. return hash;
  69. }
  70.  
  71. @Override
  72. public boolean equals(Object obj) {
  73. if (this == obj) {
  74. return true;
  75. }
  76. if (obj == null) {
  77. return false;
  78. }
  79. if (getClass() != obj.getClass()) {
  80. return false;
  81. }
  82. final Vertex<E> other = (Vertex<E>) obj;
  83. if (!this.data.equals(other.data)) {
  84. return false;
  85. }
  86. return true;
  87. }
  88.  
  89. @Override
  90. public String toString(){
  91. StringBuilder sb = new StringBuilder();
  92. sb.append("Vertex with data: ")
  93. .append(this.data)
  94. .append(" minDist: ")
  95. .append(this.minDistance)
  96. .append(" Pred: ");
  97. if (this.hasPredecessor())
  98. sb.append(this.predecessor.getData());
  99. else{
  100. sb.append("None");
  101. }
  102. return sb.toString();
  103. }
  104.  
  105. }
  106.  
  107. class Edge<E extends Comparable<E>>{
  108. private Vertex<E> source;
  109. private Vertex<E> destination;
  110. private double weight;
  111.  
  112. public Edge(Vertex<E> source, Vertex<E> destination, double weight) {
  113. this.source = source;
  114. this.destination = destination;
  115. this.weight = weight;
  116. }
  117.  
  118. public Vertex<E> getSource() {
  119. return source;
  120. }
  121.  
  122. public void setSource(Vertex<E> source) {
  123. this.source = source;
  124. }
  125.  
  126. public Vertex<E> getDestination() {
  127. return destination;
  128. }
  129.  
  130. public void setDestination(Vertex<E> destination) {
  131. this.destination = destination;
  132. }
  133.  
  134. public double getWeight() {
  135. return weight;
  136. }
  137.  
  138. public void setWeight(double weight) {
  139. this.weight = weight;
  140. }
  141.  
  142. @Override
  143. public String toString(){
  144. StringBuilder sb = new StringBuilder();
  145. sb.append("Edge from: ")
  146. .append(this.source.toString())
  147. .append("\nTo: ")
  148. .append(this.destination.toString())
  149. .append("\nWith weight: " + this.weight);
  150. return sb.toString();
  151. }
  152.  
  153.  
  154.  
  155. }
  156. class Graph<E extends Comparable<E>>{
  157.  
  158. List<Vertex<E>> vertices;
  159. List<Edge<E>> edges;
  160. Map<E,Integer> indexes; // E( name of the vertex) -> Integer (position in list vertices)
  161.  
  162. public Graph(){
  163. vertices = new ArrayList<>();
  164. edges = new ArrayList<>();
  165. indexes = new HashMap<>();
  166. }
  167.  
  168. public void addVertex(E data){
  169. Vertex<E> vertex = new Vertex<>(data);
  170. vertices.add(vertex);
  171. int index = vertices.size() - 1;
  172. indexes.put(data, index);
  173. }
  174.  
  175. public Vertex<E> getVertex(E data){
  176. return vertices.get(indexes.get(data));
  177. }
  178.  
  179. private boolean addEdge(Vertex<E> source,Vertex<E> destination,double weight){
  180. return edges.add(new Edge<E>(source,destination,weight));
  181. }
  182.  
  183. public boolean addDirectedEdge(E source,E destination,double weight){
  184. Vertex<E> s = vertices.get(indexes.get(source));
  185. Vertex<E> d = vertices.get(indexes.get(destination));
  186. return addEdge(s,d,weight);
  187. }
  188. public boolean addUndirectedEdge(E source,E destination,double weight){
  189. Vertex<E> s = vertices.get(indexes.get(source));
  190. Vertex<E> d = vertices.get(indexes.get(destination));
  191.  
  192. return addEdge(s,d,weight) && addEdge(d,s,weight);
  193. }
  194.  
  195. public List<Vertex<E>> getVertices(){
  196. return this.vertices;
  197. }
  198.  
  199. public List<Edge<E>> getEdges(){
  200. return this.edges;
  201. }
  202.  
  203. @Override
  204. public String toString(){
  205. StringBuilder sb = new StringBuilder();
  206. for (Vertex<E> v : this.getVertices()){
  207. sb.append(v.toString() + "\n");
  208. }
  209. return sb.toString();
  210. }
  211.  
  212. public double getMinDistanceBetweenDijkstra(E start,E end){
  213. Vertex<E> source = vertices.get(indexes.get(start));
  214. Vertex<E> destination = vertices.get(indexes.get(end));
  215. Dijkstra<E> dijkstra = new Dijkstra<>();
  216.  
  217. dijkstra.run(this, source);
  218.  
  219. return destination.getMinDistance();
  220. }
  221.  
  222. public List<List<Double>> getMinDistanceBetweenEveryDijkstra(){
  223.  
  224. double minWeight = Double.MAX_VALUE;
  225. for (Edge<E> edge : this.getEdges()){
  226. if (edge.getWeight() < minWeight){
  227. minWeight = edge.getWeight();
  228. }
  229. }
  230. minWeight = Math.abs(minWeight);
  231.  
  232. for (Edge<E> edge : this.getEdges()){
  233. edge.setWeight(edge.getWeight() + minWeight);
  234. }
  235.  
  236. List<List<Double>> matrix = new ArrayList<>();
  237. List<Double> resultRow;
  238.  
  239. Dijkstra<E> dijkstra = new Dijkstra<>();
  240.  
  241. for (Vertex<E> source : this.getVertices()){
  242.  
  243. dijkstra.run(this,source);
  244.  
  245. resultRow = new ArrayList<>();
  246.  
  247. for (Vertex<E> vertex : this.getVertices()){
  248. int counter = 0;
  249. while(vertex.hasPredecessor()){
  250. counter++;
  251. vertex = vertex.getPredecessor();
  252. }
  253. System.out.println(counter);
  254.  
  255. double result = vertex.getMinDistance() - (counter * minWeight);
  256. resultRow.add(result);
  257. }
  258. matrix.add(resultRow);
  259. }
  260.  
  261.  
  262. return matrix;
  263. }
  264.  
  265. public double getMinDistanceBetweenBellmanFord(E start,E end){
  266. Vertex<E> source = vertices.get(indexes.get(start));
  267. Vertex<E> destination = vertices.get(indexes.get(end));
  268.  
  269. BellmanFord<E> bellmanFord = new BellmanFord<>();
  270.  
  271. if (bellmanFord.run(this, source))
  272. return destination.getMinDistance();
  273.  
  274. else{
  275. return -1;
  276. }
  277. }
  278.  
  279. /*
  280. MatrixPair class
  281. */
  282. ////////////////////////////////////////////////////////////////////////////
  283. class Matrix{
  284. double[][] adjMatrix;
  285. Integer[][] parrentMatrix;
  286.  
  287. public Matrix(double[][] adjMatrix, Integer[][] parrentMatrix) {
  288. this.adjMatrix = adjMatrix;
  289. this.parrentMatrix = parrentMatrix;
  290. }
  291.  
  292. public double[][] getAdjMatrix() {
  293. return adjMatrix;
  294. }
  295.  
  296. public Integer[][] getParrentMatrix() {
  297. return parrentMatrix;
  298. }
  299.  
  300. public List<Integer> getPathBetween(int source,int destination){
  301. int start = source - 1;
  302. int finish = destination - 1;
  303. List<Integer> path = new ArrayList<>();
  304. while(parrentMatrix[start][finish] != start){
  305. path.add(parrentMatrix[start][finish] + 1);
  306. finish = parrentMatrix[start][finish];
  307. }
  308. path.add(parrentMatrix[start][finish] + 1);
  309. Collections.reverse(path);
  310. return path;
  311. }
  312.  
  313. public double getDistanceBetween(int source,int destination){
  314. int start = source - 1;
  315. int finish = destination - 1;
  316. return this.adjMatrix[start][finish];
  317. }
  318. }
  319. ////////////////////////////////////////////////////////////////////////////
  320.  
  321. public Matrix getMinDistanceFloydWarshall(double[][] adjMat){
  322. int N = adjMat.length;
  323.  
  324. Integer[][] parentMatrix = new Integer[N][N];
  325.  
  326. for (int i = 0; i < N; i++){
  327. for (int j = 0; j < N; j++){
  328. parentMatrix[i][j] = null;
  329. }
  330. }
  331.  
  332. for (int i = 0; i < N; i++){
  333. for (int j = 0; j < N; j++){
  334. if (adjMat[i][j] != Double.MAX_VALUE / 2 && adjMat[i][j] != 0.0){
  335. parentMatrix[i][j] = i;
  336. }
  337. }
  338. }
  339.  
  340.  
  341. for(int k = 0; k < N; ++k) {
  342. for(int i = 0; i < N; ++i) {
  343. for(int j = 0; j < N; ++j) {
  344. if ( adjMat[i][k] + adjMat[k][j] < adjMat[i][j] ){
  345. parentMatrix[i][j] = parentMatrix[k][j];
  346. }
  347. adjMat[i][j] = Math.min(adjMat[i][j], adjMat[i][k] + adjMat[k][j]);
  348. }
  349. }
  350. }
  351.  
  352. return new Matrix(adjMat,parentMatrix);
  353. }
  354.  
  355.  
  356. public double[][] getAdjMatrix(){
  357. int N = vertices.size();
  358. double[][] matrix = new double[N][N];
  359. for (int i = 0; i < N; i++){
  360. for (int j = 0; j < N; j++){
  361. if (i == j)
  362. continue;
  363. else{
  364. matrix[i][j] = Double.MAX_VALUE / 2.0;
  365. }
  366. }
  367. }
  368. List<Edge<E>> egdes = this.getEdges();
  369. for (Edge<E> e : edges){
  370. matrix[indexes.get(e.getSource().getData())][indexes.get(e.getDestination().getData())] = e.getWeight();
  371. }
  372. return matrix;
  373. }
  374. }
  375.  
  376. class Dijkstra<E extends Comparable<E>>{
  377.  
  378. public Dijkstra(){
  379. }
  380.  
  381. private Hashtable<Vertex<E>, List<Edge<E> > > makeHashtable(Graph<E> graph){
  382. Hashtable<Vertex<E>, List<Edge<E> > > table = new Hashtable<>();
  383. List<Edge<E>> lst;
  384. for (Vertex<E> v : graph.getVertices()){
  385. lst = new LinkedList<>();
  386. table.put(v,lst);
  387. }
  388.  
  389. for (Edge<E> e : graph.getEdges()){
  390. table.get(e.getSource()).add(e);
  391. }
  392.  
  393. return table;
  394. }
  395. public void run(Graph<E> graph, Vertex<E> startVertex){
  396.  
  397. if (graph == null || startVertex == null)
  398. return;
  399.  
  400. for (Vertex<E> v : graph.getVertices()){
  401. v.setMinDistance(Double.MIN_VALUE);
  402. v.setPredecessor(null);
  403. }
  404.  
  405. startVertex.setMinDistance(Double.MAX_VALUE);
  406. PriorityQueue<Vertex<E>> queue = new PriorityQueue<>(graph.getVertices());
  407. Hashtable<Vertex<E>, List<Edge<E>>> table = makeHashtable(graph);
  408.  
  409. while (!queue.isEmpty()){
  410. Vertex<E> u = queue.poll();
  411.  
  412. for (Edge<E> e : table.get(u)){
  413. Vertex<E> v = e.getDestination();
  414. if (v.getMinDistance() < Math.min(u.getMinDistance(),e.getWeight())){
  415. v.setMinDistance(Math.min(u.getMinDistance(),e.getWeight()));
  416. v.setPredecessor(u);
  417. queue.add(v);
  418. }
  419. }
  420. }
  421.  
  422. }
  423.  
  424. }
  425.  
  426. class BellmanFord<E extends Comparable<E>>{
  427.  
  428. private void relax(Edge<E> edge){
  429. if (edge.getDestination().getMinDistance() < Math.min(edge.getSource().getMinDistance(),edge.getWeight())){
  430. edge.getDestination().setMinDistance(Math.min(edge.getSource().getMinDistance(),edge.getWeight()));
  431. edge.getDestination().setPredecessor(edge.getSource());
  432. }
  433. }
  434. public boolean run(Graph<E> graph, Vertex<E> startVertex){
  435. if (graph == null || startVertex == null)
  436. return false;
  437.  
  438. for (Vertex<E> v : graph.getVertices()){
  439. v.setMinDistance(Double.MIN_VALUE);
  440. v.setPredecessor(null);
  441. }
  442.  
  443. startVertex.setMinDistance(Double.MAX_VALUE);
  444.  
  445. for (int i = 0; i < graph.getVertices().size(); i++){
  446. for (Edge<E> edge : graph.getEdges()){
  447. relax(edge);
  448. }
  449. }
  450.  
  451. for (Edge<E> edge : graph.getEdges()){
  452. if (edge.getDestination().getMinDistance() < Math.min(edge.getSource().getMinDistance(),edge.getWeight())){
  453. return false;
  454. }
  455. }
  456.  
  457. return true;
  458. }
  459. }
  460.  
  461. public class Main{
  462.  
  463. public static void main(String[] args){
  464. /*Graph<Integer> g = new Graph<>();
  465. double[][] d = new double[5][5];
  466.  
  467. d[0][0] = 0;
  468. d[0][1] = 3;
  469. d[0][2] = 8;
  470. d[0][3] = Double.MAX_VALUE / 2;
  471. d[0][4] = -4;
  472.  
  473. d[1][0] = Double.MAX_VALUE / 2;;
  474. d[1][1] = 0;
  475. d[1][2] = Double.MAX_VALUE / 2;;
  476. d[1][3] = 1;
  477. d[1][4] = 7;
  478.  
  479. d[2][0] = Double.MAX_VALUE / 2;;
  480. d[2][1] = 4;
  481. d[2][2] = 0;
  482. d[2][3] = Double.MAX_VALUE / 2;;
  483. d[2][4] = Double.MAX_VALUE / 2;;
  484.  
  485. d[3][0] = 2;
  486. d[3][1] = Double.MAX_VALUE / 2;;
  487. d[3][2] = -5;
  488. d[3][3] = 0;
  489. d[3][4] = Double.MAX_VALUE / 2;;
  490.  
  491. d[4][0] = Double.MAX_VALUE / 2;;
  492. d[4][1] = Double.MAX_VALUE / 2;;
  493. d[4][2] = Double.MAX_VALUE / 2;;
  494. d[4][3] = 6;
  495. d[4][4] = 0;
  496.  
  497.  
  498. System.out.println(g.getMinDistanceFloydWarshall(d).getPathBetween(1, 2));
  499. System.out.println(g.getMinDistanceFloydWarshall(d).getDistanceBetween(1, 2));
  500.  
  501.  
  502. for (int i = 1; i <= 5; i++){
  503. g.addVertex(i);
  504. }
  505.  
  506. g.addDirectedEdge(1, 2, 3);
  507. g.addDirectedEdge(1, 5, -4);
  508. g.addDirectedEdge(1, 3, 8);
  509.  
  510. g.addDirectedEdge(2, 4, 1);
  511. g.addDirectedEdge(2, 5, 7);
  512.  
  513. g.addDirectedEdge(3, 2, 4);
  514.  
  515. g.addDirectedEdge(4, 1, 2);
  516. g.addDirectedEdge(4, 3, -5);
  517.  
  518. g.addDirectedEdge(5, 4, 6);
  519.  
  520. System.out.println(g.getMinDistanceFloydWarshall(g.getAdjMatrix()).getPathBetween(1, 2));
  521. System.out.println(g.getMinDistanceFloydWarshall(g.getAdjMatrix()).getDistanceBetween(1, 2));
  522. */
  523. Graph<Integer> graph = new Graph<>();
  524.  
  525. graph.addVertex(1);
  526. graph.addVertex(2);
  527. graph.addVertex(3);
  528.  
  529. graph.addDirectedEdge(1, 1, 2);
  530. graph.addDirectedEdge(1, 2, 1);
  531. graph.addDirectedEdge(1, 3, -1);
  532. graph.addDirectedEdge(2, 1, 1);
  533. graph.addDirectedEdge(2, 2, 2);
  534. graph.addDirectedEdge(2, 3, 2);
  535. graph.addDirectedEdge(3, 1, 2);
  536. graph.addDirectedEdge(3, 2, 1);
  537. graph.addDirectedEdge(3, 3, 2);
  538.  
  539. for (List<Double> lst : graph.getMinDistanceBetweenEveryDijkstra()){
  540. System.out.println(lst);
  541. }
  542.  
  543. }
  544.  
  545. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement