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
| public class boj_10451 { static boolean[] isChecked; static List<List<Integer>> graphList; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t-- > 0){
int n = Integer.parseInt(br.readLine()); isChecked = new boolean[n+1]; String[] input = br.readLine().split(" "); graphList = new ArrayList<>(); for(int i=0; i<=n; i++){ graphList.add(new ArrayList<>()); } for(int i=0; i<input.length; i++){ int x = i+1; int y = Integer.parseInt(input[i]); graphList.get(x).add(y); graphList.get(y).add(x); } int cnt = 0; for(int i=1; i<=n; i++){ if(!isChecked[i]) { findParent(i); cnt++; } } System.out.println(cnt); Arrays.fill(isChecked,false); } }
private static void findParent(int x) { isChecked[x] = true; for(int i=0; i<graphList.get(x).size(); i++){ int y = graphList.get(x).get(i); if(!isChecked[y]){ findParent(y); } } } }
|