Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.ArrayList;
- /**
- *
- * @author henrico
- * problem 459
- */
- public class Main {
- private static ArrayList<Integer>[] graph;
- private static boolean[] visited;
- private static int count;
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- sc.nextLine();
- for(int i = 0;i<n;i++){
- int max = sc.next().charAt(0) - 'A' +1 ;
- graph = new ArrayList[max];
- visited = new boolean[max];
- for(int j = 0; j<max;j++){
- graph[j] = new ArrayList<Integer>();
- }
- sc.nextLine();
- String tmp = sc.nextLine();
- while(!tmp.equals("")){
- int x = tmp.charAt(0)-'A';
- int y = tmp.charAt(1)-'A';
- graph[x].add(y);
- graph[y].add(x);
- tmp = sc.nextLine();
- }
- count = 0;
- for(int j=0;j<max;j++){
- if(!visited[j]){
- count++;
- dfs(j);
- }
- }
- System.out.println(count);
- System.out.println();
- }
- }
- private static void dfs(int idx){
- visited[idx]=true;
- for(int i = 0; i<graph[idx].size();i++){
- if(!visited[graph[idx].get(i)]){
- dfs(graph[idx].get(i));
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement