数字三角形[USACO06FEB](洛谷P1118 & POJ3187)

【题目描述】

FJ and his cows enjoy playing a mental game. They write down the numbers from 1 toN(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. 

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.

【翻译】

写出一个1至N的排列Ai​,然后每次将相邻两个数相加,构成新的序列,再对新序列进行这样的操作,显然每次构成的序列都比上一次的序列长度少1,直到只剩下一个数字位置。现在想要倒着玩这样一个游戏,如果知道N,知道最后得到的数字的大小sumsum,请你求出最初序列Ai​,为1至N的一个排列。若答案有多种可能,则输出字典序最小的那一个。

【数据范围】

n<=12

sum<=12345

【分析】

将样例给出的4个数用a,b,c,d表示,然后写出sum的表达式,易得a,b,c,d的系数就是杨辉三角形第4行的数。配出系数,暴力枚举a,b,c,d即可。注意剪枝!

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=15;
int c[N][N],a[N],b[N]={0};
int n,m,flag=0;
void dfs(int step,int sum){
	if (flag || sum>m) return;
//sum>m就return这个优化在洛谷上非常厉害,第2个点本来800ms+,加了这句话瞬间50ms-
//但是可以构造较大的sum,使这个优化无效
//这说明洛谷的数据太弱了
//但是这个代码在POJ只用0ms就过了,POJ是数据更弱还是评测机太好。。。
	if (step>n){
		if (sum==m){
			flag=1;
			for (int i=1;i<=n;i++) printf("%d ",a[i]);
		}
		return;
	}
	for (int i=1;i<=n;i++){
		if (b[i]) continue;
		b[i]=1;
		a[step]=i;
		dfs(step+1,sum+c[n][step]*i);
		b[i]=0;
	}
}
int main(){
	scanf("%d%d",&n,&m);
	c[1][1]=1;
	for (int i=2;i<=n;i++){
		c[i][1]=c[i][i]=1;
		for (int j=2;j<n;j++) c[i][j]=c[i-1][j]+c[i-1][j-1];
	}
	dfs(1,0);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值