牛客 [NOIP2001]数的划分

https://ac.nowcoder.com/acm/problem/16695

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const LL MAXN=1e18,MINN=-MAXN,INF=0x3f3f3f3f;
const LL N=200200,M=2020;
LL n,k;
LL ans=0;
void dfs(int idx,int len,int sum)
{
    if((k-len)*idx>n-sum) return ;
    if(len>=k||sum>=n)
    {
        if(len==k&&sum==n) ans++;
        return ;
    }
    for(int i=idx;i<=n;i++)
    {
        if((k-len)*i>n-sum) break ;
        dfs(i,len+1,sum+i);
    }
}
int main()
{
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    LL T=1;
    //cin>>T;
    while(T--)
    {
        cin>>n>>k;
        for(int i=1;i<=n;i++)
        {
            if(k*i>n) break;
            dfs(i,1,i);//从i开始,长度为i,总数为i
        }
        cout<<ans<<endl;
    }
    return 0;
}

方法二

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
const LL MAXN=1e18,MINN=-MAXN,INF=0x3f3f3f3f;
const LL N=100200,M=2020;
LL n,k;
LL ans=0;
void dfs(int idx,int sum,int len)
{
    if(len==1)//因为最开始就填了一个1进去,所以只需要到回退到1个的时候就好了
    {
        ans++;
        return ;
    }
    for(int i=idx;i<=sum/len;i++)//因为要保证是递增的,所以最大值是除数
    {
        dfs(i,sum-i,len-1);
    }
}
int main()
{
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    LL T=1;
    //cin>>T;
    while(T--)
    {
        cin>>n>>k;
        dfs(1,n,k);
        cout<<ans<<endl;
    }
    return 0;
}
posted @ 2024-03-29 15:44  高尔赛凡尔娟  阅读(5)  评论(0编辑  收藏  举报