第一种做法:这种方法,算法复杂性大,重复的递归
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<math.h>
#include<iomanip>
#include<numeric>
using namespace std;
int getGolds(vector<int> golds);
int delGolds(vector<int> golds)
{
if (golds.size() == 1)
{
golds.erase(golds.begin());
return 0;
}
int leftNum = golds[0];
vector<int> goldsLeft = golds;
goldsLeft.erase(goldsLeft.begin());
int rightNum = golds[golds.size() - 1];
vector<int> goldsRight = golds;
goldsRight.erase(goldsRight.end() - 1);
if (leftNum+delGolds(goldsLeft) > rightNum+delGolds(goldsRight))
{
// cout << "B取:" << *golds.begin() << endl;
golds.erase(golds.begin());
}
else
{
// cout << "B取:" << *(golds.end() - 1) << endl;
golds.erase(golds.end()-1);
}
return getGolds(golds);
}
int getGolds(vector<int> golds)
{
if (golds.size() == 1 )
{
return golds[0];
}
int leftNum =golds[0];
vector<int> goldsLeft=golds;
goldsLeft.erase(goldsLeft.begin());
int rightNum = golds[golds.size()-1];
vector<int> goldsRight = golds;
goldsRight.erase(goldsRight.end() - 1);
return max(leftNum + delGolds(goldsLeft), rightNum + delGolds(goldsRight));
}
int main()
{
int T;
cin >> T;
int flag = 1;
while (T != 0)
{
T--;
vector<int> golds;
int n;
cin >> n;
for (int i = 0;i < n;i++)
{
int g;
cin >> g;
golds.push_back(g);
}
int aSum = getGolds( golds);
int sum = accumulate(golds.begin(),golds.end(),0);
int bSum = sum - aSum;
cout << "Case #" << flag << ": " << aSum << " " << bSum << endl;
// cout << "Case #" << flag << ": " << aSumleft << " " << bSumleft << endl;
flag++;
}
return 0;
}
//第二种做法,还是算法复杂性大
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<math.h>
#include<iomanip>
#include<numeric>
#include<list>
#include<deque>
using namespace std;
int getGolds(vector<int> golds,int sum)
{
if (golds.size() == 1 )
{
return golds[0];
}
int leftNum =golds[0];
vector<int> goldsLeft=golds;
goldsLeft.erase(goldsLeft.begin());
int rightNum = golds[golds.size()-1];
vector<int> goldsRight = golds;
goldsRight.erase(goldsRight.end() - 1);
return sum -min(getGolds(goldsLeft,sum- leftNum), getGolds(goldsRight, sum - rightNum));
}
int main()
{
int T;
cin >> T;
int flag = 1;
while (T != 0)
{
T--;
vector<int> golds;
int n;
int sum=0;
cin >> n;
for (int i = 0;i < n;i++)
{
int g;
cin >> g;
golds.push_back(g);
sum += g;
}
int aSum = getGolds( golds,sum);
int bSum = sum - aSum;
cout << "Case #" << flag << ": " << aSum << " " << bSum << endl;
// cout << "Case #" << flag << ": " << aSumleft << " " << bSumleft << endl;
flag++;
}
return 0;
}