题目描述:
有N种房型,每种房型有如下属性:
可入住成人数,可入住儿童数,价格;
根据用户输入的X(需入住成人数),Y(需入住儿童数),Z(需入住几晚),返回N种房型的间数及价格。
输出样例(特别说明):
输入
第一行表示一共有几种房型,设为整型N;
接下来的N行,每行三列3(个数)分别表示每种房型能够容纳的成人数、能够容纳的儿童数、单价
最后一行的三列(3个数)分别表示需要入住的成人数、儿童数,几晚
输出
打出 房型输入的顺序号,顺序号>0,表示选择了此房型数量
顺序号为0表示未选择此房型,最后一列为总价格
样例输入
2--表示两种房型
2 2 100 --第一种房型,能容纳成人数2个,儿童数2个,每晚100
4 3 180 --第二种房型,能容纳成人数4个,儿童数3个,每晚180
3 2 1 --有3个成人,两个儿童,需要住一晚
样例输出
0,1,180.0 --选择第二种房型,数量为1,总价为180
这是携程2018年暑期实习生招聘在线编程题的第三题,当时因为时间不够,没有做完。最近空下来,就把它补完吧。可以用暴力搜索算法解决,跟我上一篇博客中阿里的在线编程题思路基本是一致的。
下面是我的C++代码。为了方便起见,就不按照在线编程的要求进行多次重复输入验证了,只测试一个输入。
#include <iostream>
#include <vector>
using namespace std;
bool isNotPositive(const vector<int>& left)
{
//判断一个vector中的元素是否全小于等于0
int size = left.size();
for (int i = 0; i < size; i++) {
if (left[i] > 0) return false;
}
return true;
}
void search(const vector<vector<int>> &rooms, vector<int> &result,int &price, vector<int> left,vector<int> tmpresult,int tmpprice,int N)
{
//如果left的所有元素都<=0,搜索结束
if (isNotPositive(left)) {
//比较当前搜索结果tmpresult和之前得到的最好结果result
if (tmpprice < price) {
result = tmpresult;
price = tmpprice;
}
}
else {
//left的所有元素都>0,说明还有游客没有入住,需要继续选择房间
vector<int> tmp_left, tmp_tmpresult;
for (int i = 0; i < N; i++) {
//选择第i个房间
tmp_left = left;
tmp_tmpresult = tmpresult;
for (int j = 0; j < 2; j++) {
tmp_left[j] -= rooms[i][j];
}
tmp_tmpresult[i] += 1;
search(rooms, result, price, tmp_left, tmp_tmpresult, tmpprice + rooms[i][2], N);
}
}
}
int main()
{
int N, tmp;
cout << "请输入房型的数量:" << endl;
cin >> N;
vector<vector<int>> rooms(N);
cout << "请输入每种房型能够容纳的成人数、能够容纳的儿童数、单价:" << endl;
for (int i = 0; i < N; i++) {
for (int j = 0; j < 3; j++) {
cin >> tmp;
rooms[i].push_back(tmp);
}
}
vector<int> travelers(3);
cout << "请输入需要入住的成人数、儿童数,几晚:" << endl;
for (int i = 0; i < 3; i++) {
cin >> travelers[i];
}
vector<int> result(N);//最终结果,选择哪些房型
vector<int> tmpresult(N);//储存临时结果
vector<int> left(2);//剩下的游客
int price = INT_MAX, tmpprice = 0;//price初值设为INT_MAX,是为了让result总能得到第一个搜索结果
for (int i = 0; i < N; i++) {
result[i] = 0;
tmpresult[i] = 0;
}
for (int i = 0; i < 2; i++) {
left[i] = travelers[i];
}
search(rooms, result, price, left, tmpresult, tmpprice, N);
//输出结果
cout << "选择房型的情况:" << endl;
for (int i = 0; i < N; i++) {
cout << result[i] << ' ';
}
cout << endl;
cout << "总价为:" << endl;
cout << price*travelers[2] << endl;
system("pause");
return 0;
}
输出如下: