Backward Digit Sums(序列生成 + 模拟)

本文介绍了一道名为C-BackwardDigitSums的编程题目,任务是从1到N的数字中找到一个特定序列,使得通过连续相加的方式最终得到一个指定的总和。文章详细阐述了解题思路及实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

C - Backward Digit Sums

  Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u  

Submit Status Practice POJ 3187 

 

Description

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.

 

Input

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

 

 

Output

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.

 

Sample Input

4 16

 

Sample Output

3 1 2 4

 

Hint

Explanation of the sample: 

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

    题意:

    给出N与总数M,N指从1到N一共有N个数,通过之间任意排序,相邻两个数两两加和最后得出一个总数,当这个总数等于M时,则输出该序列,这个序列可能不止一种,输出字典序最小的一组数据。

   思路:

   先用二维数组将这N个数放在第一行位置上,然后通过调用algorithm函数中的next_permutation来对刚行数据不停生成新排序序列来进行两两加和处理,当一遇到和等于M时,输出该序列。

 AC and test:

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<stdlib.h>
using namespace std;
int main()
{
	int N,M,i,j;
	int a[15][15];
	memset(a,0,sizeof(a));
	scanf("%d%d",&N,&M);
	for(i=0;i<N;i++)
	   a[0][i]=i+1;
	
//	for(i=0;i<N;i++)
//	 printf("%d ",a[0][i]);
//	printf("\n");
	
	
//	sort(a[0],a[0]+N);
	
//	for(i=0;i<N;i++)
//	 printf("%d ",a[0][i]);
//	printf("\n");
	
    do
    {
      for(i=1;i<N;i++)
	   for(j=0;j<N-i;j++)
	  	a[i][j]=a[i-1][j]+a[i-1][j+1];
	  	
//	  for(i=0;i<N;i++)
//	   {
//	    for(j=0;j<N;j++)
//	   	printf("%d ",a[i][j]);
//	   	printf("\n");
//	   }
//printf("%d\n",a[N-1][0]);
//	   system("pause");
	   
	  if(a[N-1][0]==M) 
	  {
	  	for(i=0;i<N;i++)
	  	{
	  	  printf("%d",a[0][i]);
	  	  i==N?printf("\n"):printf(" ");
	    }
	    break;
	  }
    }while(next_permutation(a[0],a[0]+N));  //不断的生成新序列
}

   总结:

   好好看书非常重要……先把书本的学会了再说……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值