洛谷 P1922 女仆咖啡厅桌游吧(树形DP)

发布时间 2023-03-30 11:41:01作者: 高尔赛凡尔娟

https://www.luogu.com.cn/problem/P1922
标注的是个树形dp,其实就是个简单的dfs+dp

输入 #1
5
1 2
2 3
3 4
2 5
输出 #1
2

读题时间>构思时间+码代码时间(菜鸡日常

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const LL MAXN=1e18,MINN=-MAXN,INF=0x3f3f3f3f;
const LL N=2e6+10,M=3023;
const LL mod=100000007;
const double PI=3.1415926535;
#define endl '\n'
LL n,d[N],f[N],e[N],ne[N],h[N],w[N],idx;
void add(int a,int b)
{
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
bool check(int x)
{
    if(d[x]==1) return true;
    return false;
}
void dfs(int x,int fa)
{
    int cnt=1;//当前自己也算一个
    for(int i=h[x];i!=-1;i=ne[i])
    {
        int j=e[i];
        if(j==fa) continue;
        dfs(j,x);//继续深搜
        //状态转移方程
        if(check(j)) cnt++;//叶子节点,数量增加
        else f[x]+=f[j];//非叶子节点,父节点数量从底层开始往上增加
    }
    f[x]+=cnt/2;//每一个节点的女仆咖啡厅和桌游吧的数量要相等
    //所以女仆咖啡厅的数量就是一半
}
int main()
{
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    LL T=1;
    //cin>>T;
    while(T--)
    {
        memset(h,-1,sizeof h);
        cin>>n;
        for(int i=1;i<n;i++)
        {
            LL a,b;
            cin>>a>>b;
            add(a,b);//双向边
            add(b,a);
            d[a]++;//入度
            d[b]++;
        }
        dfs(1,-1);
        cout<<f[1]<<endl;
    }
    return 0;
}