#include<bits/stdc++.h>#define int long long#define IOS ios::sync_with_stdio(0),cin.tie(nullptr),cout.tie(nullptr);
#define memset(a) memset((a), (0), sizeof(a));
using namespace std;
const int N = 1e6+10, M = 1e2+10, MOD = 1e9+7;
int n, m;
int a[N], b[N];
int lowbit(int x) {
return x & -x;
}
//单点修改 将x个增加yvoid update(int x, int y) {
while (x <= n) {
b[x] += y;
x += lowbit(x);
}
}
//区间查询 1~xint query(int x) {
int s = 0;
while (x) {
s += b[x];
x -= lowbit(x);
}
return s;
}
signed main() {
IOS
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
update(i, a[i]);
}
while (m--) {
int t, x, y;
cin >> t >> x >> y;
if (t == 1) {
update(x, y);
} else {
cout << query(y) - query(x - 1) << "\n";
}
}
return 0;
}
背包
01背包
C++
#include<bits/stdc++.h>using namespace std;
#define int long long#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
const int N = 3e5+10;
int t;
int m;
int w[110], v[110];
int dp[1100];
signed main() {
cin >> t >> m;
for (int i = 1; i <= m; i++) cin >> w[i] >> v[i];
for (int i = 1; i <= m; i++) {
for (int j = t; j >= w[i]; j--) {
int nv = dp[j - w[i]] + v[i];
dp[j] = max(dp[j], nv);
}
}
cout << dp[t];
return 0;
}
完全背包
C++
#include<bits/stdc++.h>using namespace std;
#define int long long#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
const int N = 3e5+10;
int t;
int m;
int w[110], v[110];
int dp[1100];
signed main() {
cin >> t >> m;
for (int i = 1; i <= m; i ++) cin >> w[i] >> v[i];
for (int i = 1; i <= m; i ++) {
for (int j = w[i]; j <= t; j ++) {
int nv = dp[j - w[i]] + v[i];
dp[j] = max(dp[j], nv);
}
}
cout << dp[t];
return 0;
}