-
两部分值最好为数组和sum/2。但是实际中可能不这样。我们看出来数组分割成a、b两部分,那么a、b肯定有一个小于等于sum/2.这就是从数组中拿出一些数,使得数据的和小于等于sum/2.这就转换成了背包问题了。
代码如下:
#include
#include
#include
using namespace std;
int maxT(int a, int b)
{
if (a > b)
{
return a;
}
return b;
}
int diff(vector &vectorInt)
{
int len = vectorInt.size();
int sum = 0;
for (int i = 0; i < vectorInt.size(); i++)
{
sum += vectorInt[i];
}
cout << "sum= " << sum << endl;
vector<vector> dp;
for (int i = 0; i <= len; i++)
{
vector tmp;
for (int j = 0; j <= sum / 2; j++)
{
tmp.push_back(0);
}
dp.push_back(tmp);
}
for (int i = 1; i <= len; i++)
{
for (int j = 1; j <= sum / 2; j++)
{
if (j >= vectorInt[i - 1])
{
dp[i][j] = maxT(dp[i - 1][j], dp[i - 1][j - vectorInt[i - 1]] + vectorInt[i - 1]);
}
else
{
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[len][sum / 2];
}
int main()
{
vector intarr;
for (int i = 0; i < 20; i++)
{
int val = rand() % 100;
intarr.push_back(val);
cout << val << " ";
}
cout << endl;
cout << diff(intarr) << endl;
system(“pause”);
return 0;
}
执行结果如下:
C++11 的新特性function的使用,std :: function的实例可以存储,复制和调用任何可调用的目标。当使用的时候再初始化。
#include
#include
#include}
static Base* creatInstance()
{
return new Apoint();
}
void display()
{
cout << "this is a Apoint " << endl;
}
};
class Bpoint :public Base
{
public:
Bpoint()
{}
static Base* creatInstance()
{
return new Bpoint();
}
void display()
{
cout << "this is a Bpoint " << endl;
}
};
typedef std::function<Base*()> createBase;//所有使用createBase函数,必须符合Base*()这个样子。
map<string, createBase> mapPoint;
template
void addPoint()
{
auto name = typeid(T).name();
if (mapPoint.find(name) == mapPoint.end())
{
mapPoint[name] = T::creatInstance;
}
}
int main()
{
addPoint();
addPoint();
for (auto x : mapPoint)
{
cout << x.first << endl;
auto point = x.second();//这个必须是括号
point->display();
}
system(“pause”);
return 0;
}
执行结果: