next_permutation全排列函数的使用

目录

next_permutation的功能

next_permutation的形参

例题:角三辉杨


next_permutation的功能

permutation n.排列(方式); 组合(方式); 置换;

next_permutation(跟prev_permutation函数的功能相反),顾名思义,就是下一个排列(按照字典序排序的下一个排列)。例如,“1 2 3 4”的下一个排列就是“1 2 4 3”。

如果在do……while语句的while括号中放入next_permutation,那么语句块将会执行到最后一个排列(例如“1 2 3 4”的最后一个排列就是“4 3 2 1”)。

next_permutation的形参

next_permutation传入两个地址值:需要排列的第一个元素的地址值和最后一个元素的地址值。

例题:角三辉杨

Have you heard of Yanghui Triangle? Both sides of Yang Hui Triangle are one, and the sum of these two numbers is directly below the two numbers. According to this rule, we will get a Yang Hui Triangle.

Today, ywh has a problem for dzy. Ywh has an permutation in his hand, and he operates the permutation in the form of Yang Hui Triangle and gets a num. The form is as follows:

3        1        2        4

     4        3        6

          7        9

              16

But he only told dzy the length of the permutation and the final num. Can you help dzy find the permutation? If this permutation cannot be found, output "Not Found".

Recall that a permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order.

Input

Two space-separated integers: n\ (1\leq n\leq 11)n (1≤n≤11) and the final num(1\leq num\leq 10^6)num(1≤num≤106).

Output

If there is no such array b, print "Not Found".

Otherwise in the only line print n space-separated integers p_1, p_2, ..., p_np1​,p2​,...,pn​. Note that pp must be a permutation.

If there are multiple answers, choose the one that is lexicographically least.

Sample 1

InputOutput
4 16
3 1 2 4 

简析:题意中的permutation指的是全排列。

用a b c d e这个排列进行模拟:

a                        b                        c                        d                        e

           a+b                    b+c                    c+d                    d+e

                     a+2b+c               b+2c+d               c+2d+e

                               a+3b+3c+d        b+3c+3d+e

                                          a+4b+6c+4d+e

不难发现,最后得到的sum正是a b c d e与杨辉三角第五行的乘积。

那么n级排列最后得到的sum就是它与杨辉三角第n行的乘积。用这个思路可以很快得出已知排列的sum。

枚举所有排列的sum与给定的sum比较,就可以得到正确的那个排列。

代码实现如下:

#include <bits/stdc++.h> 
using namespace std;
int main()
{
	int n,m,sum,a[12][12]={0},b[12]={0};
	cin>>n>>m;
	a[1][1]=a[2][1]=a[2][2]=1;
	for(int i=3;i<12;i++)
		for(int j=1;j<=i;j++)
			a[i][j]=a[i-1][j-1]+a[i-1][j];
	for(int i=1;i<=n;i++)b[i]=i;
	do
	{
		sum=0;
		for(int i=1;i<=n;i++)sum+=b[i]*a[n][i];
		if(sum==m)
		{
			cout<<b[1];
			for(int i=2;i<=n;i++)cout<<' '<<b[i];
			return 0;
		}
	}while(next_permutation(b+1,b+n+1));
	cout<<"Not Found";
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值