思路没问题,但细节上还欠缺,运行时两个测试点运行超时,定位在两个for循环上,却不知怎么优化.
#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=100010;
int m[maxn];
int a[maxn],n;
bool judgeSort(){
for(int i=1;i<n;i++){
if(a[i]!=i)return false;
}
return true;
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
int total=0;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
m[a[i]]=i;
}
while(1){
if(m[0]==0){ //若此时0所在数组下标恰好为0,则要判断数组是否已经有序
if(judgeSort()){ //若已有序,则退出循环
break;
}else{
for(int i=1;i<n;i++){ //找到第一个没在自己该在的序号上的数,与0交换
if(a[i]!=i){
m[a[i]]=0; //更新该数所在的数组下标
m[0]=i; //更新0所在的数组下标
a[0]=a[i];
a[i]=0;
break;
}
}
}
}else{
int temp=m[0];
m[0]=m[temp];
a[m[temp]]=0; //这步省不得,因为最后要通过排序判断是否可退出循环
m[temp]=temp;
a[temp]=temp;
}
total++;
}
printf("%d",total);
return 0;
}
看了算法笔记才茅塞顿开,我的写法每次都要从1开始遍历寻找第一个不在本位上的数,更傻的是我还写了两遍,judgeSort中写过还在之后的for循环中又写了一遍,明明可以直接将judgeSort中获取到的保存下来使用.况且寻找也不用每次从头开始寻找,因为之前找到的数k都已经与0交换过了,可以将k及之前的数过掉,直接从k开始向后遍历,这样等到全部结束,k一共只遍历了n遍,而我之前的写法每次最多遍历n遍,遇到极端情况就会导致超时.
#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=100010;
int m[maxn];
int a[maxn],n,t=1; //在遍历没在自己本位上的数时,更新好遍历的起始位置,减少遍历次数
bool judgeSort(){
for(int i=t;i<n;i++){
if(a[i]!=i){ //找到第一个没在自己本位上的数
t=i;
return false;
}
}
return true;
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
int total=0;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
m[a[i]]=i;
}
while(1){
if(m[0]==0){ //若此时0所在数组下标恰好为0,则要判断数组是否已经有序
if(judgeSort()){ //若已有序,则退出循环
break;
}
m[a[t]]=0; //更新该数所在的数组下标
m[0]=t; //更新0所在的数组下标
a[0]=a[t];
a[t]=0;
}else{
int temp=m[0];
m[0]=m[temp];
a[m[temp]]=0; //这步省不得,因为最后要通过排序判断是否可退出循环
m[temp]=temp;
a[temp]=temp;
}
total++;
}
printf("%d",total);
return 0;
}
算法笔记中的思路值得借鉴!(详见p161)
每读入一个数,将其作为数组下标,将其出现位置作为数组中存放的数.
#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=100010;
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
int a[maxn],n,left,k=1,total=0;
scanf("%d",&n);
left=n-1;
for(int i=0;i<n;i++){
int temp;
scanf("%d",&temp);
a[temp]=i;
if(temp==i&&temp!=0)left--; //此处漏写了temp!=0,若0在本位,不应该left--,因为之后0还会不断变动
}
while(left>0){
if(a[0]==0){
while(k<n){
if(a[k]!=k){
swap(a[0],a[k]);
break;
}
k++;
}
}else{
swap(a[0],a[a[0]]);
left--;
}
total++;
}
printf("%d",total);
return 0;
}