有N個瓶子,編號1∼N,放在架子上。
好比有5個瓶子:ios
2 1 3 5 4
要求每次拿起2個瓶子,交換它們的位置。編程
通過若干次後,使得瓶子的序號爲:spa
1 2 3 4 5
對於這麼簡單的狀況,顯然,至少須要交換2次就能夠復位。code
若是瓶子更多呢?你能夠經過編程來解決。blog
第一行包含一個整數NN,表示瓶子數量。排序
第二行包含NN個整數,表示瓶子目前的排列情況。string
輸出一個正整數,表示至少交換多少次,才能完成排序。it
1≤N≤10000,io
5 3 1 2 5 4
3
5 5 4 3 2 1
2
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N = 10010; int n; int b[N]; bool st[N]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i ++) scanf("%d", &b[i]); int cnt = 0; for (int i = 1; i <= n; i ++) if (!st[i]) { cnt ++; for (int j = i; !st[j]; j = b[j]) st[j] = true; } printf("%d\n", n - cnt); return 0; }