数字三角形

原题目如下

FJ and his cows enjoy playing a mental game. They write down the numbers from 11 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.

中文题目如下


题目描述

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

3   1   2   4
  4   3   6
    7   9
     16

最后得到16这样一个数字,现在想要倒着玩这样一个游戏,如果知道N,知道最后得到的数字的大小sum,请你求出最初序列ai,为1至N的一个排列。若答案有多种可能,则输出字典序最小的那一个。
输入格式
两个正整数n,sum。

输出格式

输出包括1行,为字典序最小的那个答案。
当无解的时候,请什么也不输出。(好奇葩啊)

输入输出样例

输入 #1

4 16

输出 #1

3 1 2 4

说明/提示

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

对于80%的数据,nn≤10;

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

解法

比如偶设n=5,按照题目中的要求一步步模拟:
数字三角形_第1张图片
好,最终我们通过一步步的模拟,算出当n=5时,1~5位上对应的权值应该是:
位数 1 2 3 4 5
权值 1 4 6 4 1
这不就是杨辉三角的第五行么!!!!!!

别急,我们再来验证一个,设n=8,我们再来模拟一遍:

数字三角形_第2张图片
经过一番激动人心的验算,我们算出了当n=8时,1~8位对应的权值:

位数 1 2 3 4 5 6 7 8
权值 1 7 21 35 35 21 7 1
。。。算到这里,结论已经很明确了。。。

最终答案=该位杨辉三角中的数*该数

所以,本题的第一步,你需要先算出第n行杨辉三角的值是多少。

c[1][1]=1;//最左上角的数初始化为1
for(int i=2;i<=n;i++)//由于这里数组的记录是从1开始记的,所以不用担心越界
    for(int j=1;j<=i;j++)
        c[i][j]=c[i-1][j]+c[i-1][j-1];//每个数都等于它肩上两数之和
至此,辉煌的第一步完成了

深搜

#include
#include
#include
#include
#include
using namespace std;
int n,sum;//输入必备
int a[13];//输入必备
bool b[13];//判重必备
int yang[13][13];//杨辉三角必备
void dfs(int ceng,int s)
{
	if(s>sum)//如果现在累加的数已经超过了给定的数,就返回
	{
		return ;
	} 
    if(ceng>n)//如果已经搜完了n个数,就返回
    {
        if(s==sum)//如果答案跟给定的数相等
        {
            for(int i=1;i<=n;i++)
                cout<<a[i]<<" ";//输出
            exit(0);//终止程序
        }
        else
        {
        	return ;//如果没有输出答案,就返回
		}
    }
    for(int i=1;i<=n;i++)
    {
        if(!b[i])//如果当前这个数没有用过
        {
            b[i]=1;//标记成用过
            a[ceng]=i;//保存第ceng个取的数
            dfs(ceng+1,s+i*yang[n][ceng]);
            b[i]=0;//注意这里要将状态回归,不然TLE
        }
    }
}
int main()
{
    cin>>n>>sum;//输入
    yang[1][1]=1;
    for(int i=2;i<=n;i++)
    {
    	for(int j=1;j<=i;j++)
        {
            yang[i][j]=yang[i-1][j]+yang[i-1][j-1];///生成杨辉三角
		}
	}
    dfs(1,0);
    return 0;
}

你可能感兴趣的:(简约而不简单)