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
很好的题,题意也很简单。下面用两种方法。
1.stl
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int arr[10];
int sum[10];
int main()
{
int N, anw = 0;
memset(arr, 0, sizeof(arr));
memset(sum, 0, sizeof(sum));
while (scanf("%d", &N) != EOF){
scanf("%d", &anw);
int n = N;
for (int i = 1; i <= N; i++){
arr[i - 1] = i;
sum[i - 1] = i;
}
while (n != 1){
for (int i = 1; i <= n - 1; i++){
sum[i - 1] = sum[i - 1] + sum[i];
}
n--;
if (n == 1){
if (sum[0] == anw){
break;
}
else{
n = N;
next_permutation(arr, arr + N);
for (int i = 0; i < N; i++){
sum[i] = arr[i];
}
}
}
}
for (int i = 0; i < N ; i++){
printf("%d ", arr[i]);
}
putchar(10);
memset(arr, 0, sizeof(arr));
memset(sum, 0, sizeof(sum));
}
return 0;
}
2.深搜。
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int m,n;
int c[15];
int vis[15];
int num[15],flag;
int find_C(int a, int nu)
{
int i = 1, ans = 1;
while(i <= a)
{
ans = ans * nu / i;
nu --;
i ++;
}
return ans;
}
void dfs(int d,int val)
{
if(val>m)return;
int i;
if(d==n)
{
if(!flag&&val==m)
{
flag=1;
for(i=0; i<n; i++)
cout<<num[i]<<" ";
cout<<endl;
return;
}
}
for(i=1; i<=n&&!flag; i++)
{
if(!vis[i])
{
num[d]=i;
vis[i]=1;
dfs(d+1,val+c[d]*i);
vis[i]=0;
}
}
}
int main()
{
cin>>n>>m;
flag=0;
for(int i=0; i<n; i++)
c[i]=find_C(i,n-1);
memset(vis,0,sizeof(vis));
dfs(0,0);
return 0;
}
总结一下杨辉三角,如何求前面的系数。 sum = 0Cn-1*num[0] + 1Cn-1*num[1] +``+ n-1Cn-1*num[n-1],即第n行的m个数可表示为C(n-1,m-1)(n-1下标,m-1上标),即为从n-1个不同。 下面一段是求组合数的:
int find_C(int a, int nu)
{
int i = 1, ans = 1;
while(i <= a)
{
ans = ans * nu / i;
nu --;
i ++;
}
return ans;
}