Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Graph {
- private int numVertices;
- private LinkedList<Edge> adjLists[];
- Graph(int numVertices) {
- this.numVertices = numVertices;
- adjLists = new LinkedList[numVertices];
- for (int i = 0; i < numVertices; i++)
- adjLists[i] = new LinkedList();
- }
- private void addEdge(int src, Edge edge) {
- adjLists[src].add(edge);
- }
- private void printAdjLists() {
- for (int i = 0; i < adjLists.length; i++) {
- System.out.print(i + " ");
- adjLists[i].forEach(m -> System.out.print(m + " "));
- System.out.println(" ");
- }
- }
- private int CPM() {
- int destination = 0;
- int temp = 0;
- int cpm = 0;
- for (int i = 0; i < adjLists.length; i++) {
- if (adjLists[i].size() > 0) {
- if (adjLists[i].size() > 1) {
- cpm += adjLists[i].getLast().getTime();
- if (adjLists[adjLists[i].getLast().getDestination()].size() == 1) {
- temp = adjLists[i].getLast().getDestination() - 1;
- adjLists[i].removeLast();
- i = temp;
- }
- } else {
- cpm += adjLists[i].getFirst().getTime();
- }
- System.out.println(i + " ------- ");
- }
- }
- return cpm;
- }
- public static void main(String args[]) {
- Graph g = new Graph(6);
- g.addEdge(1, new Edge(2,3));
- g.addEdge(2, new Edge(3,1));
- g.addEdge(2, new Edge(3,2));
- g.addEdge(3, new Edge(5, 7));
- g.addEdge(3, new Edge(4,4));
- g.addEdge(4, new Edge(0, 0));
- g.printAdjLists();
- int cpm = g.CPM();
- System.out.println("cpm = " + cpm);
- g.printAdjLists();
- cpm = g.CPM();
- System.out.println("cpm = " + cpm);
- g.printAdjLists();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement