突然间发现CSDN上有个编程挑战的专栏,点进去以后感觉挺有兴趣的,就挑一些自己感兴趣能做的贴出来。
注:答案乃本人原创,可能存在不严谨甚至有错误的地方,如果发现,还望不吝赐教
1. 题目背景: 那一年,这一年,青春散场,到毕业季,我们奔波着忙着找工作,来到招聘会上,看到黑压压的一大片人群.. 题目描述:毕业季,很多大公司来学校招聘, 招聘会分散在不同时间段,小明想知道自己最多能完整的参加多少个招聘会(参加一个招聘会的时候不能中断或离开)。 假设现在有n个招聘会,每个招聘会都有个起止时间,时间由从招聘会第一天0点开始的小时数表示,n <= 1000 。 返回:最多参加的招聘会的个数n。 举个例子: 现在有3场招聘会,他们的起始时间为: 9-10 10-20 8-15 返回: 2
#include <iostream>
#include <map>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
bool ShortDurationTime(pair<int, int> pairA, pair<int, int> pairB)
{
return pairA.second < pairB.second;
}
int GetAttendMaxCount(vector<pair<int, int> >& time)
{
map<int, pair<int, int> > mapMeeting;
vector<pair<int, int> > vecTimeLength;
int i = 0;
for(vector<pair<int, int> >::iterator iterTime = time.begin();
iterTime != time.end(); iterTime++)
{
mapMeeting.insert(make_pair(i, *iterTime)); //将Time装进map容器中编号,便于查询
int DuraTionTime = iterTime->second - iterTime->first;
vecTimeLength.push_back(make_pair(i, DuraTionTime)); //将time中招聘会的持续时间计算出来,保存在vecTimeLength中
i++;
}
//将vecTimeLength中的元素按照持续时间由短到长升序排序(相同持续时间按照字典顺序)
sort(vecTimeLength.begin(), vecTimeLength.end(), ShortDurationTime);
vector<pair<int, int> > vecPitch;
for (vector<pair<int, int> >::iterator iterTimeLength = vecTimeLength.begin();
iterTimeLength != vecTimeLength.end(); iterTimeLength++)
{
if (vecPitch.size() == 0)//vecTimeLength第一个元素直接添加进vecPitch
{
vecPitch.push_back(*iterTimeLength);
}
else
{
bool bSign = true;
int nTotalTime = 0;
for (vector<pair<int, int> >::iterator iterPitch = vecPitch.begin();
iterPitch != vecPitch.end(); iterPitch++)
{
if ((mapMeeting[iterTimeLength->first].first >= mapMeeting[iterPitch->first].first
&& mapMeeting[iterTimeLength->first].first < mapMeeting[iterPitch->first].second)
|| (mapMeeting[iterTimeLength->first].second > mapMeeting[iterPitch->first].first
&& mapMeeting[iterTimeLength->first].second <= mapMeeting[iterPitch->first].second)
|| (mapMeeting[iterPitch->first].first >= mapMeeting[iterTimeLength->first].first
&& mapMeeting[iterPitch->first].first < mapMeeting[iterTimeLength->first].second)
|| (mapMeeting[iterPitch->first].first >= mapMeeting[iterTimeLength->first].first
&& mapMeeting[iterPitch->first].first < mapMeeting[iterTimeLength->first].second)) //两场招聘会时间重叠
{
bSign = false;
break;
}
else
{
nTotalTime += iterPitch->second;
}
}
if (bSign)///两场招聘会时间不重叠
{
vecPitch.push_back(*iterTimeLength);
nTotalTime += iterTimeLength->second;
}
else
{
if (nTotalTime + iterTimeLength->second > 24) //总时间超过24小时,中断循环,结束
{
break;
}
}
}
}
return vecPitch.size(); //vecPitch的个数即能参加最多招聘会的次数
}
注释:
该题的算法是:
(1).将每场招聘会的持续时间计算出来,按照持续时间由短到长升序排序
(2).排序后的招聘会,无条件选中第一场招聘会,然后将下一场招聘会时间同以选中招聘会时间作比较,如无重叠部分即选中该招聘会。
(3).当以选中招聘会持续时间之和加上下一场要判断的招聘会时间超过24小时,break, return。
2.如果一个数各个数位上的数字之和是质数,并且各个数位上的数字的平方和也是质数,则称它为幸运数。 给定x,y,求x,y之间( 包含x,y,即闭区间[x,y])有多少个幸运数。 例如1到20之间有4个幸运数,它们是11,12,14,16,像因为1+1 = 2是质数,1^2 + 1^2 = 2也是质数等等。 给定函数原型,其中1<=x<=y<=1000000000,请完成函数,实现上述功能。
挑战规则:
可额外编写其它的函数,然后lucky调用你编写的其它函数返回结果值; 限时3s,程序运行时间超过3s即挑战失败。
未完待续.....