fork download
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4.  
  5. public class Main {
  6. public static void main(String[] args) throws IOException{
  7. String[] NnMStr = br.readLine().split(" ");
  8. int N = Integer.parseInt(NnMStr[0]);
  9. int M = Integer.parseInt(NnMStr[1]);
  10.  
  11. int[][] arr =new int[N][N];
  12. int ans = 0;
  13.  
  14. if(M == 0) {
  15. System.out.println(N);
  16. return;
  17. }
  18. for(int i=0; i<N; i++){
  19. arr[i][i] =1;
  20. }
  21. for(int i=0; i<M; i++){
  22. String[] XnYStr = br.readLine().split(" ");
  23. int x = Integer.parseInt(XnYStr[0]);
  24. int y = Integer.parseInt(XnYStr[1]);
  25.  
  26. arr[x-1][y-1] = 1;
  27. }
  28.  
  29. for(int i=0; i<N; i++){
  30. for(int j=i; j<N; j++){
  31. if(arr[i][j]==1) {
  32. ans++;
  33. DFS(arr,i,N);
  34. }
  35. }
  36. }
  37. System.out.println(ans);
  38. }
  39. private static void DFS(int[][] arr,int start,int N){
  40. for(int i=0; i<N; i++){
  41. if(arr[start][i] == 1){
  42. arr[start][i]=0;
  43. DFS(arr,i,N);
  44. }
  45. }
  46. }
  47. }
  48.  
Success #stdin #stdout 0.09s 52952KB
stdin
4 2
2 1
3 4
stdout
3