POJ 3187 Backward Digit Sums 全排列next_permutation

Backward Digit Sums

Time Limit: 1000MS

 

Memory Limit: 65536K

Total Submissions: 9043

 

Accepted: 5136

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.

Source

USACO 2006 February Gold & Silver

算法分析:

暴力枚举:将n个数全排列一个个试即ok

代码实现:

#include<cstdio>  
#include<cstring>  
#include<cstdlib>  
#include<cctype>  
#include<cmath>  
#include<iostream>  
#include<sstream>  
#include<iterator>  
#include<algorithm>  
#include<string>  
#include<vector>  
#include<set>  
#include<map>  
#include<stack>  
#include<deque>  
#include<queue>  
#include<list>  
using namespace std;  
const double eps = 1e-8;  
typedef long long LL;  
typedef unsigned long long ULL;  
const int INT_INF = 0x3f3f3f3f;  
const int INT_M_INF = 0x7f7f7f7f;  
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;  
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;  
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};  
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};  
const int MOD = 1e9 + 7;  
const double pi = acos(-1.0);  
const int MAXN = 1e5 + 10;  
const int MAXT = 10000 + 10;  
const int M=1005;
using namespace std;
int main()
{
 
  int n,m;
  
  while(scanf("%d%d",&n,&m)!=EOF)
  {
  	 int a[20],f[20];
  	 for(int i=1;i<=n;i++)   //初始化
  	 	  a[i]=i;
	do
  	 {
  	 	for(int i=1;i<=n;i++)    //
  	       f[i]=a[i];
  	    for(int i=1;i<n;i++)    //层数
  	    for(int j=1;j<=n-i;j++)   //每层数字
  	    {
  	 	   f[j]+=f[j+1];
  	    }	
  	    if(f[1]==m)
		{
			for(int i=1;i<n;i++)
				cout<<a[i]<<" ";
			cout<<a[n]<<endl;
			break;
		}
		
  	 }while(next_permutation(a+1,a+n+1));    //实现a中的全排列
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/sdz20172133/article/details/81212836