deque 的插入操作不一定有 vector 快
#include <iostream> #include <cstring> #include <fstream> #include <vector> using namespace std; #define NOT_SELECTED 0 #define SELECTED 1 #define SIZE 6001 vector< int > relations[SIZE]; bool visited[SIZE]; int DP[SIZE][2]; int farents[SIZE]; void dfs( int node ){ if( visited[node] ) return; visited[node] = true; for( int i = 0; i < relations[node].size(); ++i ){ int next = relations[node][i]; if( !visited[next] ){ dfs( next ); DP[node][NOT_SELECTED] += max( DP[next][NOT_SELECTED], DP[next][SELECTED] ); DP[node][SELECTED] += DP[next][NOT_SELECTED]; } } } int main(){ int employees_num; int supervisor, employee; int ans = 0; while( cin >> employees_num ){ memset( visited, false, sizeof( visited ) ); memset( DP, 0, sizeof( DP ) ); memset( farents, 0, sizeof( farents ) ); for ( int i = 1; i <= employees_num; ++i ){ cin >> DP[i][SELECTED]; relations[i].clear(); } while( true ){ cin >> employee >> supervisor; if( employee == 0 && supervisor == 0 ) break; farents[employee] = supervisor; relations[supervisor].push_back( employee ); } for( int i = 1; i <= employees_num; ++i ){ if( farents[i] == 0 ){ dfs( i ); int new_ans = max( DP[i][NOT_SELECTED], DP[i][SELECTED] ); ans = max( ans, new_ans ); } } cout << ans << endl; } return 0; }
POJ 2342 Anniversary Party ( 树形DP )
原文地址:http://blog.csdn.net/pandora_madara/article/details/43878415