-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC2872.java
More file actions
92 lines (75 loc) · 2.64 KB
/
LC2872.java
File metadata and controls
92 lines (75 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
* LC2872
*/
import java.util.*;
public class LC2872 {
public static int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) {
// create the adjacency list from edges
List<Integer>[] adjList = new ArrayList[n];
for (int i = 0; i < n; i++) {
adjList[i] = new ArrayList<>();
}
// Iterate the edges
for (int[] edge : edges) {
int node1 = edge[0];
int node2 = edge[1];
adjList[node1].add(node2);
adjList[node2].add(node1);
}
int[] componentCount = new int[1];
dfs(0, -1, adjList, values, k, componentCount);
return componentCount[0];
}
// Depth First Search (DFS Time Complexity O(n))
public static long dfs(int currentNode, int parentNode, List<Integer>[] adjList, int[] nodeValues, int k,
int[] componentCount) {
long sum = nodeValues[currentNode];
for (int neighborNode : adjList[currentNode]) {
if (neighborNode != parentNode) {
// check the sum
sum += dfs(neighborNode, currentNode, adjList, nodeValues, k, componentCount);
}
}
if (sum % k == 0) {
componentCount[0]++;
sum = 0;
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The N : ");
int n = sc.nextInt();
System.out.println();
System.out.print("Enter The Row : ");
int row = sc.nextInt();
System.out.print("Enter The Column : ");
int col = sc.nextInt();
System.out.println();
int[][] edges = new int[row][col];
System.out.println("Enter The Edges Array Elements : ");
for (int i = 0; i < edges.length; i++) {
for (int j = 0; j < edges.length; j++) {
System.out.printf("[%d][%d] : ", i, j);
edges[i][j] = sc.nextInt();
}
}
System.out.println();
System.out.print("Enter The Values Array Size : ");
int size = sc.nextInt();
System.out.println();
int[] values = new int[size];
System.out.println("Enter The Values Array Elements : ");
for (int i = 0; i < values.length; i++) {
System.out.printf("[%d] : ", i);
values[i] = sc.nextInt();
}
System.out.println();
System.out.print("Enter The k : ");
int k = sc.nextInt();
System.out.println();
int ans = maxKDivisibleComponents(n, edges, values, k);
System.out.println(ans);
sc.close();
}
}