2060: [Usaco2010 Nov]Visiting Cows 拜访奶牛
Time Limit: 3 Sec Memory Limit: 64 MBSubmit: 335 Solved: 244
[ Submit][ Status][ Discuss]
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}.
解题思路:简单的树形DP。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
int n,len;
int to[100005],next[100005];
int h[100005];
int f[2][100005];
inline int read()
{
char y;int x=0,f=1; y=getchar();
while (y<'0' || y>'9') {if (y=='-') f=-1; y=getchar();}
while (y>='0' && y<='9') {x=x*10+int(y)-48; y=getchar();}
return x*f;
}
void insert(int x,int y)
{
++len; to[len]=y; next[len]=h[x]; h[x]=len;
}
void dfs(int o,int fa)
{
f[1][o]=1; f[0][o]=0;
int u=h[o];
while (u!=0)
{
if (to[u]!=fa)
{
dfs(to[u],o);
f[1][o]+=f[0][to[u]];
f[0][o]+=max(f[1][to[u]],f[0][to[u]]);
}
u=next[u];
}
}
int main()
{
n=read();
for (int i=1;i<=n-1;++i)
{
int x,y; x=read(); y=read();
insert(x,y); insert(y,x);
}
memset(f,-0x7f,sizeof(f));
dfs(1,0);
printf("%d",max(f[1][1],f[0][1]));
}