P1040 加分二叉树【dp+深搜】
生活随笔
收集整理的這篇文章主要介紹了
P1040 加分二叉树【dp+深搜】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
設一個nn個節點的二叉樹tree的中序遍歷為(1,2,3,…,n1,2,3,…,n),其中數字1,2,3,…,n1,2,3,…,n為節點編號。每個節點都有一個分數(均為正整數),記第ii個節點的分數為di,treedi,tree及它的每個子樹都有一個加分,任一棵子樹subtreesubtree(也包含treetree本身)的加分計算方法如下:
subtreesubtree的左子樹的加分× subtreesubtree的右子樹的加分+subtreesubtree的根的分數。
若某個子樹為空,規定其加分為11,葉子的加分就是葉節點本身的分數。不考慮它的空子樹。
試求一棵符合中序遍歷為(1,2,3,…,n1,2,3,…,n)且加分最高的二叉樹treetree。要求輸出;
(1)treetree的最高加分
(2)treetree的前序遍歷
輸入格式
第11行:11個整數n(n<30)n(n<30),為節點個數。
第22行:nn個用空格隔開的整數,為每個節點的分數(分數 <100<100)。
輸出格式
第11行:11個整數,為最高加分(Ans \le 4,000,000,000≤4,000,000,000)。
第22行:nn個用空格隔開的整數,為該樹的前序遍歷。
輸入輸出樣例
輸入 #1 復制
5
5 7 1 2 10
輸出 #1 復制
145
3 1 2 4 5
代碼:
//#pragma GCC optimize(3,"Ofast","inline") #include <cstdio> #include <iostream> #include <algorithm> #include <cmath> #include <cstdlib> #include <cstring> #include <map> #include <stack> #include <queue> #include <vector> #include <bitset> #include <set> #include <utility> #include <sstream> #include <iomanip> using namespace std; typedef long long ll; typedef unsigned long long ull; #define inf 0x3f3f3f3f #define rep(i,l,r) for(int i=l;i<=r;i++) #define lep(i,l,r) for(int i=l;i>=r;i--) #define ms(arr) memset(arr,0,sizeof(arr)) //priority_queue<int,vector<int> ,greater<int> >q; const int maxn = (int)1e5 + 5; const ll mod = 1e9+7; int score[35]; int dp[35][35]; void print(int l,int r) {if(l==r) {printf("%d ",l);return ;}if(l>r) return ;for(int i=l;i<=r;i++) {if(dp[l][r]==dp[l][i-1]*dp[i+1][r]+score[i]) {printf("%d ",i);print(l,i-1);print(i+1,r);return ;}} } int main() {#ifndef ONLINE_JUDGEfreopen("in.txt", "r", stdin);freopen("out.txt", "w", stdout);#endif//ios::sync_with_stdio(0),cin.tie(0);int n;scanf("%d",&n);rep(i,0,n+1) {rep(j,0,n+1) {dp[i][j]=1;}}rep(i,1,n) {scanf("%d",&score[i]);dp[i][i]=score[i];}score[0]=score[n+1]=1;for(int i=n;i>=1;i--) {for(int j=i;j<=n;j++) {for(int k=i;k<=j;k++) {if(dp[i][k-1]==1&&dp[k+1][j]==1) dp[i][j]=max(dp[i][j],score[k]);else dp[i][j]=max(dp[i][j],dp[i][k-1]*dp[k+1][j]+score[k]);}}}printf("%d\n",dp[1][n]);print(1,n);return 0; } 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的P1040 加分二叉树【dp+深搜】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【数学】MORE XOR
- 下一篇: 12-容器之间link