牛客假日团队赛19(树形dp)
链接:https://ac.nowcoder.com/acm/contest/1126/A
来源:牛客网
After many weeks of hard work, Bessie is finally getting a vacation! After many weeks of hard work, Bessie is finally getting a vacation! numbered 1…N. The cows have set up quite an unusual road network with exactly N-1 roads connecting pairs of cows C1 and C2 (1 <= C1 <= N; 1 <= C2 <= N; C1 != C2) in such a way that there exists a unique path of roads between any two cows.
FJ wants Bessie to come back to the farm soon; thus, he has instructed Bessie that if two cows are directly connected by a road, she may not visit them both. Of course, Bessie would like her vacation to be as long as possible, so she would like to determine the maximum number of cows she can visit.
输入描述:
- Line 1: A single integer: N
- Lines 2…N: Each line describes a single road with two space-separated integers: C1 and C2
输出描述: - Line 1: A single integer representing the maximum number of cows that Bessie can visit.
示例1
输入
复制
7
6 2
3 4
2 3
1 2
7 6
5 6
输出
复制
4
说明
Bessie knows 7 cows. Cows 6 and 2 are directly connected by a road, as are cows 3 and 4, cows 2 and 3, etc.
Bessie can visit four cows. The best combinations include two cows on the top row and two on the bottom. She can’t visit cow 6 since that would preclude visiting cows 5 and 7; thus she visits 5 and 7. She can also visit two cows on the top row: {1,3}, {1,4}, or {2,4}.
题目大意:
建一棵树,相邻层数上的节点不能同时选取,要求最多可以选取多少个节点。
树形dp板子题,第一次读错题用并查集搞了一波,wa了,问了巨神taorist才知道是一道树形dp简单学了皮毛之后过了。
建立树的过程中,标记每个节点是否有父节点,遍历一遍找到没有父节点的一个节点为根节点,以该根节点开始递归,每个节点两个状态,f[x][1](x为该节点)为选取该节点,f[x][0]为不选。f[x][0],此时该节点的下一层节点可以选取也可以不选取,f[x][1],此时该节点下一层节点不可以选取。时间复杂度o(n)。
#include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;
const int N=1e5;
vector<int>son[N];
int f[N][2],v[N],n;
void dp(int x)
{
f[x][0]=0;
f[x][1]=1;
for(int i=0; i<son[x].size(); ++i)
{
int y=son[x][i];
dp(y);
f[x][0]+=max(f[y][0],f[y][1]);
f[x][1]+=f[y][0];
}
}
int main()
{
scanf("%d",&n);
for(int i=1; i<n; ++i)
{
int x,y;
scanf("%d %d",&x,&y);
v[x]=1;
son[y].push_back(x);
}
int root;
for(int i=1; i<=n; ++i)
{
if(v[i]==0)
{
root=i;
break;
}
}
dp(root);
printf("%d\n",max(f[root][0],f[root][1]));
return 0;
}