思路:问能住几个晚上,每个晚上住的地方都是不相邻的,最大独立集问题。dp[i][0/1]表示以i为根节点并且不选/选这个点的最大值。如题i节点如果选了那么下个节点必定不能选
如果i不选那么子节点可选可不选&preview=true)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
//#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=100000000;
const int N=2e6+10;
const int M=1e3+10;
const int inf=0x7f7f7f7f;
const int maxx=2e5+7;
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
ll lcm(ll a,ll b)
{
return a*(b/gcd(a,b));
}
template <class T>
void read(T &x)
{
char c;
bool op = 0;
while(c = getchar(), c < '0' || c > '9')
if(c == '-')
op = 1;
x = c - '0';
while(c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
if(op)
x = -x;
}
template <class T>
void write(T x)
{
if(x < 0)
x = -x, putchar('-');
if(x >= 10)
write(x / 10);
putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
ll res=1%p;
while(b)
{
if(b&1) res=res*a%p;
a=1ll*a*a%p;
b>>=1;
}
return res;
}
struct node
{
int to,nex;
}edge[N];
int siz[N],head[N],tot;
int dp[N][2];
void add(int u,int v)
{
edge[++tot].to=v;
edge[tot].nex=head[u];
head[u]=tot;
}
void dfs(int u,int fa)
{
dp[u][1]=1;
for(int i=head[u];i!=0;i=edge[i].nex)
{
int v=edge[i].to;
if(v==fa)continue;
dfs(v,u);
dp[u][0]+=max(dp[v][1],dp[v][0]);
dp[u][1]+=dp[v][0];
}
}
int main()
{
SIS;
int n,k;
cin>>n>>k;
// memset(head,-1,sizeof head);
for(int i=1;i<=n-1;i++)
{
int u,v;
cin>>u>>v;
add(u,v);
add(v,u);
}
dfs(k,-1);
cout<<dp[k][1]<<endl;
return 0;
}

京公网安备 11010502036488号