Advertisement
Guest User

Untitled

a guest
Nov 16th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. import java.util.*;
  2. class Graph {
  3.     private int numVertices;
  4.     private LinkedList<Edge> adjLists[];
  5.  
  6.     Graph(int numVertices) {
  7.         this.numVertices = numVertices;
  8.         adjLists = new LinkedList[numVertices];
  9.  
  10.         for (int i = 0; i < numVertices; i++)
  11.             adjLists[i] = new LinkedList();
  12.     }
  13.  
  14.     private void addEdge(int src, Edge edge) {
  15.         adjLists[src].add(edge);
  16.     }
  17.  
  18.     private void printAdjLists() {
  19.         for (int i = 0; i < adjLists.length; i++) {
  20.             System.out.print(i + " ");
  21.             adjLists[i].forEach(m -> System.out.print(m + " "));
  22.             System.out.println(" ");
  23.         }
  24.     }
  25.  
  26.     private int CPM() {
  27.         int destination = 0;
  28.         int temp = 0;
  29.         int cpm = 0;
  30.         for (int i = 0; i < adjLists.length; i++) {
  31.             if (adjLists[i].size() > 0) {
  32.                 if (adjLists[i].size() > 1) {
  33.                     cpm += adjLists[i].getLast().getTime();
  34.                     if (adjLists[adjLists[i].getLast().getDestination()].size() == 1) {
  35.                         temp = adjLists[i].getLast().getDestination() - 1;
  36.                         adjLists[i].removeLast();
  37.                         i = temp;
  38.                     }
  39.                 } else {
  40.                     cpm += adjLists[i].getFirst().getTime();
  41.                 }
  42.                 System.out.println(i + "    -------      ");
  43.             }
  44.         }
  45.         return cpm;
  46.     }
  47.  
  48.     public static void main(String args[]) {
  49.         Graph g = new Graph(6);
  50.         g.addEdge(1, new Edge(2,3));
  51.         g.addEdge(2, new Edge(3,1));
  52.         g.addEdge(2, new Edge(3,2));
  53.         g.addEdge(3, new Edge(5, 7));
  54.         g.addEdge(3, new Edge(4,4));
  55.         g.addEdge(4, new Edge(0, 0));
  56.         g.printAdjLists();
  57.  
  58.         int cpm = g.CPM();
  59.         System.out.println("cpm = " + cpm);
  60.  
  61.         g.printAdjLists();
  62.  
  63.         cpm = g.CPM();
  64.         System.out.println("cpm = " + cpm);
  65.  
  66.         g.printAdjLists();
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement