题目描述
解题思路1
用vector < queue < int > > 进行存储座位,不需要额外判断和维护该行的空余座位
依次判断每一个queue.size()是否满足要求
如果找不到连续的,就遍历每一行,若每一行size()不为0就弹出相应位置,重复操作知道弹出x个座位
解题思路2
- 火车总购票数小于100,所以必定有解,数据范围不大,所以暴力模拟求解
- 座位的选择只有两种方式
- 第一种,寻找是否有某一行可以有连续p个座位,安排!
- 第二种,找不到连续座位,从小到大,见缝插针,安排p个座位
代码实现1:STL模拟
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
vector <queue<int>> all; //存储所有的未安排的座位
int main()
{
for (int i = 0; i < 20; i ++)
{
queue <int> t;
for (int j = 1; j <= 5; j ++) //将所有座位放入all中
{
t.push(i * 5 + j);
}
all.push_back(t);
}
int n;
cin >> n;
while (n --)
{
int x;
cin >> x;
bool success = false; //找不到连续的座位标记
for (auto &r : all)
{
if (r.size() >= x) //当前行有连续x个座位
{
while (x --)
{
cout << r.front() << " "; //将座位号输出
r.pop(); //将座位弹出
}
success = true; //标记已经找到连续的座位
break;
}
}
if (!success) //找不到连续的座位
{
for (auto &r : all)
{
while (r.size() && x) //当这一行有座位并且需要安排座位时
{
cout << r.front() << " ";
r.pop();
x --; //需要安排的座位减一
}
}
}
cout << endl;
}
return 0;
}
代码实现2:暴力枚举
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 30;
int seat[N][N];
bool is_buyed[N][N]; //判断当前这个作为是否已经被购买
int main()
{
int n;
cin >> n;
int num = 1;
for (int i = 1; i <= 20; i ++)
{
for (int j = 1; j <= 5; j ++)
{
seat[i][j] = num; //给1~100个作为编号
num ++;
}
}
while (n --)
{
int p = 0;
cin >> p; //输入所需座位数
bool flag = false;
for (int i = 1; i <= 20; i ++)
{
int bn = 0;
int c = 0;
for (int j = 1; j <= 5; j ++) //搜索每一行座位,bn记录第一个空余座位的前一个座位,c记录连续座位的个数
{
if (is_buyed[i][j])
{
c = 0;
bn = j;
}
else c ++;
}
if (c >= p) //如果连续作为个数大于需求数,则可以安排在这一排
{
flag = true;
for (int j = bn + 1; j < bn + 1 + p; j ++) //从第一个空座位开始枚举,枚举p个座位
{
is_buyed[i][j] = true;
cout << seat[i][j] << " ";
}
cout << endl;
break;
}
}
if (!flag) //如果没有找到连续的座位
{
int cnt = 0;
for (int i = 1; i <= 20; i ++)
{
for (int j = 1; j <= 5; j ++) //从小到大找p个座位
{
if (!is_buyed[i][j])
{
cnt ++;
cout << seat[i][j] << " ";
is_buyed[i][j] = true;
}
if (cnt == p) break;
}
if (cnt == p) break;
}
cout << endl;
}
}
return 0;
}