POJ 1731(递归方式|next_permutation())

Orders

Time Limit: 1000MS Memory Limit: 10000K

Description

The stores manager has sorted all kinds of goods in an alphabetical order of their labels. All the kinds having labels starting with the same letter are stored in the same warehouse (i.e. in the same building) labelled with this letter. During the day the stores manager receives and books the orders of goods which are to be delivered from the store. Each order requires only one kind of goods. The stores manager processes the requests in the order of their booking.

You know in advance all the orders which will have to be processed by the stores manager today, but you do not know their booking order. Compute all possible ways of the visits of warehouses for the stores manager to settle all the demands piece after piece during the day.

Input

Input contains a single line with all labels of the requested goods (in random order). Each kind of goods is represented by the starting letter of its label. Only small letters of the English alphabet are used. The number of orders doesn’t exceed 200.

Output

Output will contain all possible orderings in which the stores manager may visit his warehouses. Every warehouse is represented by a single small letter of the English alphabet – the starting letter of the label of the goods. Each ordering of warehouses is written in the output file only once on a separate line and all the lines containing orderings have to be sorted in an alphabetical order (see the example). No output will exceed 2 megabytes.

Sample Input

bbjd

Sample Output

bbdj
bbjd
bdbj
bdjb
bjbd
bjdb
dbbj
dbjb
djbb
jbbd
jbdb
jdbb

问题分析

如果只是简单的stl的话,我就不写这篇博客了。。。
介绍一下递归方式,全排列的模板,但是为了避免重复,因此我们可以采用记录上次递归选用的字符,然后做个判断不要让这次选的和上次的重复即可。

// #include <bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
const int N = 201;
int n;
char s[N],tmp[N];
bool vis[N];
void dfs(int step)
{
    if(step==n){
        tmp[step] = '\0';
        cout<<tmp<<endl;
        return;
    }
    char c = '\0';
    for(int i = 0; i < n; ++i){
        if(!vis[i]&&s[i]!=c){  //如果和上次选用的字符不相同
            vis[i] = true;
            tmp[step] = s[i];
            c = s[i]; //记录本次递归采用的字符
            dfs(step+1);
            vis[i] = false;
        }
    }
}

int main()
{
    // freopen("in.txt","r",stdin);
    cin>>s;
    n = strlen(s);
    sort(s,s+n);
    dfs(0);
    return 0;
}

当然,stl明显更简洁些…..

// #include <bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<string>
using namespace std;
const int N = 201;

int main()
{
    // freopen("in.txt","r",stdin);
    string s;
    cin>>s;
    sort(s.begin(),s.end());
    do {
        cout<<s<<endl;
    } while(next_permutation(s.begin(),s.end()));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/eternally831143/article/details/79735549