写法1:
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int t, n;
int w[N], f[N];
int main()
{
cin >> t;
while(t --)
{
cin >> n;
for (int i = 0; i < n; i ++)
cin >> w[i];
memset(f, 0, sizeof f);
f[0] = w[0];
f[1] = max(w[0], w[1]);
for (int i = 2; i < n; i ++)
f[i] = max(f[i - 1], f[i - 2] + w[i]);
cout << f[n - 1] << endl;
}
return 0;
}
写法2:
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int t;
int f[N];
int main()
{
cin >> t;
while(t --)
{
int n, w;
cin >> n;
memset(f, 0, sizeof f);
cin >> w;
f[1] = w;
for (int i = 2; i <= n; i ++)
{
cin >> w;
f[i] = max(f[i - 1], f[i - 2] + w);
}
cout << f[n] << endl;
}
return 0;
}