Ignatius and the Princess II (字典序排序)

把大象关进冰箱有几步它就有几步(滑稽.jpg)
字典序排序第一步:从右往左找出第一对正序(即左边数字小于右边数字),并记录左边数字下标为i;
第二步:再重新从右往左找出第一个大于所记录数字的数字,并交换他俩的值
第三步:将从i开始(不包括i)以后的数字从大到小排列,这样就成功的找到了当前数字排列的下一个排列。(lalala)
从这串数字正序开始重复以上步骤直到不能交换位置,这样就找到了这串数字的全排列。(这就是字典序排序的作用)
附代码:

#include <iostream>
#include <algorithm>
using namespace std;
int A[1005];
int  main(){
    int a,b;
    while(cin>>a>>b){
        for(int i=0;i<a;i++){
            A[i]=i+1;
        }
        for(int i=0;i<b-1;i++){
            int c,d,e;
            for(int j=a-2;j>=0;j--){
                if(A[j]<A[j+1]){
                    c=j; d=A[j]; break;
                }
            }
            for(int j=a-1;j>=0;j--){
                if(A[j]>d){
                    int temp=A[c];
                    A[c]=A[j];
                    A[j]=temp;
                     break;
                }
            }
            sort(A+c+1,A+a);
        }
        for(int i=0;i<a;i++){
            if(i==a-1) {
                cout<<A[i]<<endl; break;
            }
            cout<<A[i]<<" ";
        }
    }
}

题目出处

发布了24 篇原创文章 · 获赞 2 · 访问量 464

猜你喜欢

转载自blog.csdn.net/chineseherofeng/article/details/104691482