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 | 179 |
| 201 | 4893 | 관리자 | 2019.12.20 | 149 |
| 200 | 4878 | 관리자 | 2019.12.20 | 149 |
| 199 | 4848 | 관리자 | 2019.12.20 | 152 |
| 198 | 4698 | 관리자 | 2019.12.20 | 148 |
| 197 | 4685 | 관리자 | 2019.12.20 | 206 |
| 196 | 4073 | 관리자 | 2020.04.06 | 160 |
| 195 | 4068 | 관리자 | 2020.04.06 | 217 |
| 194 | 4065 | 관리자 | 2019.12.20 | 155 |
| 193 | 4064 | 관리자 | 2020.04.06 | 157 |
| 192 | 4059 | 관리자 | 2020.04.06 | 5941 |
| 191 | 4055 | 관리자 | 2020.04.06 | 156 |
| 190 | 4044 | 관리자 | 2020.04.06 | 167 |
| 189 | 4043 | 관리자 | 2020.04.06 | 155 |
| 188 | 4040 | 관리자 | 2020.04.06 | 154 |
| 187 | 4039 | 관리자 | 2019.12.20 | 157 |
| 186 | 4035 | 관리자 | 2020.04.06 | 159 |
| 185 | 4034 | 관리자 | 2020.04.06 | 151 |
| 184 | 4028 | 관리자 | 2020.04.06 | 175 |
| 183 | 4023 | 관리자 | 2019.12.20 | 178 |
| » | 3740 | 관리자 | 2019.12.20 | 216 |
| 181 | 3730 | 관리자 | 2019.12.20 | 181 |
| 180 | 3719 | 관리자 | 2019.12.20 | 158 |
| 179 | 3716 | 관리자 | 2019.12.20 | 147 |
| 178 | 3713 | 관리자 | 2019.12.20 | 167 |
| 177 | 3712 | 관리자 | 2019.12.20 | 164 |
| 176 | 3709 | 관리자 | 2019.12.20 | 150 |
| 175 | 3708 | 관리자 | 2019.12.20 | 117 |
| 174 | 3707 | 관리자 | 2019.12.20 | 112 |
| 173 | 3705 | 관리자 | 2019.12.20 | 115 |