Anniversary party
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11018 Accepted Submission(s): 4567
Problem Description
There is going to be a party to celebrate the 80-th Anniversary of the Ural State University. The University has a hierarchical structure of employees. It means that the supervisor relation forms a tree rooted at the rector V. E. Tretyakov. In order to make the party funny for every one, the rector does not want both an employee and his or her immediate supervisor to be present. The personnel office has evaluated conviviality of each employee, so everyone has some number (rating) attached to him or her. Your task is to make a list of guests with the maximal possible sum of guests’ conviviality ratings.
题解
树形dp的常规入门题:设dp[i][0]表示:当前这个点不选,dp[i][1]表示当前这个点选择的最优解。
转移方程:
dp[cur][0]+=max(dp[son][1],dp[son][0]);//当前这个点不选,那他的孩子可选可不选,取
最大的。
dp[cur][1]+=dp[son][0]//当前这点选择,那他的孩子就不能选择。
代码:
AC代码如下
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cstdio>
using namespace std;
const int N=6001;
int val[N],n,dp[N][2];
vector<int> vec[N];
bool vis[N];
void dfs(int i,int pre)
{
vis[i]=true;
int sum=0,tot=0;
for (int j=0;j<vec[i].size();j++)
{
int temp=vec[i][j];
if (vis[temp]) continue;
dfs(temp,i);
sum+=max(dp[temp][1],dp[temp][0]);
tot+=dp[temp][0];
}
dp[i][0]=sum;
dp[i][1]=val[i]+tot;
}
int main()
{
vec[0].push_back(1);
while (scanf("%d",&n)!=EOF)
{
for (int i=1;i<=n;i++)
{
scanf("%d",val+i);
vec[i].clear();
}
int a,b;
while (true)
{
scanf("%d%d",&a,&b);
if (!a) break;
vec[a].push_back(b);
vec[b].push_back(a);
}
dfs(0,0);
printf("%d\n",dp[0][0]);
memset(vis,false,sizeof(vis));
memset(dp,0,sizeof(dp));
}
return 0;
}
还有一个爆内存的程序,不知道为什么
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<vector>
#include<map>
#include<cmath>
using namespace std;
const int N=6000+10;
int pre[N],dp[N][2],vis[N],n;
vector<int> G[N];
int max(int x,int y)
{
if (x>=y) return x;
else return y;
}
void dfs(int u,int father)
{
int d=G[u].size();
for (int i=0;i<d;i++)
{
int v=G[u][i];
if (v!=father) dfs(v,pre[v]=u);
}
}
void find(int t)
{
vis[t]=1;
for (int i=1;i<=n;i++)
{
if (pre[i]==t&&!vis[i])
{
find(i);
dp[t][0]+=max(dp[i][0],dp[i][1]);
dp[t][1]+=dp[i][0];
}
}
}
int main()
{
int u,v;
while(scanf("%d",&n)!=EOF)
{
memset(dp,0,sizeof(dp));
for (int i=1;i<=n;i++)
scanf("%d",&dp[i][1]);
while(scanf("%d%d",&u,&v)&&(u+v))
{
G[u].push_back(v);
G[v].push_back(u);
}
memset(pre,-1,sizeof(pre));
dfs(1,-1);
memset(vis,0,sizeof(vis));
find(1);
printf("%d\n",max(dp[1][0],dp[1][1]));
}
return 0;
}