日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

数字三角形(洛谷-P1118)

發布時間:2025/3/17 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数字三角形(洛谷-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 916

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的排列?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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。