Dear Dynamic Programmer,
I was trying to solve UVA 10154 "Weights & Measures".
I first tried an DP LIS approach which is accepted by PC. However, UVA changed the test cases to reject this approach. and UVATOOLKIT is not helpful (it uses DP LIS solution).
Later, I was trying to write DP KNAP approach.
If any one can give me hints about the correct solution for this problem, I'll be grateful.
Here is my second try:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int best[6000][6000];
bool comp(pair<int, int> a, pair<int, int> b){
return a.second > b.second;
}
int main(){
vector<pair<int, int> > v;
v.push_back(make_pair(0, 0));
int C = 0;
int w, s;
while(cin >> w >> s){
if(s-w>C) C = s-w;
v.push_back(make_pair(w, s-w));
}
sort(v.begin()+1, v.end(), comp);
int N = v.size();
for(int i=0 ; i<=N ; i++)
for(int j=0 ; j<=C ; j++)
best[i][j] = 0;
for(int i=1 ; i<=N ; i++){
for(int j=1 ; j<=v[i].first+v[i].second ; j++){
if(v[i].first<=j){
best[i][j] = max(best[i-1][j], best[i-1][j-v[i].first]+1);
}
else{
best[i][j] = best[i-1][j];
}
}
}
// For debugging only
for(int i=0 ; i<=N ; i++){
for(int j=0 ; j<=C ; j+=100){
cout << best[i][j] << " ";
}
cout << endl;
}
cout << best[N][C] << endl;
return 0;
}
created
last reply
- 3
replies
- 483
views
- 2
users
- 1
link