排列组合函数next_permutation()

next_permution(),按照字典序进行排列组合,

括号里的参数为类似sort里面的参数,用法相同

#include <bits/stdc++.h>
using namespace std;
#define Maxn 10

int main(){
    int a[3];
    a[0]=1;a[1]=2;a[2]=3;
    do{
        cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
    }while (next_permutation(a,a+3)); //参数3指的是要进行排列的长度
}
//如果存在a之后的排列,就返回true。如果a是最后一个排列没有后继,返回false,每执行一次,a就变成它的后继

  

如果交换a[0],a[1],a[2]的大小,排列的次数会改变

#include <bits/stdc++.h>
using namespace std;
#define Maxn 10

int main(){
    int a[3];
    a[0]=3;a[1]=2;a[2]=1;
    do{
        cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
    }while (next_permutation(a,a+3)); //参数3指的是要进行排列的长度
}

  

 

例题(白书)p78,字母重排

输入一个字典(******结尾),然后输入若干单词w,你都需要在字典中找出所有可以用w的字母重排后得到的单词,并按照字典序从小到大的顺序在一行中输出(

不存在输出:(   )输入单词之间用空格或空行隔开,输入单词都不超过6个小写字母组成:

样例输入:

trap given score refund only trap work earn course pepper part
******

resco nfudre aptr sett oresuc

输出

score
refund
part trap trap
:(
course

 

#include <bits/stdc++.h>
using namespace std;
#define Maxn 10
char MAP[Maxn][Maxn];
char AIM[Maxn][Maxn];
int main(){
    string A;
    string B;
    string C;
    getline(cin,A);
    getline(cin,B);
    getchar();
    getline(cin,C);
    int j = 0;
    int k = 0;
    for( int i = 0; i < A.length(); i++ ){
        if(A[i] == ' '){
            MAP[k][j] = '\0';
            k++;
            j = 0;
        }else{
            MAP[k][j] = A[i];
            j++;
        }
    }
    MAP[k++][j] = '\0';
    set<string>s;
    for(int i = 0; i < k; i++){
        s.insert(MAP[i]);
    }
    int y = 0;
    int t = 0;
    for( int i = 0; i < C.length(); i++ ){
        if(C[i] == ' '){
            AIM[y][t++] = '\0';
            y++;
            t = 0;
        }else{
            AIM[y][t] = C[i];
            t++;
        }
    }
    AIM[y++][t] = '\0';
    int cnt = 0;
    for(int i = 0; i < y; i++){
        sort(AIM[i],AIM[i] + strlen(AIM[i]));
        bool flag = true;
        do{
            for(int j = 0; j < k; j++){
                if(strcmp(AIM[i],MAP[j]) == 0){
                    flag = false;
                    cout << AIM[i] << " ";
                }
            }
        }while( next_permutation(AIM[i],AIM[i] + strlen(AIM[i]) ) );//全排列
        if(flag){
            cout << ":(";
        }
        cout << endl;
    }
}

  

转载于:https://www.cnblogs.com/yakoazz/p/5848762.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值