Time limit: 0.5 second
Memory limit: 8 MB
Background
The president of the Ural State University is going to make an 80'th Anniversary party. The university has a hierarchical structure of employees; that is, the supervisor relation forms a tree rooted at the president. Employees are numbered by integer numbers in a range from 1 to N, The personnel office has ranked each employee with a conviviality rating. In order to make the party fun for all attendees, the president does not want both an employee and his or her immediate supervisor to attend.
Problem
Your task is to make up a guest list with the maximal conviviality rating of the guests.
Input
The first line of the input contains a number N. 1 ≤ N ≤ 6000.Each of the subsequent N lines contains the conviviality rating of the corresponding employee.Conviviality rating is an integer number in a range from –128 to 127. After that the supervisor relation tree goes.Each line of the tree specification has the formwhich means that the K-th employee is an immediate supervisor of L-th employee. Input is ended with the line0 0
Output
Sample
input | output |
---|---|
7 1 1 1 1 1 1 1 1 3 2 3 6 4 7 4 4 5 3 5 0 0 |
5 |
算是比较基础的树形dp的题吧 ,qwq ,先要寻找根节点 。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std ; 5 const int inf = 1 << 30 , maxn = 6000 + 11 ; 6 int n ,fen[maxn] , f[maxn][2] , head[maxn] , cnt , ru[maxn] ; 7 struct id 8 { 9 int nxt , to ; 10 } edge[maxn] ; 11 12 void add( int u , int v ) 13 { 14 edge[++cnt].to = v , edge[cnt].nxt = head[u] ; 15 head[u] = cnt ; 16 } 17 18 void Init( ) 19 { 20 scanf( "%d" , &n ) ; int l ,k ; 21 for( int x = 1 ; x <= n ; ++x ) scanf( "%d" , fen+x ) ; 22 while( 1 ) 23 { 24 scanf( "%d%d" , &l , &k ) ; 25 if( l == k && k == 0 ) break ; 26 add( k , l ) ; 27 ru[l]++ ; 28 } 29 } 30 31 int dfs( int u , int use ) 32 { 33 if( ~f[u][use] ) return f[u][use] ; 34 int v = 0 ; f[u][use] = 0 ; 35 for( int x = head[u] ; x ; x = edge[x].nxt ) 36 { 37 v = edge[x].to ; 38 if( use == 1 ) f[u][use] += dfs( v , 0 ) ; 39 else 40 { 41 f[u][use] += max( dfs(v , 1) , dfs(v , 0) ) ; 42 } 43 } 44 if( use == 1 ) f[u][use] += fen[u] ; 45 return f[u][use] ; 46 } 47 48 49 void Solve( ) 50 { 51 int ans = 0 ;memset( f , -1 , sizeof(f) ) ; 52 for( int x = 1 ; x <= n ; ++x ) 53 { 54 if( !ru[x] ) 55 { 56 // cout<<x<<endl; 57 ans = max( ans , max( dfs( x , 0 ) , dfs( x , 1 ) ) ) ; 58 } 59 } 60 printf( "%d " , ans ) ; 61 } 62 63 64 int main( ) 65 { 66 Init( ) ; 67 Solve( ) ; 68 return 0 ; 69 }