hdu 1716排列2

拿到这道题,我的想法是,利用dfs来做,可在解决输出同样的数这个问题时,遇到了麻烦,难以解决;且在格式的处理上也遇到了麻烦:
代码如下:

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define inf 0x7fffffff
bool mark[5];
int a[5], b[5];
queue q;
void dfs(int num)
{
	if (num == 4) {
		for (int i = 1;i <= 4;i++) {
			cout << b[i];
			if (i == 4) cout <<" ";
			
		}
		return;
	}
	   for(int j=1;j<=4;j++)
		   if (mark[j] == false) {
			   mark[j] = true;
			   b[num + 1] = a[j];
			   dfs(num + 1);
			   mark[j] = false;
		   }
}
int main()
{
	while (cin >> a[1] >> a[2] >> a[3] >> a[4])
	{
		if ((a[1] == 0) && (a[2] == 0) & (a[3] == 0) && (a[4] == 0)) break;
		memset(mark, false, sizeof(mark));
		for (int i = 1;i <= 4;i++)
		{
			if (a[i] == 0)continue;
			mark[i] = true;
			b[1] = a[i];
            dfs(1);
			cout << endl;
			mark[i] = false;
		}
		cout << endl;
	}
	return 0;
}

在查阅各个博主的博客后,得知了一个全排列的函数
#include
bool next_permutation(iterator start,iterator end)
(补:用的时候会改变数组的值,且next_permutation()在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数)
当当前序列不存在下一个排列时,函数返回false,否则返回true
感觉炒鸡厉害,于是打算利用这个函数,来写出这个程序;

// ConsoleApplication19.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#pragma warning(disable:4996);
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define inf 0x7fffffff
int a[5];
queue q;
int main()
{
	int tag = 0;
	while (cin >> a[1] >> a[2] >> a[3] >> a[4])
	{
		if (a[1] == 0 && a[4] == 0 && a[2] == 0 && a[3] == 0) break;
		if (tag) cout << endl;
		tag = 1;
		int flag = 1,tmp;
		do {
			if (a[1] == 0) { continue; }//0不能开头
			if (flag)
			{
				cout << a[1] << a[2] << a[3] << a[4];
				flag = 0;
			}
			else if (tmp == a[1]) 
				cout << " " << a[1] << a[2] << a[3] << a[4];
			else 
				cout << endl << a[1] << a[2] << a[3] << a[4];//当最大的位数改变时,直接换行,不用担心前面的空格
			tmp = a[1];
			
		} while (next_permutation(a + 1, a + 5));
		cout << endl;
	}
	return 0;
}



你可能感兴趣的:(HDUOJ)