Ural 1039 Anniversary Party

时间:2022-06-22 22:35:32

题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1039

Dynamic Programming. 建立树形结构,每个employee有两个选择,去或者不去。supervisor的选择影响着sub-tree的选择。代码如下:

 #include <iostream>
#include <math.h>
#include <stdio.h>
#include <cstdio>
#include <algorithm>
#include <string.h>
#include <string>
#include <sstream>
#include <cstring>
#include <queue>
#include <vector>
#include <functional>
#include <cmath>
#include <set>
#define SCF(a) scanf("%d", &a)
#define IN(a) cin>>a
#define FOR(i, a, b) for(int i=a;i<b;i++)
#define Infinity 9999999
typedef long long Int;
using namespace std; struct tree {
int parent;
vector<int> children;
int size = ;
};
int N;
tree * trees[];
int dp[][]; //i -> employee id, j -> attend 1 or not 0
int conviviality[]; int calcuTree(int parent, int choice) //choice 1: attend or not, choice 0: cannot atted
{
if (dp[parent][choice] != Infinity)
return dp[parent][choice]; int maxCon = ;
int maxConDGo = ;
int maxConGo = conviviality[parent];
//this employee don't go, its child has 2 choices
for (int i = ; i < trees[parent]->size; i++)
{
int child = trees[parent]->children[i];
if (dp[child][] == Infinity)
dp[child][] = calcuTree(child, );
if (dp[child][] == Infinity)
dp[child][] = calcuTree(child, );
maxConDGo += max(dp[child][], dp[child][]);
} //this employee go, its child has only one choice.
for (int i = ; i < trees[parent]->size; i++)
{
int child = trees[parent]->children[i];
if (dp[child][] == Infinity)
dp[child][] = calcuTree(child, );
maxConGo += dp[child][];
} if (choice == )
maxCon = max(maxConGo, maxConDGo);
else
maxCon = maxConDGo; return maxCon;
} int main()
{
while (SCF(N) != EOF)
{
FOR(i, , N + )
SCF(conviviality[i]);
int L, K;
int index = ;
FOR(i, , N + )
{
trees[i] = new tree;
trees[i]->parent = i;
} bool *root = new bool[N + ];
FOR(i, , N + )
root[i] = true; while (scanf("%d %d", &L, &K))
{
if (L == && K == )
break;
trees[K]->children.push_back(L);
trees[K]->size += ;
root[L] = false;
} FOR(i, , N + )
{
dp[i][] = dp[i][] = Infinity;
} int president = ;
FOR(i, , N + )
{
if (root[i])
{
president = i;
break;
}
} FOR(i, , N + )
{
dp[i][] = calcuTree(i, );
dp[i][] = calcuTree(i, );
} int maxAns = max(dp[president][], dp[president][]);
printf("%d\n", maxAns);
}
return ;
}