自学内容网 自学内容网

【洛谷】AT_dp_m Candies 的题解

【洛谷】AT_dp_m Candies 的题解

洛谷传送门

AT 传送门

题解

显然是一个 dp

首先暴力枚举的话经过用会 TLE 的,发现公式里每个 dp 值都由上一行中一段连续的 dp 值之和转移而来,可以前缀和优化转移,每次用 s u m sum sum 数组预处理上一行 dp 的前缀和,可以 O ( 1 ) O(1) O(1) 地求出连续一段 dp 值之和并转移。

代码

#include <bits/stdc++.h>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int mod = 1e9 + 7;
namespace fastIO {
inline int read() {
register int x = 0, f = 1;
register char c = getchar();
while (c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
inline void write(int x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
}
using namespace fastIO;
int n, k, a[105];
ll dp[100005], ans[100005];
int main() {
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
n = read(), k = read();
for(int i = 1; i <= n; i ++) {
a[i] = read();
}
dp[0] = 1;
for(int i = 1; i <= n; i ++) {
ans[0] = dp[0];
for(int j = 1; j <= k; j ++) {
ans[j] = (ans[j - 1] + dp[j]) % mod;
}
for(int j = 0; j <= k; j ++) {
dp[j] = ((ans[j] - (j <= a[i] ? 0 : ans[j - a[i] - 1])) % mod + mod) % mod;
}
}
cout << dp[k] << endl;
return 0;
}

原文地址:https://blog.csdn.net/ZH_qaq/article/details/142695461

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!