给定一个数组,分隔成两部分,求两个部分之间的差值最小和C++11 function的使用

  1. 两部分值最好为数组和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
    #include
    using namespace std;
    class Base
    {
    public:
    virtual void display()
    {
    cout << "this is a Base " << endl;
    }
    };
    class Apoint:public Base
    {
    public:
    Apoint()
    {

    }
    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;
}
执行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值