P1118 [USACO06FEB] Backward Digit Sums G/S

题目描述

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

输入格式

共一行两个正整数 n,sumn,sumn,sum

输出格式

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

当无解的时候,请什么也不输出。

输入输出样例 #1

输入 #1

4 16

输出 #1

3 1 2 4

说明/提示

  • 对于 40%40\%40% 的数据,1≤n≤71\le n\le 71n7
  • 对于 80%80\%80% 的数据,1≤n≤101\le n \le 101n10
  • 对于 100%100\%100% 的数据,1≤n≤121\le n \le 121n121≤sum≤123451\le sum\le 123451sum12345

C++实现

#include
#include
const int PT[][13] = //先打一张杨辉三角表
{
{ 1 } , // N = 1
{ 1 , 1 } , // N = 2
{ 1 , 2 , 1 } , // N = 3
{ 1 , 3 , 3 , 1 } , // N = 4
{ 1 , 4 , 6 , 4 , 1 } , // N = 5
{ 1 , 5 , 10, 10, 5 , 1 } , // N = 6
{ 1 , 6 , 15, 20, 15, 6 , 1 } , // N = 7
{ 1 , 7 , 21, 35, 35, 21, 7 , 1 } , // N = 8
{ 1 , 8 , 28, 56, 70, 56, 28, 8 , 1 } , // N = 9
{ 1 , 9 , 36, 84,126,126, 84, 36, 9 , 1 } , // N = 10
{ 1 , 10, 45,120,210,252,210,120, 45, 10 , 1 } , // N = 11
{ 1 , 11, 55,165,330,462,462,330,165, 55 ,11 , 1 } }; // N = 12
int a[15],dfs(int s,int p);
int n,sum;
bool finished,used[15];
int main()
{
scanf(“%d%d”,&n,&sum);
dfs(0,0); // 从 0,0 开始搜索
if(finished)for(int i=0;i<n;i++)printf("%d ",a[i]);
}
int dfs(int s,int p)
{
if( p == n )
{
if( s==sum) finished = true ;
return 0;
}
for(int i=1;i<=n;i++)
{
if(used[i])continue ;
used[i] = true ;
a[p] = i;
if( s+ PT[n-1][p]*a[p] <= sum )dfs( s+ PT[n-1][p]*a[p] , p+1 ) ;
if(finished )return 0;
used[i] = false ;
}
}

在这里插入图片描述

后续

接下来我会不断用C++来实现信奥比赛中的算法题、GESP考级编程题实现、白名单赛事考题实现,记录日常的编程生活、比赛心得,感兴趣的请关注,我后续将继续分享相关内容

Logo

集算法之大成!助力oier实现梦想!

更多推荐