有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; }