此题实在无语就因为把判断输入条件写成 n!=-1就WA了几次,自己以后要多注意
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <cstdio> 5 #include <cmath> 6 7 using namespace std; 8 9 int main(){ 10 int n; 11 while(cin >> n && n >= 0){ 12 int v,num,sumV = 0; 13 vector<int> value; 14 for(int i =0; i < n; i ++){ 15 cin >>v>>num; 16 sumV += v*num; 17 int tmp =1; 18 while(num > tmp){ 19 value.push_back(tmp*v); 20 num -=tmp; 21 tmp <<=1; 22 } 23 value.push_back(num*v); 24 /* 25 if(num > 1){ 26 int temp = 0, k=0; 27 while(1){ 28 int a = pow(2,k++); 29 if(temp + a > num ) break; 30 temp += a; 31 value.push_back(a*v); 32 } 33 value.push_back((num-temp)*v); 34 } 35 else{ 36 value.push_back(v); 37 }*/ 38 } 39 vector<int> dp(sumV/2+1,0); 40 for(int i = 0; i < value.size(); i ++ ){ 41 for(int j = sumV/2; j >= value[i]; j -- ){ 42 dp[j] = max(dp[j],dp[j-value[i]]+value[i]); 43 } 44 } 45 cout<< sumV-dp[sumV/2] << " "<<dp[sumV/2]<<endl; 46 } 47 return 0; 48 }