和PAT書上的思路不一樣。我使用了map,費內存是真的。但是換來了運行時間。
使用map的思路是這樣的。
原來用數組,下標裏面存值。
用map則是key是值,value是原來數組的下標,即map<值,下標>
這樣就O(1)訪問了。
#include<map>
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n;
scanf("%d", &n);
map<int, int> imap;
int num = -1;
for(int i=0; i<n; ++i){
int temp;
scanf("%d", &temp);
if(temp!=i) num++;
imap[temp]=i;
}
int index = 0;
int cnt = 0;
int k=1;
while(num>0){
while(imap[0]!=0){
swap(imap[0],imap[imap[0]]);
cnt++;
num--;
}
for(int i=k;i<n;++i){
if(imap[i]!=i){
swap(imap[0], imap[i]);
cnt++;
k=i+1;
break;
}
}
}
printf("%d\n", cnt);
return 0;
}