题意:给出一种排序方式排列一串只有a到z组成的字符串,按升序排序,要求这个排序方式在字符长度为1000时排序的次数不会超过10000次!!输出的时候输出要交换的两个元素的序号,第A个元素的序号AI和第B个元素的序号BI。按照输出的序列能够还原到字符串排序前的状态。
思路:长度1000的字符串排序不超过10000次就得出结果,要求排序方法的效率要高。
起先对题目的理解有误,认为必须是两个相邻的才能交换,这是不对的,导致选择了冒泡排序,在字符串接近100时排序就超过10000次了。
调整思路之后不相邻的也能交换,选择了选择排序,AC!
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; struct node { int x,y; }a[10010]; int main() { char str[1010], ch; scanf("%s",str); int len=strlen(str); int cnt=0; int x; for(int i=0;i<len-1;i++) { x=i; for(int j=i+1;j<len;j++) { if(str[j]<str[x]) x=j; } if(x!=i) { a[cnt].x=x+1;a[cnt++].y=i+1; ch=str[x]; str[x]=str[i]; str[i]=ch; } } ///printf("%s\n",str); ///cout<<"cnt="<<cnt<<endl; for(int i=cnt-1;i>=0;i--) printf("%d %d\n",a[i].x,a[i].y); return 0; }