平衡二叉樹(DP)

在這裏插入圖片描述

思路:根據題意我們讓左子樹爲高度n的滿二叉樹,右子樹上的點儘可能少,那麼我們首先吧他的高度拉滿使其爲n-m-1,此時我們在右子樹的左子樹上高度拉滿點最少,可得方程dp[i]=dp[i-1]+dp[i-m-1]。dp[i]表示高度爲i的右子樹的最少點。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
//#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=1e4+7;
const int N=2e5+10;
const int inf=0x7f7f7f7f;


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 dp[N];
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    dp[1]=1;
    for(int i=2;i<=n;i++)
    {
        dp[i]=dp[i-1]+1;
        if(i>m)
        {
            dp[i]+=dp[i-m-1];
        }
    }
   ll ans=(1ll<<(n-1))-1-dp[n-m-1];
    cout<<ans<<endl;
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章