题目链接:点击打开链接
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8742 | Accepted: 4963 |
Description
3 1 2 4 4 3 6 7 9 16Behind 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
Output
Sample Input
4 16
Sample Output
3 1 2 4
Hint
There are other possible sequences, such as 3 2 1 4, but 3 1 2 4 is the lexicographically smallest.
Source
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
int n,sum,v[20],right,a[20],c[20],i,b[20];
void dfs(int x)
{
int i,k,j;
if (right==1) return;
if (x==n)
{
k=n;
for (j=1;j<=n;j++)
b[j]=a[j];
while (1)
{
for (j=1;j<=k-1;j++)
b[j]=b[j]+b[j+1];
k--;
if (k<=1) break;
}
if (b[1]==sum)
{
for (j=1;j<=n;j++)
c[j]=a[j];
right=1;
}
return;
}
for (i=1;i<=n;i++)
if (v[i]==0)
{
x+=1;
a[x]=i;
v[i]=1;
dfs(x);
v[i]=0;
a[x]=-1;
x-=1;
}
}
int main()
{
scanf("%d%d",&n,&sum);
for (i=1;i<=n;i++)
v[i]=0;
right=0;
dfs(0);
for (i=1;i<=n;i++)
printf("%d ",c[i]);
return(0);
}