POJ1731 Orders(dfs)

Orders

Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 11705   Accepted: 6941

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

题意:给的字符串含有重复字母,要求你给出不含重复项的全排列

思路:其实整体的思路很明确,建立一个新数组,dfs遍历给的字符串往上赋值就行

        唯一有一个地方要注意的就是,不能有重复的排列项。比如说输入案例给的bbdj,有两个b,你不能输出两遍bbdj

,所里这里就要加点东西,就是在你循环到要放第i个字符的时候,要规定以后的循环中第i个位置不可以选上一个选的那个字符

比如说:还是根据样例的输入,你已经排好了新数组的第一位是d,第二位就要从原数组中的b开始循环,当循环到第一个b时你令一个temp=b,然后往下深搜得到一个结果。当回溯到第二位上放哪个元素的时候,由于这时候temp=b,所以下面的第二个b就不能上任,这样就避免了,重复出现多次相同的排列组合的情况。

不明白的就看代码吧!!加油!

AC代码: 

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
char s[205],d[205];
int vis[205];
int len;
void dfs(int cnt,int k)
{
	int i;
	int temp='\0';
	if(k==len) 
	{
		for(i=0;i<len;i++)
		cout<<d[i];
		cout<<endl;
		return;
	}
	for(i=0;i<len;i++)
	{
		if(!vis[i]&&temp!=s[i])//这次选的字母不能和上次的相同 
		{
			vis[i]=1;
			d[k]=s[i];
			temp=s[i];//在这一层for循环中temp始终等于一个值 
			dfs(i+1,k+1);
			vis[i]=0;
		}
		//else dfs(i+1,k);
	}
}
int main()
{
	scanf("%s",s);
	len=strlen(s);
	sort(s,s+len);
	dfs(0,0);
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/zvenWang/article/details/83589358