1、摆花
分析:
输入2 4 3 2 的情况下,只有 (2,2) , (3,1) 这两种方案。
所以,设置状态 dp[i][j] 表示到第 i 种花(共 n 种花)、第 j 个位置(共 m 个位置)的情况下的总方案数。
k 表示 第 i 种花使用的数量,a[i] 表示第 i 种花本来的数量。
示例代码:
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const ll p = 1e6+7 , N = 1e3+5;
ll a[N],dp[N][N];
int n,m;
int main(){
ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
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++)// k<=j 避免花数过多,超过了j(余下的位置)
dp[i][j]=(dp[i][j]+dp[i-1][j-k])%p;
}
}
cout<<dp[n][m];
return 0;
}
2、异或选数
分析:
有多少个子序列进行异或可以得到x。
设状态 dp[i][j] 表示到第 i 个数字(共n个)、异或和为 j 的子序列的个数。
对于每次的状态有选择这个数 和 不选择 这两种情况。
dp[i][j] = dp[i-1][j] + dp[i-1][j^a[i]]
代码示例:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+5,p = 998244353;
int a[N],dp[N][70],n,x;
int main(){
ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
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++){//a[i]<=63,所以异或结果肯定不会大于64
dp[i][j]=(dp[i-1][j]+dp[i-1][j^a[i]])%p;
}
}
cout<<dp[n][x];
return 0;
}
3、数字三角形
代码示例:
#include<bits/stdc++.h>
using namespace std;
const int N = 510;
int f[N][N];
int n;
int main(){
cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<=i;j++)
cin>>f[i][j];
for(int i=n-1;i>=0;i--)
for(int j=0;j<=i;j++)
f[i][j]+=max(f[i+1][j],f[i+1][j+1]);
cout<<f[0][0];
return 0;
}