题解 | 前缀平方和序列

前缀平方和序列

https://www.nowcoder.com/practice/5a4a7feaa70e45f1ad69ac86f0e4b246

#include <bits/stdc++.h>
using namespace std;
const int N=1e3+10;
const int mod = 1e9+7;
typedef long long ll;
typedef unsigned long long ull;
const ll INF = 1e18;
ll a[N];
ll dp[N][N];
ll pre[N];
ll n,x;
void solve()
{

    cin>>n>>x;



    for(int i=1;i<=n;i++)
    {
        if(i==1)
        {
            for(int j=1;j*j<=x;j++)
            {
                dp[i][j]=1;
            }
        }
        else 
        {
            for(int j=1;j*j<=x;j++)
            {
                pre[j] = (pre[j-1]+dp[i-1][j])%mod;
            }
            for(int j=i;j*j<=x;j++)
            {
                dp[i][j] = pre[j-1];
            }
        }
    }

    ll res = 0;
    for(int i=1;i*i<=x;i++)
    {
        res = (res+dp[n][i])%mod;
    }

    cout<<res<<'\n';


}
    


int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t=1;
    // cin>>t;
    while(t--)
    {
        solve();

    }


    return 0;
}

题解似乎很少像我一样用dp做的,这里提供一种dp做法,dp[i][j]为长度为i ,以sum=j*j作为前缀和,那么不难发现,对于第i个长度,sum=j*j 其实就是i-1长度下,从1到j-1的所有可能的总和,这里可以用前缀和优化复杂度到O(n*sqrt(x));

全部评论

相关推荐

点赞 评论 收藏
分享
一只代码牛:应该不是你的问题,我感觉应该是最近不缺人
我的求职进度条
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务