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)); //不断的生成新序列 }
总结:
好好看书非常重要……先把书本的学会了再说……