数字三角形(洛谷-P1118)
題目描述
FJ?and his cows enjoy playing a mental game. They write down the numbers from?11?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 44 3 67 916Behind?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的排列?a_i,然后每次將相鄰兩個數相加,構成新的序列,再對新序列進行這樣的操作,顯然每次構成的序列都比上一次的序列長度少?1,直到只剩下一個數字位置。下面是一個例子:
3,1,2,4
4,3,6
7,9
16
最后得到?16?這樣一個數字。
現在想要倒著玩這樣一個游戲,如果知道?N,知道最后得到的數字的大小?sum,請你求出最初序列?a_i,為?1?至?N?的一個排列。若答案有多種可能,則輸出字典序最小的那一個。
管理員注:本題描述有誤,這里字典序指的是?1,2,3,4,5,6,7,8,9,10,11,12
而不是?1,10,11,12,2,3,4,5,6,7,8,9
輸入輸出格式
輸入格式:
兩個正整數?n,sum?。
輸出格式:
輸出包括?1?行,為字典序最小的那個答案。
當無解的時候,請什么也不輸出。
輸入輸出樣例
輸入樣例#1:
4 16
輸出樣例#1:
3 1 2 4
思路:
一開始毫無思路,看了題解知道答案的系數和與楊輝三角有關,于是先用一個數組存儲答案,再用dfs搜索。
最后兩個測試點超時,仔細看了看代碼,發現可以用剪枝,剪枝后成功AC。
注:關于答案系數與楊輝三角
源代碼
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<string> #include<cstdlib> #include<queue> #include<set> #include<map> #include<stack> #include<vector> #define INF 0x3f3f3f3f #define PI acos(-1.0) #define N 21 #define MOD 123 #define E 1e-6 using namespace std; int n,sum; int triangle[N][N]; int a[N],vis[N]; bool flag; void dfs(int step,int cnt) {if(flag)return;if(cnt>sum)//當前和大于sum,剪枝return;if(step==n+1&&cnt==sum)//達到最后一層并找到答案{flag=true;for(int i=1;i<=n;i++)cout<<a[i]<<" ";}for(int i=1;i<=n;i++)if(!vis[i]){a[step]=i;vis[i]=1;cnt+=triangle[n][step]*a[step];//加上i*系數dfs(step+1,cnt);cnt-=triangle[n][step]*a[step];//減去i*系數vis[i]=0;} } int main() {cin>>n>>sum;/*構造存儲答案系數的楊輝三角*/triangle[1][1]=1;for(int i=2;i<=n;i++)for(int j=1;j<=i;j++)triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j];dfs(1,0);//從1開始搜索return 0; }?
總結
以上是生活随笔為你收集整理的数字三角形(洛谷-P1118)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 除以13(信息学奥赛一本通-T1175)
- 下一篇: 约数研究(洛谷-P1403)