求排列的stl函数

C++STL的next_permutationACM 2008-07-25 15:22:21 阅读1077 评论2 字号:大中小
    这是一个求一个排序的下一个排列的函数。如果要走遍所有的排列,你必须先排序。
这是这两个函数使用需要注意的地方。其函数原形为:

template<class BidIt>

bool next_permutation(BidIt first, BidIt last);

template<class BidIt, class Pred>

 bool next_permutation(BidIt first, BidIt last, Pred pr);

而其prev_permutation与之相反,是求一个排列的前一个排序。

下面几个题目是北大OJ上的,这里体现出了STL的优势。(但有时STL效率并不是太高的!)

http://acm.pku.edu.cn/JudgeOnline/problem?id=1731

[Code]

 

#include <iostream>

#include <cstring>

#include <algorithm>

using namespace std;

 

int main()

{

     char ch[205];

     cin >> ch;

     sort(ch, ch + strlen(ch) );

     char *first =  ch;

     char *last = ch + strlen(ch);

     do {

         cout << ch << endl;

     }while(next_permutation(first, last));

     return 0;

}

[/Code]

 

http://acm.pku.edu.cn/JudgeOnline/problem?id=1146

 (  ID Codes)

[Code ]

 

#include <iostream>

#include <algorithm>

#include <string>

#include <vector>

using namespace std;

 

int main()

{

    string str;

    while(cin >> str && str[0] != '#'){

        if( next_permutation(str.begin(), str.end())){

            cout << str << endl;

        }

        else{

            cout << "No Successor" << endl;

        }

    }

    return 0;

}

[/Code]

http://acm.pku.edu.cn/JudgeOnline/problem?id=1256

Anagram

[Code]

 

#include <iostream>

#include <algorithm>

#include <string>

#include <vector>

using namespace std;

 

int compare(char a, char b)

{

    if(tolower(a) == tolower(b))

       return a < b;

    else return tolower(a) < tolower(b);

}

 

int main()

{

    int len, n;

    cin >> n;

    char str[15];

    cin.ignore();

 

    while(n --) {

       cin.getline(str, 15);

       len = strlen(str);

       sort(str, str + len, compare);

       cout << str << endl;

       while(next_permutation(str, str + len, compare))

           cout << str << endl;

    }

    return 0;

}

[/Code]

 

http://acm.pku.edu.cn/JudgeOnline/problem?id=1833

排列

[Code]

 

#include <iostream>

#include <algorithm>

#include <string>

#include <vector>

using namespace std;

 

int main()

{

    int nCases, n, k, i;

    int num[1024];

    scanf("%d", &nCases);

 

    while(nCases --) {

       scanf("%d%d", &n, &k);

       for(i = 0; i < n; i++)

           scanf("%d", &num[i]);

       for(i = 0; i < k; i++)

           next_permutation(num, num + n);

       for(i = 0;i < n; i++)

           printf("%d ", num[i]);

       printf("/n");

    }

 

    return 0;

}

[/Code]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值