洛谷(P4933 大师)DP

在这里插入图片描述

先练他几十道DP,就不信还不会
题意:大体就是求等差子序列的个数(公差可以为负)
定义 d[i][j] 表示以 i 结尾且公差为 j(j>=0) 的子序列的个数
定义 f[i][j] 表示以 i 结尾且公差为 j(j<0) 的子序列的个数
有了状态表示状态转移就很明显了
代码:

#include <bits/stdc++.h>
#define ll long long
#define IOS std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
template<class T> inline void read(T &x){
    
    
    x=0; register char c=getchar(); register bool f=0;
    while(!isdigit(c))f^=c=='-',c=getchar();
    while(isdigit(c))x=x*10+c-'0',c=getchar(); if(f)x=-x;
}
using namespace std;

ll a[2005];
ll mod=998244353;
ll d[1005][20004];
ll f[1005][20004];
int visz[20004];
int visf[20004];

int main()
{
    
    
    ll n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
    
    cin>>a[i];}
    ll ans=n;
    queue<ll> q;
    for(int i=1;i<=n;i++)
    {
    
    
        for(int j=i-1;j>=1;j--)
        {
    
    
            ll op=a[i]-a[j];
            if(op>=0)
            {
    
    
                d[i][op]=(d[i][op]+d[j][op]+1)%mod;
                if(visz[op]==0)
                {
    
    
                    q.push(op);
                    visz[op]=1;
                }
            }
            else
            {
    
    
                f[i][-op]=(f[i][-op]+f[j][-op]+1)%mod;
                if(visf[-op]==0)
                {
    
    
                    q.push(op);
                    visf[-op]=1;
                }
            }
        }
        while(!q.empty())
        {
    
    
            ll u=q.front();
            q.pop();
            if(u>=0)
            {
    
    
                visz[u]=0;
                ans=(ans+d[i][u])%mod;
            }
            else
            {
    
    
                visf[-u]=0;
                ans=(ans+f[i][-u])%mod;
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43781431/article/details/108063310
今日推荐