这个是我做出来的第一道树形DP,是把DFS与DP的简单结合。
思路:这个题默认就只有一个根结点,就先找到这个根结合,然后从根结点从上往下进行深
度遍历,然后在回塑的时候由最底层往上一步一步地DP就行了。
#include<iostream>
#include<vector>
using namespace std;
#define N 6666
#define inf -1000000000
int n;
int father[N];
int v[N];
vector<int> son[N];
int d[N][2];
void dfs(int k)
{
int i,j;
//cout<<k<<' ';
for (vector<int>::size_type it=0;it<son[k].size();it++)
{
dfs(son[k][it]);
}
i=0,j=0;
for (vector<int>::size_type it=0;it<son[k].size();it++)
{
i+=max(0,max(d[son[k][it]][0],d[son[k][it]][1]));
j+=max(0,d[son[k][it]][0]);
}
d[k][0]=i;
d[k][1]=j+v[k];
}
int main()
{
///freopen("C:\in.txt","r",stdin);
int i,j,k;
cin>>n;
for (i=1;i<=n;i++)
cin>>v[i];
for (i=0;i<=n;i++)
father[i]=i,son[i].clear();
while(true)
{
int a,b;
cin>>a>>b;
if (a==0&&b==0)
break;
father[a]=b;
son[b].insert(son[b].end(),a);
}
memset(d,0,sizeof(d));
for (i=1;i<=n;i++) if (father[i]==i)
{
dfs(i);
break;
}
cout<<max(d[i][1],d[i][0])<<endl;
return 1;
}
Anniversary party
| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 3015 | Accepted: 1665 |
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.
Input
Employees are numbered from 1 to N. A first line of input contains a number N. 1 <= N <= 6 000. 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 go N – 1 lines that describe a supervisor relation tree. Each line of the tree specification has the form:
L K
It means that the K-th employee is an immediate supervisor of the L-th employee. Input is ended with the line
0 0
L K
It means that the K-th employee is an immediate supervisor of the L-th employee. Input is ended with the line
0 0
Output
Output should contain the maximal sum of guests' ratings.
Sample Input
7 1 1 1 1 1 1 1 1 3 2 3 6 4 7 4 4 5 3 5 0 0
Sample Output
5
Source

本文介绍了一个将深度优先搜索(DFS)与动态规划(DP)相结合的算法,用于解决特定类型的问题。通过从根节点开始的深度遍历,算法逐步计算并更新每个节点的状态,最终得到最优解。
Anniversary party P2342&spm=1001.2101.3001.5002&articleId=8193154&d=1&t=3&u=02a99ec1a3884e128c73b766a4e5842b)
574

被折叠的 条评论
为什么被折叠?



