NOIP 1118 数字三角形(dfs剪枝 杨辉三角)

题目描述

FJ and his cows enjoy playing a mental game. They write down the numbers from 11 to N(1 \le N \le 10)N(1N10) 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=4N=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 NN . 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.

有这么一个游戏:

写出一个 11 至 NN 的排列 a_iai ,然后每次将相邻两个数相加,构成新的序列,再对新序列进行这样的操作,显然每次构成的序列都比上一次的序列长度少 11 ,直到只剩下一个数字位置。下面是一个例子:

3,1,2,43,1,2,4

4,3,64,3,6

7,97,9

1616

最后得到 1616 这样一个数字。

现在想要倒着玩这样一个游戏,如果知道 NN ,知道最后得到的数字的大小 sumsum ,请你求出最初序列 a_iai ,为 11 至 NN 的一个排列。若答案有多种可能,则输出字典序最小的那一个。

[color=red]管理员注:本题描述有误,这里字典序指的是 1,2,3,4,5,6,7,8,9,10,11,121,2,3,4,5,6,7,8,9,10,11,12

而不是 1,10,11,12,2,3,4,5,6,7,8,91,10,11,12,2,3,4,5,6,7,8,9 [/color]

输入输出格式

输入格式:

两个正整数 n,sumn,sum 。

输出格式:

输出包括 11 行,为字典序最小的那个答案。

当无解的时候,请什么也不输出。(好奇葩啊)

输入输出样例

输入样例#1:  复制
4 16
输出样例#1:  复制
3 1 2 4

说明

对于 40\%40% 的数据, n≤7n7 ;

对于 80\%80% 的数据, n≤10n10 ;

对于 100\%100% 的数据, n≤12,sum≤12345

n12,sum12345 。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define LL long long
using namespace std;
int YH[20][20];
int n,sum;
int a[20];
int vis[20];
int flag=0;
void YH_()
{
    YH[0][0]=1;
    for(int i=1;i<=12;i++)
    {
        for(int j=0;j<=i;j++)
        {
            if(j==0||j==i)
            {
                YH[i][j]=1;
            }
            else
            {
                YH[i][j]=YH[i-1][j-1]+YH[i-1][j];
            }
        }
    }
}
void Print()
{
    for(int i=0;i<n;i++)
    {
        cout<<a[i];
        if(i==n-1)
            cout<<endl;
        else cout<<" ";
    }
}
void dfs(int ans,int step)
{
    if(flag)return ;
    if(ans>sum)return ;
    if(step==n&&ans==sum)
    {
        Print();
        flag=1;
        return ;
    }
    for(int i=1;i<=n;i++)
    {
        if(vis[i]==1)continue;
        if(vis[i]==0)
        {
            a[step]=i;
            vis[i]=1;
            ans+=i*YH[n-1][step];
            //cout<<ans<<"+="<<i<<"*"<<YH[n-1][step]<<endl;
            dfs(ans,step+1);
            vis[i]=0;
            ans-=i*YH[n-1][step];
        }
    }
}
int main()
{
    YH_();
    cin>>n>>sum;
    dfs(0,0);
}

对于n个数(a,b,c,d..)的情况a,b,c,d,的系数刚好为杨辉三角的值。

例如n=4 1a+3b+3c+d

猜你喜欢

转载自blog.csdn.net/weixin_40894017/article/details/80501866