【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
- 【PAT】1067. Sort with Swap(0,*)
- pat 1067. Sort with Swap(0,*) (25)
- PAT 1067. Sort with Swap(0,*) (25)
- 【PAT】1067. Sort with Swap(0,*) (25)
- PAT|1067. Sort with Swap(0,*)
- pat-1067. Sort with Swap(0,*) (25)
- PAT 1067. Sort with Swap(0,*)
- 【PAT】1067. Sort with Swap(0,*)
- 浙大PAT 1067题 1067. Sort with Swap(0,*)
- PAT A 1067. Sort with Swap(0,*) (25)
- 【PAT甲级】1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25) PAT甲级
- PAT甲级.1067. Sort with Swap(0,*) (25)
- PAT甲级练习1067. Sort with Swap(0,*) (25)
- PAT甲级1067. Sort with Swap(0,*) (25)
- PAT-A 1067. Sort with Swap(0,*) (25)
- PAT-A-1067. Sort with Swap(0,*) (25)
- 【PAT】【Advanced Level】1067. Sort with Swap(0,*) (25)
- 如何写好自己的简历
- 创建数据库系统
- 1.自定义控件--自定义属性attr
- PAT甲级1052
- Leaflet入门:利用leaflet展示各个国家的某些数据
- 【PAT】1067. Sort with Swap(0,*)
- P1028数的计算
- Java基础知识点总结
- P1307 数字反转
- Codeforces #211 (Div. 2) A. Soroban
- opencv的ROI操作
- call和apply用法
- POJ 1365 Prime Land 【素数分解】
- Plus One