经典题:求字典序第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 <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <ctype.h>
#include <cmath>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <vector>
#include <limits.h>
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<n;i++) //合并掉这个位置
				num[i]=num[i+1];
			m=m-(zushu-1)*(f[n-1]+1)-1; //-1是因为第一个只有一个数字
			n--;
		}
		printf("\n");
	}
}
/*------------------Main Function------------------*/
int main()
{
	//freopen("test.txt","r",stdin);
	//freopen("cowtour.out","w",stdout);
	//freopen("cowtour.in","r",stdin);
	work();
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值