杭电oj HDOJ 2062 Subset sequence
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=2062
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.
题目大意
现在把“子集序列”定义为“非空子集”(如{1, 2}的“子集序列”为{1}, {1, 2},{2},{2,1}),本题要求按词典顺序对测试集合An的所有子集进行排序,给出题中要求的第m个。
解题思路
由于本题对所谓的“非空子集”做了重新的定义,所以不能按“通常的”集合思量来考虑。
- A1={1},其子集序列的字典序排列为 { 1 } \{1\} {1}
- A2={1,2},其子集序列的字典序排列为 { 1 } 、 { 1 , 2 } \{1\}、\{1,2\} {1}、{1,2} { 2 } 、 { 2 , 1 } \{2\}、\{2,1\} {2}、{2,1}
- A3={1,2,3},其子集序列的字典序排列为
{
1
}
、
{
1
,
2
}
、
{
1
,
2
,
3
}
、
{
1
,
3
}
、
{
1
,
3
,
2
}
\{1\}、\{1,2\}、\{1,2,3\}、\{1,3\}、\{1,3,2\}
{1}、{1,2}、{1,2,3}、{1,3}、{1,3,2}
{
2
}
、
{
2
,
1
}
、
{
2
,
1
,
3
}
、
{
2
,
3
}
、
{
2
,
3
,
1
}
\{2\}、\{2,1\}、\{2,1,3\}、\{2,3\}、\{2,3,1\}
{2}、{2,1}、{2,1,3}、{2,3}、{2,3,1}
{
3
}
、
{
3
,
1
}
、
{
3
,
1
,
2
}
、
{
3
,
2
}
、
{
3
,
2
,
1
}
\{3\}、\{3,1\}、\{3,1,2\}、\{3,2\}、\{3,2,1\}
{3}、{3,1}、{3,1,2}、{3,2}、{3,2,1}
假设集合An的子集序列个数为f(n),因此可以得出 f ( n ) = n × ( f ( n − 1 ) + 1 ) f(n)=n\times(f(n-1)+1) f(n)=n×(f(n−1)+1)又设子集序列中每组的个数为g(n),所以 g ( n ) = f ( n ) n g(n)=\frac{f(n)}{n} g(n)=nf(n)
接下来使用给出的测试用例(n=3,m=10)来演示求解过程,由m除以对应的g(n)来确定所求子集的所属“组数”group为第2组,所以所求子集的第一个数为“2”,接下来把第2组子集中的所有第一个数去掉,剩下两组四个集合: { 1 } 、 { 1 , 3 } \{1\}、\{1,3\} {1}、{1,3} { 3 } 、 { 3 , 1 } \{3\}、\{3,1\} {3}、{3,1}接下来对m和n进行迭代, m = m − ( g r o u p − 1 ) × g ( n ) − 1 m=m-(group-1)\times g(n)-1 m=m−(group−1)×g(n)−1所以m变成为4,n=n-1=3,因此把问题的规模缩小为(n=2,m=4),接下来继续由m除以对应的g(n)来确定所求子集的所属“组数”group…直到n=0或m=0时结束迭代,在这个过程中每一个找出的数而组成的子集就是问题所求的子集
本人的C++解决方案
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n, i = 2, group, num[21], count, pos, j;
__int64 m, fn[21], gn[21];
// 因为每个数只能出现一次,出现过的时应该从所选序列中剔除
// 标记数组用来标记每个数是否还在所选序列中
bool mark[21];
// 可组成题中要求子集的总数
fn[1] = 1;
for (; i <= 20; i++) {
fn[i] = i * (fn[i - 1] + 1);
}
// 每一组子集的个数
for (i = 1; i <= 20; i++) {
gn[i] = fn[i] / i;
}
while (cin >> n >> m) {
// 初始化备选序列
for (i = 1; i <= n; i++) {
num[i] = i;
}
// 初始化标记数组
for (i = 1; i <= n; i++) {
mark[i] = true;
}
// 用于输出每个所选数之间的“空格”所用,输出最后一个所选数之后不再输出“空格”
count = 0;
// n=0或m=0时结束迭代
while (n && m) {
// pos和j都用于找出当前的所选数所用
pos = 1;
j = 0;
// 确定所求子集的所属“组数”group
group = int(ceil(long double(m) / gn[n]));
// 确定所选数
while (j != group) {
if (mark[pos]) {
j++;
}
pos++;
}
if (count) {
cout << " ";
}
cout << num[pos - 1];
count++;
// 把选过的数剔除备选序列
mark[pos - 1] = false;
// 迭代m和n
m = m - (group - 1) * gn[n] - 1;
n--;
}
cout << endl;
}
return 0;
}
代码通过HDOJ平台运行检查,如发现错误,欢迎指出和纠正,谢谢!