解题思路
这道题卡了我好久,很难受,又是01背包或者DFS的题,但是我没给t赋初值,让我调了快1个小时,然后就是剪枝!
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> v;
int Max;
void dfs(int i, int sumV, int opt){
if(i >= v.size()) return;
if(sumV + v[i] <= opt){
Max = max(Max, sumV + v[i]);
if(Max == opt) return;
dfs(i+1, sumV+v[i], opt);
}
dfs(i+1, sumV, opt);
}
int main(){
string s;
while(getline(cin,s)){
v.clear();
int t=0,flag=0,sum=0;
for(int i=0;i<=s.size();i++){
if(s[i]==' '||i==s.size()){
if(t != 0){ //0放在里面是没有意义的
v.push_back(t);
sum +=t;
t=0;
}
}else if(s[i]>='0'&&s[i]<='9'){
t = t*10 + s[i] -'0';
}else{
flag=1;
break;
}
}
if(flag) cout<<"ERROR"<<endl;
else{
t = sum/2;
Max=0;
dfs(0, 0, t);
printf("%d %d\n",sum-Max, Max);
}
}
return 0;
}