[恢]hdu 2062
2011-12-20 16:07:00
地址:http://acm.hdu.edu.cn/showproblem.php?pid=2062
题意:求n个数集合的第m个子序列,按字典序排序,也就是说1 2 < 1 2 3 < 1 3。
代码:
# include <stdio.h>
# include <string.h>
typedef long long ll ;
ll n, m, dp[25] = {0, 1} ;
int visited[25] ;
int flag ;
void init()
{
int i ;
for (i = 2 ; i <= 20 ; i++)
dp[i] = 1 + dp[i-1]* (i-1) ;
}
int find(int idx)
{
int i, cnt = 0 ;
for (i = 1 ; ; i++)
{
if (visited[i] == 0)
cnt++ ;
if (cnt == idx){
visited[i] = 1 ;
return i ;
}
}
return -1 ;
}
void output (ll n, ll m)
{
ll idx = (m-1)/dp[n] + 1 ;
if (flag == 0) flag = 1 ;
else printf (" ") ;
printf ("%d", find(idx)) ;
if (n == 1 || m%dp[n] == 1) return ;
output(n-1, (m-1)%dp[n]) ;
}
int main ()
{
init () ;
while (~scanf ("%I64d%I64d", &n, &m))
{
flag = 0 ;
memset(visited, 0, sizeof(visited)) ;
output(n,m) ;
printf ("\n") ;
}
return 0 ;
}