POJ 3187 Backward Digit Sums

http://poj.org/problem?id=3187

穷竭搜索 全排列 然后按规则求和 排列之前先按升序排序

这样可以保证第一个和为k的就是符合最小序列的结果

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 int sum(int a[], int n)
 8 {
 9     int s[11];
10     for (int i = 0; i < n; i++)
11     {
12         s[i] = a[i];
13     }
14     while (n != 1)
15     {
16         n--;
17         for (int i = 0; i < n; i++)
18         {
19             s[i] += s[i+1];
20         }
21     }
22     return s[0];
23 }
24 int main()
25 {
26     int s,n;
27     int a[11], calc[11];
28     freopen("in.txt","r", stdin);
29     while (~scanf("%d%d", &n, &s))
30     {
31         for(int i = 0; i < n; i++)
32         {
33             a[i] = i+1;
34         }
35         do
36         {
37             for (int i =0 ;i < n; i++)
38             {
39                 calc[i] = a[i];
40             }
41             if ( sum(calc, n) == s) break;
42         }while (next_permutation(a, a+n));
43         for (int i =0 ; i < n; i++)
44         {
45             printf("%d ", calc[i]);
46         }
47         putchar('\n');
48     }
49     return 0;
50 }

 

posted @ 2017-01-18 23:16  Lorazepam  阅读(121)  评论(0编辑  收藏  举报