您的位置:首页 > 其它

poj 1192 树形dp

2014-02-23 10:38 246 查看
好久没刷过树形dp了,都快忘记了

dp【n】【0】表示不含有节点n时的最大权值和

dp【n】【1】表示含有节点n时的最大权值和

AC代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;

#define MAX 0x3f3f3f3f

struct Edge{
int to, next;
};

struct Point{
int x, y;
int value;
};

int head[1100], tot;
Edge edge[2200];
Point point[1100];
int N;
int dp[1100][2];
bool mark[1100];

int add_adge( int a, int b ){
edge[tot].to = b;
edge[tot].next = head[a];
head[a] = tot++;
edge[tot].to = a;
edge[tot].next = head[b];
head[b] = tot++;
return 0;
}

int DFS( int pre, int pos ){
mark[pos] = true;
dp[pos][0] = 0;
for( int i = head[pos]; i != -1; i = edge[i].next ){
int to = edge[i].to;
if( to == pre ){
continue;
}
if( !mark[to] ){
DFS( pos, to );
}
dp[pos][0] = max( dp[pos][0], dp[to][0] );
dp[pos][0] = max( dp[pos][0], dp[to][1] );
}
dp[pos][1] = point[pos].value;
for( int i = head[pos]; i != -1; i = edge[i].next ){
int to = edge[i].to;
if( to == pre ){
continue;
}
if( !mark[to] ){
DFS( pos, to );
}
dp[pos][1] += max( 0, dp[to][1] );
}

return 0;
}

int main()
{
while( scanf( "%d", &N ) != EOF ){

tot = 0;
memset( head, -1, sizeof( head ) );

for( int i = 0; i < N; i++ ){
cin >> point[i].x >> point[i].y >> point[i].value;
}

for( int i = 0; i < N; i++ ){
for( int j = i + 1; j < N; j++ ){
if( abs( point[i].x - point[j].x ) + abs( point[i].y - point[j].y ) == 1 ){
add_adge( i, j );
}
}
}

for( int i = 0; i < N; i++ ){
for( int j = 0; j < 2; j++ ){
dp[i][j] = -MAX;
}
}

memset( mark, false, sizeof( mark ) );
DFS( -1, 0 );
int ans = -MAX;
for( int i = 0; i < N; i++ ){
ans = max( ans, dp[i][1] );
ans = max( ans, dp[i][0] );
}
cout << ans << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: