1. 程式人生 > >洛谷 P1352 沒有上司的舞會【樹形DP】

洛谷 P1352 沒有上司的舞會【樹形DP】

open define 樹形dp for bitset air stdin begin algorithm

題目描述
某大學有N個職員,編號為1~N。他們之間有從屬關系,也就是說他們的關系就像一棵以校長為根的樹,父結點就是子結點的直接上司。現在有個周年慶宴會,宴會每邀請來一個職員都會增加一定的快樂指數Ri,但是呢,如果某個職員的上司來參加舞會了,那麽這個職員就無論如何也不肯來參加舞會了。所以,請你編程計算,邀請哪些職員可以使快樂指數最大,求最大的快樂指數。

輸入輸出格式
輸入格式:
第一行一個整數N。(1<=N<=6000)

接下來N行,第i+1行表示i號職員的快樂指數Ri。(-128<=Ri<=127)

接下來N-1行,每行輸入一對整數L,K。表示K是L的直接上司。

最後一行輸入0 0

輸出格式:
輸出最大的快樂指數。

#include<cstdio>
#include<string>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<cstring>
#include<set>
#include<queue>
#include<algorithm>
#include<vector>
#include<map>
#include<cctype>
#include<stack>
#include<sstream>
#include<list>
#include<assert.h>
#include<bitset>
#include<numeric>
#define debug() puts("++++")
#define gcd(a,b) __gcd(a,b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define fi first
#define se second
#define pb push_back
#define sqr(x) ((x)*(x))
#define ms(a,b) memset(a,b,sizeof(a))
#define sz size()
#define be begin()
#define pu push_up
#define pd push_down
#define cl clear()
#define lowbit(x) -x&x
#define all 1,n,1
#define rep(i,x,n) for(int i=(x); i<=(n); i++)
#define in freopen("in.in","r",stdin)
#define out freopen("out.out","w",stdout)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e18;
const int maxn = 1e5 + 20;
const int maxm = 1e6 + 10;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int dx[] = {-1,1,0,0,1,1,-1,-1};
const int dy[] = {0,0,1,-1,1,-1,1,-1};
int dir[4][2] = {{0,1},{0,-1},{-1,0},{1,0}};
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int mod = 10056;
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
int h[maxn];
int v[maxn];
int n;
vector<int> son[maxn];
int f[maxn][2];
void dfs(int x)
{
    f[x][0]=0;
    f[x][1]=h[x];
    for(int i=0;i<son[x].size();i++)
    {
        int y=son[x][i];
        dfs(y);
        f[x][0]+=max(f[y][0],f[y][1]);
        f[x][1]+=f[y][0];
    }
}
int main()
{
   cin>>n;
   rep(i,1,n) cin>>h[i];
   rep(i,1,n-1)
   {
       int x,y;
       cin>>x>>y;
       son[y].push_back(x);
       v[x]=1;
   }
   int root;
   rep(i,1,n)
   {
       if(!v[i])
       {
           root=i;
           break;
       }
   }
   dfs(root);
   cout<<max(f[root][0],f[root][1])<<endl;
}

洛谷 P1352 沒有上司的舞會【樹形DP】