题目描述:点击进入
思路
01背包,套板子
代码
#include<iostream>
#include<string>
#include<map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define best 131
#define INF 0x3f3f3f3f
#define P pair<int,int>
using namespace std
;
typedef long long ll
;
typedef unsigned long long ull
;
const double eps
=1e-5;
const double pai
=acos(-1.0);
const int N
=3e4+10;
const int maxn
=110;
const int mod
=1e9+7;
int n
,m
,v
[N
],w
[N
],f
[N
];
int main()
{
scanf("%d%d",&n
,&m
);
for(int i
=1;i
<=m
;i
++)
{
scanf("%d%d",&v
[i
],&w
[i
]);
}
for(int i
=1;i
<=m
;i
++)
{
for(int j
=n
;j
>=v
[i
];j
--)
{
f
[j
]=max(f
[j
],f
[j
-v
[i
]]+v
[i
]*w
[i
]);
}
}
printf("%d\n",f
[n
]);
return 0;
}
模板(一维)
#include<iostream>
#include<string>
#include<map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define best 131
#define INF 0x3f3f3f3f
#define P pair<int,int>
using namespace std
;
typedef long long ll
;
typedef unsigned long long ull
;
const double eps
=1e-5;
const double pai
=acos(-1.0);
const int N
=3e4+10;
const int maxn
=110;
const int mod
=1e9+7;
int f
[1010],w
[1010],v
[1010];
int main()
{
int t
,m
;
memset(f
,0,sizeof(f
));
scanf("%d%d",&t
,&m
);
for(int i
=1;i
<=m
;i
++) scanf("%d%d",&w
[i
],&v
[i
]);
for(int i
=1;i
<=m
;i
++)
{
for(int j
=t
;j
>=w
[i
];j
--)
{
f
[j
]=max(f
[j
-w
[i
]]+v
[i
],f
[j
]);
}
}
printf("%d\n",f
[t
]);
return 0;
}
模板(二维)
#include<iostream>
#include<string>
#include<map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#define X first
#define Y second
#define best 131
#define INF 0x3f3f3f3f
#define P pair<int,int>
using namespace std
;
typedef long long ll
;
typedef unsigned long long ull
;
const double eps
=1e-5;
const double pai
=acos(-1.0);
const int N
=3e4+10;
const int maxn
=110;
const int mod
=1e9+7;
int w
[105],v
[105];
int dp
[105][1005];
int main()
{
int t
,m
,res
=-1;
scanf("%d%d",&t
,&m
);
for(int i
=1;i
<=m
;i
++) scanf("%d%d",&w
[i
],&v
[i
]);
for(int i
=1;i
<=m
;i
++)
{
for(int j
=t
;j
>=0;j
--)
{
if(j
>=w
[i
]) dp
[i
][j
]=max(dp
[i
-1][j
-w
[i
]]+v
[i
],dp
[i
-1][j
]);
else dp
[i
][j
]=dp
[i
-1][j
];
}
}
printf("%d\n",dp
[m
][t
]);
return 0;
}
转载请注明原文地址:https://blackberry.8miu.com/read-9251.html