经典题:求字典序第m个的序列(2062)

Subset sequence

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4587    Accepted Submission(s): 2228


Problem Description
Consider the aggregate An= { 1, 2, …, n }. For example, A1={1}, A3={1,2,3}. A subset sequence is defined as a array of a non-empty subset. Sort all the subset sequece of An in lexicography order. Your task is to find the m-th one.
 

Input
The input contains several test cases. Each test case consists of two numbers n and m ( 0< n<= 20, 0< m<= the total number of the subset sequence of An ).
 

Output
For each test case, you should output the m-th subset sequence of An in one line.
 

Sample Input
 
   
1 1 2 1 2 2 2 3 2 4 3 10
 

Sample Output
 
   
1 1 1 2 2 2 1 2 3 1

设f[i]为1到n的排成的序列的总数,则可由打表发现:f[i]=n*(f[i-1]+1),这里其实蕴含着递归的思想。我们想要知道序列的具体位置,由规律性:zushu=ceil(m*1.0/(f[n-1]+1)),然后就可以取出首位元素了,剩下的序列可由递归求解,同时,原序列需要更新,元素被取出。然后就要更新内层的组数了:m=m-(zushu-1)*(f[n-1]+1)-1,因为每个序列的最小的那一个就一个元素,其后没有元素,所以需要-1。n还需自减一次。


/*------------------Header Files------------------*/
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
/*------------------Definitions-------------------*/
#define LL long long
#define PI acos(-1.0)
#define INF 0x3F3F3F3F
#define MOD 10E9+7
#define MAX 500050
/*---------------------Work-----------------------*/

void work()
{
	int n;
	LL m,f[25];
	f[0]=0;
	for(int i=1;i<=20;i++)
		f[i]=i*(f[i-1]+1);
	while(scanf("%d%I64d",&n,&m)==2)
	{
		int num[25];
		for(int i=1;i<=n;i++)
			num[i]=i;
		bool flag=true;
		while(m>0)
		{
			int zushu=ceil(m*1.0/(f[n-1]+1)); //计算所属组数
			if(!flag) printf(" ");
			flag=false;
			printf("%d",num[zushu]);
			for(int i=zushu;i



你可能感兴趣的:(思维/数学题)