概念:一系列有序的事件 特点:描述的是一些过程,不是类似与背包问题一样是一个结果。 把混沌的状态细化 1、例题:大盗阿福
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5+10;
int t,n;
int a[N],f[N][2];
int main()
{
cin >> t;
while(t --)
{
cin >> n;
for (int i = 1; i <= n; i ++ ) cin >> a[i];
f[1][0] = 0, f[1][1] = a[1];
for (int i = 2; i <= n; i ++ )
{
f[i][0] = max(f[i-1][0],f[i-1][1]);
f[i][1] = f[i-1][0] + a[i];
}
cout<<max(f[n][0],f[n][1])<<endl;
}
return 0;
}
2、股票买卖IV f[i,j,0]表示到了第i天,已经进行了j次交易,手中没货的状态 f[i,j,1]表示到了第i天,正在进行第j次交易,手中有货的状态
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5+10,M = 110;
int n,k;
int f[N][M][2];
int w[N];
int main()
{
cin >> n >> k;
for (int i = 1; i <= n; i ++ ) cin >> w[i];
memset(f,-0x3f,sizeof f);
for (int i = 0; i <= n; i ++ ) f[i][0][0] = 0;
for (int i = 1; i <= n; i ++ )
{
for (int j = 1; j <= k; j ++ )
{
f[i][j][0] = max(f[i-1][j][0],f[i-1][j][1] + w[i]);
f[i][j][1] = max(f[i-1][j][1],f[i-1][j-1][0]-w[i]);
}
}
int res = 0;
for (int i = 0; i <= k; i ++ ) res = max(res,f[n][i][0]);
cout << res << endl;
return 0;
}
3、股票买卖v
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5+10,inf = 0x3f3f3f3f;
int w[N],f[N][3];
int n;
int main()
{
cin >> n;
for (int i = 1; i <= n; i ++ ) cin >> w[i];
f[0][0] = f[0][1] = -inf;
f[0][2] = 0;
for (int i = 1; i <= n; i ++ )
{
f[i][0] = max(f[i-1][0],f[i-1][2]-w[i]);
f[i][1] = f[i-1][0]+w[i];
f[i][2] = max(f[i-1][2],f[i-1][1]);
}
int res = 0;
for (int i = 1; i <= n; i ++ ) res = max(res,f[i][1]);
cout<<res<<endl;
return 0;
}
|