P1048 [NOIP2005 普及组] 采药
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t,m;
cin>>t>>m;
std::vector<int>bei(t+1,0);
for(int i=0;i<m;i++){
int a,b;
cin>>a>>b;
for(int i1=bei.size()-1;i1-a>=0;i1--){
bei[i1]=bei[i1]>bei[i1-a]+b?bei[i1]:bei[i1-a]+b;
}
}
cout<<bei[t]<<endl;
return 0;
}
简单背包
P1616 疯狂的采药
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long t,m;
cin>>t>>m;
std::vector<long long>bei(t+1,0);
for(int i=0;i<m;i++){
int a,b;
cin>>a>>b;
for(int i1=0;i1+a<bei.size();i1++){
bei[i1+a]=bei[i1+a]>bei[i1]+b?bei[i1+a]:bei[i1]+b;
}
}
cout<<bei[t]<<endl;
return 0;
}
改变遍历方式即可;
考虑数据大小改用int应该就会溢出;
P1049 [NOIP2001 普及组] 装箱问题
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t,m;
cin>>t>>m;
std::vector<int>bei(t+1,0);
for(int i=0;i<m;i++){
int a,b;
cin>>a;
for(int i1=bei.size()-1;i1-a>=0;i1--){
bei[i1]=bei[i1]>bei[i1-a]+a?bei[i1]:bei[i1-a]+a;
}
}
cout<<t-bei[t]<<endl;
return 0;
}
看做价格等于背包容量
P1833 樱花
#include <bits/stdc++.h>
using namespace std;
int toint(string s1){
int ans=0;
for(int i=0;i<s1.size();i++){
ans*=10;
ans+=s1[i]-'0';
}
return ans;
}
int thetime(string s1){
int pos=s1.find(':');
int t=toint(s1.substr(0,pos))*60+toint(s1.substr(pos+1,10));
return t;
}
int main()
{
string s1,s2;
cin>>s1;
cin>>s2;
int t,m;
t=thetime(s2)-thetime(s1);
//cout<<t;
cin>>m;
std::vector<int>bei(t+1,0);
for(int i=0;i<m;i++){
int a,b,c;
cin>>a>>b>>c;
if(c==0){
for(int i1=0;i1+a<bei.size();i1++){
bei[i1+a]=bei[i1+a]>bei[i1]+b?bei[i1+a]:bei[i1]+b;
}
}else {
for(int i2=0;i2<c;i2++){
for(int i1=bei.size()-1;i1-a>=0;i1--){
bei[i1]=bei[i1]>bei[i1-a]+b?bei[i1]:bei[i1-a]+b;
}
}
}
}
cout<<bei[t]<<endl;/**/
return 0;
}
没开优化超时;
#include <bits/stdc++.h>
using namespace std;
int toint(string s1){
int ans=0;
for(int i=0;i<s1.size();i++){
ans*=10;
ans+=s1[i]-'0';
}
return ans;
}
int thetime(string s1){
int pos=s1.find(':');
int t=toint(s1.substr(0,pos))*60+toint(s1.substr(pos+1,10));
return t;
}
void gouzao(vector<int>&zhi,int c){
zhi.clear();
//cout<<"??"<<c<<" "<<":";
int temp=1;
for(;temp<=c;temp*=2){
zhi.push_back(temp);
c-=temp;
}
if(c){
zhi.push_back(c);
}/*
for(int num:zhi){
cout<<num<<" ";
}cout<<endl;
*/ }
int main()
{
string s1,s2;
cin>>s1;
cin>>s2;
int t,m;
t=thetime(s2)-thetime(s1);
vector<int>zhi;
//cout<<t;
cin>>m;
std::vector<int>bei(t+1,0);
for(int i=0;i<m;i++){
int a,b,c;
cin>>a>>b>>c;
if(c==0){
for(int i1=0;i1+a<bei.size();i1++){
bei[i1+a]=bei[i1+a]>bei[i1]+b?bei[i1+a]:bei[i1]+b;
}
}else {
gouzao(zhi,c);
for(int i2=0;i2<zhi.size();i2++){
for(int i1=bei.size()-1;i1-a*zhi[i2]>=0;i1--){
int last=bei[i1];
bei[i1]=bei[i1]>bei[i1-a*zhi[i2]]+b*zhi[i2]?bei[i1]:bei[i1-a*zhi[i2]]+b*zhi[i2];
}
}
}
}
cout<<bei[t]<<endl;/**/
return 0;
}
使用二进制优化 拆分为1 2 ....c-2的i+1次方+1;