【PAT】1067. Sort with Swap(0,*)

来源:互联网 发布:阿里云 安卓软件 编辑:程序博客网 时间:2024/05/17 08:09

关键:当0回归原位遍历数组查找不在本位的数时,应定义一个全局变量k,避免每次查找都是o(n)的数量级,这样之后所有查找只是线性时间完成

#define LOCAL#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn=100010;int a[maxn];int b[maxn];int main(){    #ifdef LOCAL        freopen("data.in","r",stdin);        freopen("data.out","w",stdout);    #endif // LOCAL    int n;    cin>>n;    int cur;    int left=n-1;    for(int i=0;i<n;i++){        scanf("%d",&a[i]);        if(a[i]==0) cur=i;        b[a[i]]=i;        if(a[i]!=0&&a[i]==i) left--;    }    int ans=0;    int k=1;   while(left){        if(cur){            swap(a[cur],a[b[cur]]);            ans++;            cur=b[cur];            left--;        }else{            while(k<n){                if(a[k]!=k){                    b[a[k]]=0;                    swap(a[0],a[k]);                    cur=k;                    ans++;                    break;                }                k++;            }        }    }  /*  while(left>0){        if(cur==0){            for(int i=1;i<n;i++){                if(a[i]!=i){                    b[a[i]]=0;                    swap(a[0],a[i]);                    cur=i;                    ans++;                    break;                }            }        }        while(cur){            swap(a[cur],a[b[cur]]);            ans++;            cur=b[cur];            left--;        }    }*/    cout<<ans;    return 0;}

#define LOCAL#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn=100010;int pos[maxn];int main(){    #ifdef LOCAL        freopen("data.in","r",stdin);        freopen("data.out","w",stdout);    #endif // LOCAL    int n,ans=0;    scanf("%d",&n);    int left=n-1,num;    for(int i=0;i<n;i++){        scanf("%d",&num);        pos[num]=i;        if(num==i&&num!=0)            left--;    }    int k=1;    while(left>0){        if(pos[0]==0){            while(k<n){                if(pos[k]!=k){                    ans++;                    swap(pos[k],pos[0]);                    break;                }                k++;            }        }else{            while(pos[0]!=0){                swap(pos[0],pos[pos[0]]);                ans++;                left--;            }        }    }    cout<<ans;    return 0;}


0 0