【cf1204E】E. Natasha, Sasha and the Prefix Sums (组合数学+dp)

传送门

题意:
现有\(n\)\(1\)\(m\)\(-1,n,m\leq 2000\),要由这些数组成一个序列,定义\[\displaystyle f(a)=max(0,max_{1\leq i\leq n+m}\sum_{j=1}^ia_j)\]

\(f(a)\)为序列\(a\)的所有前缀和的最大值。
最终询问所有可能的序列的\(f(a)\)之和为多少。

思路:

  • 注意到我们需要求的是前缀的和。根据这一点可以发现,如果当前序列\(f(a)=x\),那么在最前面加上一个\(1\),此时\(f(a')=x+1\);加上一个\(-1\),此时\(f(a')=max(0,x-1)\)
  • 以上是一个很重要的观察,那么我们就可以据此来进行\(dp\)
  • 定义\(dp_{x,y}\)表示现在有\(x\)\(1\)\(y\)\(-1\)的答案。那么转移式就有:

\[ dp_{x,y}=dp_{x-1,y}+{x-1+y\choose y}+dp_{x,y-1}-({x+y-1\choose x}-f_{x,y-1}) \]
其中\(f_{x,y}\)表示当有\(x\)\(1\)\(y\)\(-1\)时,\(f(a)=0\)的序列数。这个就相当于对于任意一个前缀,\(1\)的个数不会超过\(-1\),那么可以直接根据卡特兰数的公式来进行计算。
代码很好写,解决这个问题的关键就是把握住“前缀和”这个概念,与常规\(dp\)不同的是,这时我们选择从前面进行插入。
代码如下:

/*
 * Author:  heyuhhh
 * Created Time:  2020/3/14 15:52:51
 */
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#include <iomanip>
#include <assert.h>
#define MP make_pair
#define fi first
#define se second
#define pb push_back
#define sz(x) (int)(x).size()
#define all(x) (x).begin(), (x).end()
#define INF 0x3f3f3f3f
#define Local
#ifdef Local
  #define dbg(args...) do { cout << #args << " -> "; err(args); } while (0)
  void err() { std::cout << '\n'; }
  template<typename T, typename...Args>
  void err(T a, Args...args) { std::cout << a << ' '; err(args...); }
  template <template<typename...> class T, typename t, typename... A> 
  void err(const T <t> &arg, const A&... args) {
  for (auto &v : arg) std::cout << v << ' '; err(args...); }
#else
  #define dbg(...)
#endif
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
//head
const int N = 4000 + 5, MOD = 998244853;

int C[N][N];
void init() {
    C[0][0] = 1;
    for(int i = 1; i < N; i++) {
        C[i][0] = 1;
        for(int j = 1; j <= i; j++) {
            C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % MOD;   
        }
    }
}

int n, m;
int f[N][N], g[N][N];

void run() {
    cin >> n >> m;
    for(int i = 1; i <= n; i++) {
        f[0][i] = 1;
        for(int j = i; j <= m; j++) {
            f[i][j] = (C[i + j][i] - C[i + j][i - 1] + MOD) % MOD;
        }   
    }
    for(int i = 1; i <= n; i++) g[i][0] = i;
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= m; j++) {
            g[i][j] = (g[i - 1][j] + C[i + j - 1][j]) % MOD + ((g[i][j - 1] - (C[i + j - 1][j - 1] - f[i][j - 1])) % MOD + MOD) % MOD;
            g[i][j] %= MOD;
        }   
    }
    cout << g[n][m] << '\n';
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cout << fixed << setprecision(20);
    init();
    run();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/heyuhhh/p/12507040.html