二维DP
列题1,摆花代码
2 4 3 2 =>2(最终的结果) #include<bits/stdc++.h> using namespace std; using ll = long long; const int N = 105; const ll p = 1e6 + 7; ll a[N], dp[N][N]; int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); int n, m; cin >> n >> m; for (int i = 1; i <= n; ++i)cin >> a[i]; dp[0][0] = 1; for (int i = 1; i <= n; ++i){ for (int j = 0; j <= m; ++j){ for (int k = 0; k <= a[i] && k <= j; ++k) dp[i][j] = (dp[i][j] + dp[i - 1][j-k]) % p; } } cout << dp[n][m]<<"\n"; return 0; }
选数异或
#include<bits/stdc++.h> using namespace std; using ll = long long; const int N = 1e5; const ll p = 998244353; ll a[N], dp[N][70]; int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); int n, x; cin >> n >> x; for (int i = 1; i <= n; ++i)cin >> a[i]; dp[0][0] = 1; for (int i = 1; i <= n; ++i){ for (int j = 0; j < 64; ++j){ dp[i][j] = (dp[i - 1][j] + dp[i - 1][j^a[i]]) % p; } } cout << dp[n][x] << "\n"; return 0; }
利用二维解数字三角形
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 =>27 #include<bits/stdc++.h> using namespace std; using ll = long long; const int N = 150; ll dp[N][N][N],a[N][N]; int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); int n; cin >> n; for (int i = 1; i <= n; i++){ for (int j = 1; j <= i; j++){ cin >> a[i][j]; } } for (int i = n; i >= 1; --i){ for (int j = 1; j <= i; ++j){ for (int k = 0; k <= n-i; ++k){ if (k >= 1)dp[i][j][k] = a[i][j] + max(dp[i + 1][j][k], dp[i + 1][j + 1][k - 1]); else dp[i][j][k] = a[i][j] + dp[i + 1][j][k]; } } } if (n & 1)cout << dp[1][1][(n - 1) / 2]; else cout << dp[1][1][(n - 1) / 2], dp[1][1][n - 1 - (n - 1) / 2]; return 0; }