hdu 1027

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1027

给出 n m ,求对于 n 的全排列里第 m 小的,可以直接用dfs,因为m 最大是 10000,最多变换后面的8位就可以了,也可以直接用库函数里的全排列函数,先求出第m 小的全排列需要变换的最少的个数,然后对于最后面的几个数进行排列,前面的不用动

View Code
 1 typedef long long ll;
 2 int n,num;
 3 int mark[9];
 4 ll tsum;
 5 int main()
 6 {
 7     int n,m;
 8     int i,j;
 9     while(~scanf("%d%d",&n,&m))
10     {
11         int tem = 1;
12         for(i = 2; i <= 8; i++)
13         {
14             tem *= i;
15             if(tem >= m) break;
16         }
17         int k = 0;
18         for(j = n - i + 1; j <= n; j++)
19         mark[k ++] = j;
20         int sum = 2;
21         while(next_permutation(mark,mark + k) && sum < m)
22         {
23             sum ++;
24         }
25         printf("%d",1);
26         for(j = 2; j <= n - i; j++)
27         printf(" %d",j);
28         for(i = 0; i < k; i++)
29         printf(" %d",mark[i]);
30         printf("\n");
31     }
32     return 0;
33 }

 

View Code
 1 void per(int n,int *a,int cur)
 2 {
 3     int i,j;
 4     if(sum == m) return ;
 5     if(cur == n)
 6     {
 7         sum ++;
 8         if(sum == m)
 9         {
10             for(i = 0; i < n; i++)
11             printf("%d ",a[i]);
12             cout<<endl;
13         }
14         return ;
15     }
16     for(i = 1; i <= n; i++)
17     {
18         if(!vis[i])
19         {
20             vis[i] = 1;
21             a[cur] = i;
22             per(n,a,cur + 1);
23             vis[i] = 0;
24         }
25     }
26 }
27 int main()
28 {
29     int i,j;
30     int n;
31     int a[1001];
32     while(~scanf("%d%d",&n,&m))
33     {
34         sum = 0;
35         per(n,a,0);
36     }
37 }
posted @ 2012-11-20 19:28  AC_Girl  阅读(181)  评论(0编辑  收藏  举报