poj 3187 이전 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_6635898a 0100 kko 3. 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);
}

좋은 웹페이지 즐겨찾기