樹型dp poj1192

來源:互聯網
上載者:User

簡單樹型dp。

題目好羅嗦。。一棵樹找最大權值和子樹 可以是中間子樹 。算出最大權值

dfs 一下 搞掂!!

麥當勞最愛板燒哈哈哈 ~

#include <iostream>#include <string.h>#include <vector>#include <cstdlib>  //abs() 自己寫宏好容易寫錯  要加好多好多括弧- -外面一個大括弧沒加 wa到死#define Max(a,b) (a)>(b)?(a):(b)using namespace std;const int MAXN=1010;bool v[MAXN];int dp[MAXN][2],N;vector<int> node[MAXN];struct point{int x,y,w;}pp[MAXN];void dfs(int rt){v[rt]=1;int i,j;int sz=node[rt].size();dp[rt][0]=0;   //rt自己不算上dp[rt][1]=pp[rt].w; //rt自己算上 for (i = 0; i < sz; i++) {j=node[rt][i];if(v[j])  continue;dfs(j);dp[rt][0]=Max(dp[rt][0],Max(dp[j][0],dp[j][1])); //找一個權值最大子樹dp[rt][1]=Max(dp[rt][1],dp[rt][1]+dp[j][1]); //加上自己的權值 就算沒有加上子樹的 也要有這個值 因為雙親會用到 }}void judge(int a,int b){int dis=(abs(pp[a].x-pp[b].x)+abs(pp[a].y-pp[b].y));if(dis==1){node[a].push_back(b);node[b].push_back(a);}return;}int main(void){while(cin>>N){memset(v,0,sizeof(v));int i,j,k;for (i = 0; i < N; i++) {cin>>pp[i].x>>pp[i].y>>pp[i].w;node[i].clear();}memset(dp,0,sizeof(dp));for (i = 0; i < N; i++) {for (j = i+1; j < N; j++) {judge(i,j);}}dfs(0);int ans=Max(dp[0][0],dp[0][1]);cout<<ans<<endl;}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.