CF 1855A - Dalton the Teacher
Dalton is the teacher of a class with n students, numbered from 1 to n. The classroom contains n chairs, also numbered from 1 to n. Initially student i is seated on chair pi. It is guaranteed that 1,p2,…,pn
?is a permutation of length n.
A student is happy if his/her number is different from the number of his/her chair. In order to make all of his students happy, Dalton can repeatedly perform the following operation: choose two distinct students and swap their chairs. What is the minimum number of moves required to make all the students happy? One can show that, under the constraints of this problem, it is possible to make all the students happy with a finite number of moves.
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a ermutation, but [1,2,2] is not a permutation (2 appears twice in the array), and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤1000). The description of the test cases follows.
The first line contains a single integer n (2≤n≤105) — the number of students.
The second line contains n integers p1,p2,…,pn (1≤pi≤n) — pi denotes the initial chair of student i. It is guaranteed that p is a permutation.
It is guaranteed that the sum of n over all test cases does not exceed 105.
Output
For each test case, output the minimum number of moves required.
--------------------------------------------
道爾頓是一個(gè)班的老師,班上有n名學(xué)生,編號(hào)從1到n。 教室里有n把椅子,編號(hào)也從1到n。 最初,學(xué)生 i 坐在椅子 pi 上。 保證 1,p2,…,pn
? 是長(zhǎng)度為n的排列。
如果學(xué)生的號(hào)碼與他/她的椅子的號(hào)碼不同,他/她會(huì)很高興。 為了讓所有的學(xué)生都高興,道爾頓可以重復(fù)執(zhí)行以下操作:選擇兩個(gè)不同的學(xué)生并交換他們的椅子。 最少需要多少步才能讓所有學(xué)生都滿意? 可以證明,在這個(gè)問題的約束下,有可能通過有限數(shù)量的動(dòng)作讓所有學(xué)生都滿意。
長(zhǎng)度為 n 的排列是由 n 個(gè)從 1 到 n 的不同整數(shù)以任意順序組成的數(shù)組。 例如,[2,3,1,5,4]是排列,但[1,2,2]不是排列(2在數(shù)組中出現(xiàn)兩次),并且[1,3,4]也不是排列 排列(n=3,但數(shù)組中有 4 個(gè))。
輸入
每個(gè)測(cè)試包含多個(gè)測(cè)試用例。 第一行包含測(cè)試用例的數(shù)量 t (1≤t≤1000)。 測(cè)試用例的描述如下。
第一行包含一個(gè)整數(shù) n (2≤n≤105) — 學(xué)生人數(shù)。
第二行包含 n 個(gè)整數(shù) p1,p2,…,pn (1≤pi≤n) — pi 表示學(xué)生 i 的初始主席。 保證p是一個(gè)排列。
保證所有測(cè)試用例的n之和不超過105。
輸出
對(duì)于每個(gè)測(cè)試用例,輸出所需的最小移動(dòng)次數(shù)。
----------------------------------------
當(dāng)位置跟序號(hào)一樣的時(shí)候,記錄下來,最后看一樣的有多少,如果一樣的是偶數(shù)個(gè),那么就除以2即可,如果是奇數(shù)個(gè),那么就除以2+1,當(dāng)然如果都不一樣,返回0即可,下面是代碼: