Advertisement
Josif_tepe

Untitled

Jul 1st, 2023
1,202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.06 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. import java.util.Scanner;
  5.  
  6. class Graph {
  7.     int N;
  8.     List<List<Integer>> graph;
  9.  
  10.     public Graph(int N) {
  11.         this.N = N;
  12.         graph = new ArrayList<>(N);
  13.         for(int i = 0; i < N; i++) {
  14.             graph.add(new ArrayList<>());
  15.         }
  16.     }
  17.     public void addEdge(int a, int b) {
  18.         graph.get(a).add(b);
  19.         graph.get(b).add(a);
  20.     }
  21.  
  22.     public int countNumberOfCycles(int lengthOfCycle) {
  23.         int result = 0;
  24.         boolean[] visited = new boolean[N];
  25.         for(int i = 0; i < N; i++) {
  26.             result += dfs(i, i, 1, lengthOfCycle, visited);
  27.             visited[i] = true;
  28.         }
  29.     result /= 2;
  30.         return result;
  31.     }
  32.     private int dfs(int node, int startingNodeOfCycle, int currentLengthOfCycle, int cycleLength, boolean[] visited) {
  33.         if(currentLengthOfCycle == cycleLength) {
  34.             for(int i = 0; i < graph.get(node).size(); i++) {
  35.                 if(graph.get(node).get(i) == startingNodeOfCycle) {
  36.                     return 1;
  37.                 }
  38.             }
  39.             return 0;
  40.         }
  41.  
  42.         visited[node] = true;
  43.         int result = 0;
  44.         for(int i = 0; i < graph.get(node).size(); i++) {
  45.             int neighbour = graph.get(node).get(i);
  46.             if(!visited[neighbour]) {
  47.                 result += dfs(neighbour, startingNodeOfCycle, currentLengthOfCycle + 1, cycleLength, visited);
  48.             }
  49.         }
  50.         visited[node] = false;
  51.         return result;
  52.     }
  53. }
  54. public class Main {
  55.     public static void main(String[] args) {
  56.         Scanner sc = new Scanner(System.in);
  57.         int n = sc.nextInt();
  58.         int m = sc.nextInt();
  59.         Graph g = new Graph(n);
  60.         for(int i = 0; i < m; i++) {
  61.             int a = sc.nextInt();
  62.             int b = sc.nextInt();
  63.             g.addEdge(a, b);
  64.         }
  65.         int cycleLength = sc.nextInt();
  66.         System.out.println(g.countNumberOfCycles(cycleLength));
  67.     }
  68. }/*
  69. 5
  70. 6
  71. 0 1
  72. 0 2
  73. 1 2
  74. 2 3
  75. 2 4
  76. 3 4
  77. 3
  78. */
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement