hdu 5136(dp計數),hdu5136dp計數

來源:互聯網
上載者:User

hdu 5136(dp計數),hdu5136dp計數

題目連結


題意:直徑為K的每個點的邊數不超過3的相互不同構的樹有多少種?


解法:把樹的直徑拉開,兩邊就是兩棵二叉樹了。子問題:一個深度為m的不同構的二叉樹有多少種?dp[i]表示深度為i的個數。sum[i]表示dp的首碼和。轉移方程就是:dp[i+1]=dp[i]*sum[i-1]+dp[i]+dp[i]*(dp[i]-1)/2;

然後回到原問題:如果K是偶數(想象中間有個虛擬不動點),則兩邊是兩棵深度為K/2的二叉樹,答案為:dp[i]*(dp[i]-1)/2+dp[i]

如果K為奇數,則中間還有一個節點:他也是顆二叉樹,則分兩種大情況:

                               第三個二叉樹的深度小於K/2,則sum[K/2-1]*(dp[K/2]*(dp[K/2]-1)/2+dp[K/2])即可;

                               第三個二叉樹的深度等於K/2,則分三類討論:1 三棵二叉樹結構一樣dp[K/2] 2 兩棵一樣,2 另一棵不一樣:dp[K/2]*(dp[K/2]-1) 3 三棵都不一樣:dp[K/2]*(dp[K/2]-1)*(dp[K/2]-2)/6


代碼:

/******************************************************* @author:xiefubao*******************************************************/#pragma comment(linker, "/STACK:102400000,102400000")#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <queue>#include <vector>#include <algorithm>#include <cmath>#include <map>#include <set>#include <stack>#include <string.h>//freopen ("in.txt" , "r" , stdin);using namespace std;#define eps 1e-8#define zero(_) (abs(_)<=eps)const double pi=acos(-1.0);typedef long long LL;const int Max=100010;const LL INF=1000000007;LL ans[Max];LL sum[Max];LL powa(LL t,LL p){    LL ans=1;    while(p)    {        if(p&1)            ans=(ans*t)%INF;        t=(t*t)%INF;        p>>=1;    }    return ans;}LL getreverse(LL t){    return powa(t,INF-2)%INF;}LL getans(int t){    int l=t/2;    LL rem=((ans[l]*((ans[l]-1+INF)%INF)%INF*getreverse((LL)2))%INF+ans[l])%INF;    //cout<<ans[l]<<" "<<rem<<endl;    if(t&1)    {        rem=(rem*sum[l-1])%INF;        rem=(rem+ans[l])%INF;        rem=(rem+ans[l]*(ans[l]-1)%INF)%INF;        rem=(rem+ans[l]*((ans[l]-1+INF)%INF)%INF*((ans[l]-2+INF)%INF)%INF*getreverse(6)%INF)%INF;        return rem;    }    else    {        return rem;    }}LL geter(int t){    return (ans[t-1]*sum[t-2]%INF+ans[t-1]*((ans[t-1]-1+INF)%INF)%INF*getreverse(2)%INF+ans[t-1])%INF;}void init(){    ans[0]=1;    ans[1]=1;    ans[2]=2;    sum[0]=1;    sum[1]=2;    sum[2]=4;    for(int i=3; i<Max; i++)    {        ans[i]=geter(i);        sum[i]=(sum[i-1]+ans[i])%INF;    }}int main(){    init();    int n;    while(cin>>n&&n)    {        cout<<getans(n)<<endl;    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.