例题链接:SDNUOJ-1043:http://www.acmicpc.sdnu.edu.cn/problem/show/1043
解析:直接按照01背包问题的解法,但是更新数据的时候是自下而上进行数据更新
(01背包数据更新是自上而下,这样不会影响下面的更新,完全背包数据更新是自下而上,这样就可以实现多个物件被使用)
#include <cstdio> #include <cstring> #include <string> #include <cmath> #include <iostream> #include <algorithm> #include <vector> #include <stack> #include <sstream> #include <map> #include <set> #include <queue> #include <stdlib.h> #define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); using namespace std; typedef long long ll; int a[1005]; int main() { int t,n; cin >> t >> n; for (int i=1;i<=n;i++) //个数 { int x,y; //采药时间+这个药的价值 cin >> x >> y; for (int j=x;j<=t;j++) { a[j]=max(a[j],a[j-x]+y); } } cout << a[t] << endl; return 0; }
例题链接:Luogu 1616 疯狂的采药:https://www.luogu.com.cn/problem/P1616
#include <cstdio> #include <cstring> #include <string> #include <cmath> #include <iostream> #include <algorithm> #include <vector> #include <stack> #include <sstream> #include <map> #include <set> #include <queue> #include <stdlib.h> #define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); using namespace std; typedef long long ll; ll a[10000005]; //数组开的大小是1e7,并且会爆ll,不要用int int main() { ll t,n; cin >> t >> n; for (ll i=1;i<=n;i++) //个数 { ll x,y; cin >> x >> y; for (ll j=x;j<=t;j++) { a[j]=max(a[j],a[j-x]+y); } } cout << a[t] << endl; return 0; }