有n个部下,每个部下需要完成一项任务,第i个部下需要花Bi分钟交待任务,然后执行Ji分钟后完成任务,不能同时给两个部下交待任务,但部下们可以同时执行各自任务。输入要求第一行为部下个数,以下每行两个整数B(交待任务的时间)J(执行任务的时间)。
分析:执行任务时间长的先交待,即应该从大到小排序任务时间,这是一个贪心算法。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Job
{
int j, b;//j is the time to finish mission,b is the time to tell the mission, you need to tell the mission first
bool operator < (const Job &x) const
{
return j > x.j;
}
};
int main()
{
int n, b, j;//n is the number of soldiers
cout << "please input you soldiers' number" << endl;
cin >> n;
vector <Job> v;
for (int i = 0; i < n; i++)
{
cin >> b;
cin >> j;
v.push_back(job);
}
sort(v.begin(), v.end());
int s = 0;
int ans = 0;
for (int i = 0; i < n; i++)
{
s = s + v[i].b;
ans = max(ans, s + v[i].j);
}
cout << ans << endl;
return 0;
}
但以上程序在VS2015中编译未能通过,在V.push_back((Job){j,b})报错应输入表达式。
查资料后发现应该在定义结构体时增加一个构造函数:
Job(int m, int n) :j(m), b(n) {}
在压入容器前应该构造Job对象job:
Job job(j,b);
在使用sort时必须要支持<运算符,这也是本程序中重载运算符的原因,关于C++的迭代器和构造函数方面尚存很多知识漏洞,亟待努力。