Untitled
unknown
plain_text
4 years ago
1.5 kB
6
Indexable
import java.io.*;
import java.util.*;
public class Solution {
public static void DFS(ArrayList[] graph,boolean[] vis,int s){
if(vis[s]=true) return;
vis[s]=true;
ArrayList<Integer> al=graph[s];
for(int ele:al){
DFS(graph,vis,ele);
}
}
public static void main(String[] args) throws IOException{
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
int tc=Integer.parseInt(br.readLine());
while(tc-->0){
String[] in=br.readLine().split(" ");
int n=Integer.parseInt(in[0]);
int m=Integer.parseInt(in[1]);
ArrayList[] a=new ArrayList[n+1];
boolean[] vis=new boolean[n+1];
for(int i=0;i<n+1;i++){
vis[i]=false;
}
while(m-->0){
String[] s=br.readLine().split(" ");
int x=Integer.parseInt(s[0]);
int y=Integer.parseInt(s[1]);
a[x].add(y);
}
int c=0;
for(int i=0;i<n+1;i++){
if(vis[i]==false){
DFS(a,vis,i);
c++;
}
}
bw.write(c+"\n");
}
bw.flush();
}
}Editor is loading...