POJ 3187:Backward Digit Sums(dfs)

来源:互联网 发布:怎么查看端口号被占用 编辑:程序博客网 时间:2024/06/05 07:30

原题地址:点击打开链接

题意:

如对于n=4sum=16,输出序列3 1 2 4(为满足的序列中字典序最小的数列)

                    3       1       2       4

                        4       3       6

                            7       9

                               16

其中1 <= n <= 10

Time Limit: 1000MS

Memory Limit: 65536K

 

Sample Input

4 16

Sample Output

3 1 2 4

 

答案:

#include <iostream>#include <algorithm>#define MAX_N 10using namespace std;int n, sum, a[MAX_N];bool Check(){if(1 == n)return 1 == sum;int b[MAX_N][MAX_N] = {0}, i, j = 0;for (i = 0; i < n; i ++)b[0][i] = a[i];for (i = 1; i < n ; i ++)for (j = 0; j < n - i; j ++)b[i][j] = b[i - 1][j] + b[i - 1][j + 1];return b[i - 1][j - 1] == sum;}void solve(){int i;for(i = 0; i < n; i ++)a[i] = i + 1;do{if(Check())break;}while(next_permutation(a, a + n));for (i = 0; i < n - 1; i ++)cout << a[i] << " ";cout << a[i] << endl;}int main(){while(cin >> n >> sum){solve();}return 0;}


直接对1-n全排列找到第一个就ok,复杂度为n!

这道题之前用dfs自己实现全排列,提交一直是WA,换了next_permutation一下子就AC了



0 0