题目大意:给你N个数字(1–N),要求你将这N个数字排序,使得这N个数字生序。排序的操作:只能交换两个数字的位置
问至少需要几次操作
解题思路:按照贪心的想法,交换数字的时候,直接交换到所处的位置即可,这个方法是最优的
#include <cstdio>
#include <cstring>
const int N = 110;
int val[N], pos[N];
bool vis[N];
int n, cas = 1;
void init() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &val[i]);
pos[val[i]] = i;
}
}
void solve() {
int ans = 0;
for (int i = 1; i <= n; i++) {
if (val[i] == i) continue;
else {
ans++;
val[pos[i]] = val[i];
pos[val[i]] = pos[i];
}
}
printf("Case %d: %d\n", cas++ ,ans);
}
int main() {
int test;
scanf("%d", &test);
while (test--) {
init();
solve();
}
return 0;
}