-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCam5.java
More file actions
65 lines (59 loc) · 1.66 KB
/
Cam5.java
File metadata and controls
65 lines (59 loc) · 1.66 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
/** https://www.spoj.com/problems/CAM5/ tag: #bfs #dfs */
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;
class Cam5 {
static void BFS(int vertex, ArrayList<ArrayList<Integer>> listFriends, boolean[] countedArr) {
Deque<Integer> queue = new LinkedList<>();
queue.addLast(vertex);
countedArr[vertex] = true;
while (!queue.isEmpty()) {
int p = queue.pollFirst();
for (int k : listFriends.get(p)) {
if (!countedArr[k]) {
countedArr[k] = true;
queue.addLast(k);
}
}
}
}
static int cal(ArrayList<ArrayList<Integer>> listFriends) {
boolean[] countedArr = new boolean[listFriends.size()];
int count = 0;
for (int i = 0; i < listFriends.size(); i++) {
if (!countedArr[i]) {
count++;
BFS(i, listFriends, countedArr);
}
}
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int[] resultArr = new int[t];
for (int i = 0; i < t; i++) {
int people = sc.nextInt();
int e = sc.nextInt();
if (e == 0) {
resultArr[i] = people;
continue;
}
ArrayList<ArrayList<Integer>> listFriends = new ArrayList<>(people);
for (int j = 0; j < people; j++) {
listFriends.add(new ArrayList<Integer>());
}
for (int j = 0; j < e; j++) {
int a = sc.nextInt();
int b = sc.nextInt();
listFriends.get(a).add(b);
listFriends.get(b).add(a);
}
resultArr[i] = cal(listFriends);
}
for (int r : resultArr) {
System.out.println(r);
}
}
}