POJ 3187 Backward Digit Sums (全排列)

Backward Digit Sums
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 5727   Accepted: 3320

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.

题意;给你一个最底层的数,求能按照题目那样阶梯型进行向下累加的序列的最小字典序


思路:全排列暴力验证就行了

ac代码:

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stack>
#include<set>
#include<queue>
#include<vector>
#include<iostream>
#include<algorithm>
#define MAXN 1010000
#define ll long long
#define INF 0xfffffff
#define mem(x) memset(x,0,sizeof(x))
#define PI acos(-1)
#define eps 1e-8
using namespace std;
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
ll powmod(ll a,ll b,ll MOD){ll ans=1;while(b){if(b%2)ans=ans*a%MOD;a=a*a%MOD;b/=2;}return ans;}
double dpow(double a,ll b){double ans=1.0;while(b){if(b%2)ans=ans*a;a=a*a;b/=2;}return ans;}
//head

int a[MAXN];
int b[MAXN];
void debug(int x)
{
	for(int i=1;i<=x;i++)
	printf("%d ",a[i]);
	printf("\n");
}
int fun(int x)
{
	int k=x,i,j;
	for(i=1;i<=x;i++)
	b[i]=a[i];
	//debug(x);
	for(i=1;i<=x;i++)
	{
		for(j=1;j<k;j++)
		b[j]=b[j]+b[j+1];
		k--;
	}
	//printf("%d\n",b[1]);
	return b[1];
}
int main()
{
	int n,i,j,m;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		for(i=1;i<=n;i++)
		a[i]=i;
		if(fun(n)==m)
		{
			printf("%d",a[1]);
			for(i=2;i<=n;i++)
			printf(" %d",a[i]);
			continue;
		}
		while(next_permutation(a+1,a+n+1))
		{
			if(fun(n)==m)
			{
				printf("%d",a[1]);
				for(i=2;i<=n;i++)
				printf(" %d",a[i]);
				break;
			}
		}
	}
	return 0;
}


你可能感兴趣的:(POJ 3187 Backward Digit Sums (全排列))