PKU 3187 解题报告

Backward Digit Sums

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 90   Accepted Submission(s) : 37
Problem 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
 
 
 
分析:这是一道很简单同时也是一道很有意义的暴力题,这道题让我认识到了回溯和迭代的思想,以及暴力枚举的算法。该题大意,找出N个数的字典序排列 ,并求出满足题中累加方法的而求得值的最小字典序排列,这里的最小意思为:顺序靠前  如 1 2 3 就比 2 1 3 小 。 
代码如下:
 1 #include <iostream>
 2 #include <algorithm>   algorithm
 3 using namespace std;
 4 
 5 
 6 int main(){
 7      int n,sum,a[10],b[10],i,j;
 8      cin >> n >> sum;
 9      for(i=0;i<n;i++) a[i] = i+1;
10      do{
11         for(i=0;i<n;i++) b[i] = a[i];
12         for(i=0;i<n-1;i++)
13         for(j=0;j<n-1-i;j++) 
14         
15             b[j] = b[j]+b[j+1];
16                  if(b[0] == sum){
17                  for(i=0;i<n;i++) 
18                 cout << a[i] << ' ';
19                  cout << endl;
20                  break;
21          }
22      }while(next_permutation(a,a+n));    
23 
24 
25     return 0;
26 }

我这里用到了一个stl 标准库函数 

next_permutation() 意思为产生下一个字典序全排列,同时也存在一个pre_permutation()意思是产生上一个字典序全排列。
 
posted @ 2013-04-08 23:05  box先森  阅读(218)  评论(0)    收藏  举报