poj 3187 Backward Digit Sums(dfs暴搜)

问题描述

FJ and his cows enjoy playing a mental game. They write down the numbers from 1 to N (1 <= N <= 10) in a certain order and then sum adjacent numbers to produce a new list with one fewer number. They repeat this until only a single number is left. For example, one instance of the game (when N=4) might go like this:

    3   1   2   4 
 4   3   6 
 7   9 
 16
Behind FJ's back, the cows have started playing a more difficult game, in which they try to determine the starting sequence from only the final total and the number N. Unfortunately, the game is a bit above FJ's mental arithmetic capabilities.

Write a program to help FJ play the game and keep up with the cows.

输入

Line 1: Two space-separated integers: N and the final sum.

输出

Line 1: An ordering of the integers 1..N that leads to the given sum. If there are multiple solutions, choose the one that is lexicographically least, i.e., that puts smaller numbers first.

样例输入

4 16

样例输出

3 1 2 4

提示

Explanation of the sample:

There are other possible sequences, such as 3 2 1 4, but 3 1 2 4 is the lexicographically smallest.

这道题难点主要求是顶点个最后一层的数字的关系。起初我也不知道,后来看了http://blog.sina.com.cn/s/blog_6635898a0100kko3.html这篇题解才懂得原来
sum = C(0,n-1)*num[0] + C(1,n-1)*num[1] +``+C(n-1,n-1)*num[n-1]。
然后就是暴搜num数组;

#include <iostream>
#include <stdio.h>
using namespace std;

int n,sum,c[11],dp[11];int vis[11];
bool flag;

int fond_c(int a,int b)//求C(a,b)
{
    int ans=1;int m=b;
    for(int i=1;i<=a;i++)
    {
        ans=ans*m/i;
        m--;
    }
    return ans;
}

void dfs(int deep,int val)
{

    if(val>sum)return ;
    if(deep==n)
    {
        if(val==sum)
        {
            for(int i=0;i<n;i++)
                printf("%d ",dp[i]);
            flag=true;
        }
        return ;
    }
    for(int i=1;i<=n&&!flag;i++)
    {
        if(!vis[i])
        {
            dp[deep]=i;
            vis[i]=1;
            dfs(deep+1,val+i*c[deep]);
            vis[i]=0;
        }
    }
}

int main()
{
    scanf("%d%d",&n,&sum);
    for(int i=0;i<=n-1;i++)
    {
        c[i]=fond_c(i,n-1);
    }
    dfs(0,0);
}




你可能感兴趣的:(poj 3187 Backward Digit Sums(dfs暴搜))