import java util ArrayList import java util Arrays import java util Sc

 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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.lang.Math;
class point {
//int value;
int cap=0;
ArrayList<Integer> list = new ArrayList<Integer>();
}
public class CompSet {
public static void main(String[] arg) {
Scanner sc = new Scanner(System.in);
int i=0,j=0,flag,n=sc.nextInt(),m=sc.nextInt(),first,second,CompNumber=0;
int [] marks=new int[n];
point [] graph=new point[n];
for (i=0;i<n;i++) {
graph[i]=new point();
marks[i]=0;
}
for(i=0;i<m;i++){
first=sc.nextInt(); second=sc.nextInt();
graph[first].cap++;
graph[first].list.add(second);
graph[second].cap++;
graph[second].list.add(first);
}
for (i=0;i<n;i++){
if(marks[i]==0) {
CompNumber++;
marking(graph, i ,CompNumber,marks);
}
else continue;
}
System.out.println(CompNumber);
}
public static void marking (point [] graph,int ver,int CompNumber,int [] marks)
{
if(marks[ver]==0) {
int i = 0;
marks[ver] = CompNumber;
for (i = 0; i < graph[ver].cap; i++) {
marking(graph, graph[ver].list.get(i), CompNumber, marks);
}
}
}
}