hdu4661 树形DP

这次被虐残了,很好想的树上统计拓扑排序数,比赛的时候找儿子节点循环判断有一个很恶心的错误,一直到比赛结束都没找出来。


ACcode:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int NS=1000001;
const int MOD=1000000007;

struct node{
    int num;
    LL way;
}no[NS];

int n,top;
int head[NS],next[NS<<1],to[NS<<1];
LL ans,fac[NS],facm[NS];

void add(int u,int v)
{
    to[top]=v;
    next[top]=head[u];
    head[u]=top++;
}

LL qpow(LL x,int y)
{
    x%=MOD;
    LL ret=1;
    while (y>0)
    {
        if (y&1) ret*=x,ret%=MOD;
        x*=x,x%=MOD;
        y>>=1;
    }
    return ret;
}

LL cbn(int x,int y)
{
    return (((fac[x]*facm[y])%MOD)*facm[x-y])%MOD;;
}

void dfs(int rt,int pre)
{
    int cnt=0;
    LL ret=1;
    for (int i=head[rt];i!=-1;i=next[i])
    {
        int son=to[i];
        if (son!=pre)
        {
            dfs(son,rt);
            node tmp=no[son];
            cnt+=tmp.num;
            ret=(((ret*cbn(cnt,tmp.num))%MOD)*tmp.way)%MOD;
        }
    }
    no[rt].num=cnt+1,no[rt].way=ret;
}

void dfs2(int rt,int pre)
{
    if (pre>=0)
    {
        LL tmp=(no[pre].way*qpow(cbn(n-1,no[rt].num),MOD-2))%MOD;
        no[rt].way=(tmp*cbn(n-1,n-no[rt].num))%MOD;
    }
    for (int i=head[rt];i!=-1;i=next[i])
    if (to[i]!=pre)
        dfs2(to[i],rt);
    ans+=(no[rt].way*no[rt].way)%MOD;
}

int main()
{
    int T;
    facm[0]=fac[0]=1;
    for (int i=1;i<NS;i++)
    {
        fac[i]=(fac[i-1]*i)%MOD;
        facm[i]=qpow(fac[i],MOD-2);
    }
    for (scanf("%d",&T);T;T--)
    {
        ans=top=0;
        memset(head,-1,sizeof(head));
        scanf("%d",&n);
        for (int i=1;i<n;i++)
        {
            int u,v;
            scanf("%d %d",&u,&v);
            add(u,v),add(v,u);
        }
        dfs(1,-1);
        dfs2(1,-1);
        ans%=MOD;
        printf("%I64d\n",ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值