[ZCMU OJ]1620: 全排列 & 1683: 排列(next_permutation全排列函数的使用)

首先我们先来认识一个函数:全排列函数——next_permutation。这个函数用于全排列问题功能十分强大。与之相对还有一个函数prev_permutation;二者区别在于:前者求的是下一个全排列,而后者求的是上一个全排列;二者在用法上是相同的(类似sort的用法)。对于next_permutation,如果当前的序列存在下一个全排列则return true,否则return false;prev_permutation同理。

函数原型:

 #include <algorithm>

bool next_permutation(iterator start,iterator end);

接下来两道题是next_permutation的典型用法。

———————————————————————————————

1620: 全排列

Description

给定n个数 a[0] , a[1] ........ a[n-1], 输出其全排列。

Input

第一行输入一个数n,(n<7)

接下来一行输入n个数。

Output

按字典序从小到大输出全排列

Sample Input

3

1 2 3

3

1 2 2

Sample Output

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

1 2 2

2 1 2

2 2 1

———————————————————————————————————————————

ac代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	while(cin>>n)
	{
		int a[n];
		for(int i=0;i<n;i++)
		cin>>a[i];
		
		sort(a,a+n); //记得给数组提前排好序 
		
		do
		{
			for(int i=0;i<n;i++)
			{
				cout<<a[i];
				if(i!=n-1)
				cout<<" ";
			}
			cout<<endl;
		}while(next_permutation(a,a+n));
	} 
} 

———————————————————————————————————————————

1683: 排列

Description

给你一个数,输出所有的排列

Input

一个数n

Output

看样例

Sample Input

2

Sample Output

1 2

2 1

———————————————————————————————————————————

ac代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	while(cin>>n)
	{
		int a[n+1];
		for(int i=1;i<=n;i++)
		a[i]=i;
		
		sort(a+1,a+n+1);//仍然需要排序 
		
		do
		{
			for(int i=1;i<=n;i++)
			{
				cout<<a[i];
				if(i!=n)
				cout<<" ";
			}
			cout<<endl;
		} while(next_permutation(a+1,a+n+1));//注意边界 
	} 
}

猜你喜欢

转载自blog.csdn.net/Solar_Zheng0817/article/details/124414946