http://www.lydsy.com/JudgeOnline/problem.php?id=2060
裸的树形dp
d[x][1]表示访问x的数量,d[x][0]表示不访问x的数量
d[x][1]=sum{d[y][0]}, y是儿子
d[x][0]=sum{max(d[y][1], d[y][0])}, y是儿子
然后任意找一个点当做根dfs即可。
答案就是max(d[root][0], d[root][1])
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define for1(i,a,n) for(int i=(a);i<=(n);++i)
#define for2(i,a,n) for(int i=(a);i<(n);++i)
#define for3(i,a,n) for(int i=(a);i>=(n);--i)
#define for4(i,a,n) for(int i=(a);i>(n);--i)
#define CC(i,a) memset(i,a,sizeof(i))
#define read(a) a=getint()
#define print(a) printf("%d", a)
#define dbg(x) cout << (#x) << " = " << (x) << endl
#define printarr2(a, b, c) for1(_, 1, b) { for1(__, 1, c) cout << a[_][__]; cout << endl; }
#define printarr1(a, b) for1(_, 1, b) cout << a[_] << '\t'; cout << endl
inline const int getint() { int r=0, k=1; char c=getchar(); for(; c<'0'||c>'9'; c=getchar()) if(c=='-') k=-1; for(; c>='0'&&c<='9'; c=getchar()) r=r*10+c-'0'; return k*r; }
inline const int max(const int &a, const int &b) { return a>b?a:b; }
inline const int min(const int &a, const int &b) { return a<b?a:b; } const int N=50005;
int ihead[N], cnt, n, d[N][2];
struct ED { int to, next; }e[N<<1];
void add(int u, int v) {
e[++cnt].next=ihead[u]; ihead[u]=cnt; e[cnt].to=v;
e[++cnt].next=ihead[v]; ihead[v]=cnt; e[cnt].to=u;
}
void dfs(int x, int fa) {
int y;
d[x][1]=1;
for(int i=ihead[x]; i; i=e[i].next) if((y=e[i].to)!=fa) {
dfs(y, x);
d[x][1]+=d[y][0];
d[x][0]+=max(d[y][0], d[y][1]);
}
}
int main() {
read(n);
rep(i, n-1) add(getint(), getint());
dfs(1, 0);
print(max(d[1][0], d[1][1]));
return 0;
}
Description
Input
Output
Sample Input
6 2
3 4
2 3
1 2
7 6
5 6
INPUT DETAILS:
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. The illustration below depicts the
roads that connect the cows:
1--2--3--4
|
5--6--7
Sample Output
OUTPUT DETAILS:
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}.