Sort with Swap(0,*) (25)
来源:互联网 发布:大话手游罗刹鬼姬数据 编辑:程序博客网 时间:2024/05/17 00:52
IDEA
1.注意输入的数字从0-n-1,意思是让数字存在其对应下标下
2.题目只让0和某数交换,交换次数尽量少,则尽量让该数放在正确位置下,完后就不参与交换了
3.考虑两种情况:array[0]==0,0本身在正确位置,若还有不在正确位置的数字,则0与其交换;
array[0]!=0,让通过交换使得array[0]到正确位置,指导位置0有正确数,即0.位置;然后重复第一种情况
IDEA
#include<iostream>#include<fstream>using namespace std;int findpos(int* array,int begin,int end){for(int i=begin;i<end;i++){if(array[i]!=i){return i;}}return 0;}//void output(int *array,int n){//for(int i=0;i<n;i++){//cout<<array[i]<<" ";//}//}int main(){#ifndef ONLINE_JUDGEfreopen("input.txt","r",stdin);#endifint n;cin>>n;int *array=new int[n];for(int i=0;i<n;i++){cin>>array[i];}int index=1;index=findpos(array,index,n);int count=0;while(index){//index!=0,表示还有没有归为的数 if(array[0]==0){//swaparray[0]=array[index];array[index]=0;//output(array,n);//cout<<endl;count++;}while(array[0]!=0){//不在正确位置上,那要通过变换使得v[0] == 0int tmp=array[0];array[0]=array[tmp];array[tmp]=tmp;//output(array,n);//cout<<"-"<<endl;count++;}index=findpos(array,index,n);//0在自己位置上,找到第一个不在正确位置上的数 }cout<<count<<endl;#ifndef ONLINE_JUDGEfclose(stdin);#endifreturn 0;}
0 0
- Sort with Swap(0,*) (25)
- Sort with Swap(0,*)(25)
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- pat 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- PAT 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)
- 【PAT】1067. Sort with Swap(0,*) (25)
- PB调用WebService
- 人人网开源框架 paoding-rose 应用初探
- SVN 主干与分支的合并
- 详解Visual Studio调试中断点几个的小技巧
- 在业务类中忘记加上 @Component 导致的错误
- Sort with Swap(0,*) (25)
- memcached 入门
- MySQL 学习
- Surface Pro 3 停止在开机界面不动了
- IOC和DI
- Websocket协议的学习、调研和实现
- 从 JSON 字符串中解析 List 列表的方法
- 动手之前先想想
- 递归法求三角形数(1,3,6,10,15...)