[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));//注意边界 
	} 
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值