C++
DP
재귀함수
#include <cstdio>
#include <algorithm>
#include <climits>
#include <cstring>
using namespace std;
int N,W;
int dt[110][10010];
int we[110],vv[110];
int serch(int n, int w){
if(n==N){
return 0;
}
if(dt[n][w]!=-1){
return dt[n][w];
}
if(w+we[n]>W){
return dt[n][w] = serch(n+1,w);
}
return dt[n][w] = max(serch(n+1,w+we[n])+vv[n],serch(n+1,w));
}
int main()
{
memset(dt,-1,sizeof(dt));
scanf("%d %d",&N,&W);
for(int i=0;i<N;i++){
scanf("%d %d",&we[i],&vv[i]);
}
printf("%d",serch(0,0));
return 0;
}
Bottom up
#include <cstdio>
#include <algorithm>
#include <climits>
#include <cstring>
using namespace std;
int N,W;
int dt[110][10010];
int we[110],vv[110];
int main()
{
scanf("%d %d",&N,&W);
for(int i=1;i<=N;i++){
scanf("%d %d",&we[i],&vv[i]);
}
for(int i=1;i<=N;i++){
for(int w=0;w<=W;w++){
dt[i][w] = dt[i-1][w];
if(w - we[i] >= 0)
dt[i][w] = max(dt[i][w], dt[i-1][w - we[i]] + vv[i]);
}
}
int max_ = 0;
for(int w=0;w<=W;w++){
max_=max(max_,dt[N][w]);
}
printf("%d",max_);
return 0;
}
댓글 0
번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|
공지 | 안내사항 | 관리자 | 2019.12.02 | 175 |
201 | 4893 | 관리자 | 2019.12.20 | 145 |
200 | 4878 | 관리자 | 2019.12.20 | 145 |
199 | 4848 | 관리자 | 2019.12.20 | 148 |
198 | 4698 | 관리자 | 2019.12.20 | 144 |
197 | 4685 | 관리자 | 2019.12.20 | 202 |
196 | 4073 | 관리자 | 2020.04.06 | 156 |
195 | 4068 | 관리자 | 2020.04.06 | 213 |
194 | 4065 | 관리자 | 2019.12.20 | 151 |
193 | 4064 | 관리자 | 2020.04.06 | 153 |
192 | 4059 | 관리자 | 2020.04.06 | 5937 |
191 | 4055 | 관리자 | 2020.04.06 | 152 |
190 | 4044 | 관리자 | 2020.04.06 | 157 |
189 | 4043 | 관리자 | 2020.04.06 | 151 |
188 | 4040 | 관리자 | 2020.04.06 | 150 |
187 | 4039 | 관리자 | 2019.12.20 | 153 |
186 | 4035 | 관리자 | 2020.04.06 | 155 |
185 | 4034 | 관리자 | 2020.04.06 | 147 |
184 | 4028 | 관리자 | 2020.04.06 | 165 |
183 | 4023 | 관리자 | 2019.12.20 | 174 |
» | 3740 | 관리자 | 2019.12.20 | 212 |
181 | 3730 | 관리자 | 2019.12.20 | 176 |
180 | 3719 | 관리자 | 2019.12.20 | 154 |
179 | 3716 | 관리자 | 2019.12.20 | 143 |
178 | 3713 | 관리자 | 2019.12.20 | 164 |
177 | 3712 | 관리자 | 2019.12.20 | 161 |
176 | 3709 | 관리자 | 2019.12.20 | 147 |
175 | 3708 | 관리자 | 2019.12.20 | 114 |
174 | 3707 | 관리자 | 2019.12.20 | 109 |
173 | 3705 | 관리자 | 2019.12.20 | 112 |