题目描述
输入样例
8 3 4
20 25 15 18 20 18 8 5
输出样例
20 15
20 18 18 8
25 5
思路
模拟题
具体做法如下
1.按照题意,首先从盒子中拿取,此时如果当前松枝上为空,则直接插上;
否则需要判断当前盒子顶端的松针片是否<=当前松枝的上一个松针片,且松针不能超过最大容量,如果满足,插上。如果以上两种情况都不满足,或者盒子已经空了,那么从盒子里拿去的步骤就完成了
2.从盒子里拿取完成后,需要判断,当前松枝是否已经达到最大容量了,如果是,则直接输出当前松枝上的松枝片,不用再从传送带上拿取
3.如果从盒子内拿完后,仍然没有达到最大容量,则接着从传送带上拿取。此时需要保证传送带上面有松枝片,然后如果当前松枝上为空,则直接插上;否则需要判断当前传送带首段松针片是否<=当前松枝的上一个松针片,如果满足,插上。
本文采用数组模拟队列和栈
AC代码
#include <iostream>
#include <vector>
using namespace std;
const int N = 1010;
int q[N], st[N]; //数组q模拟队列,st数组模拟栈
int hh, tt, ttop; //hh为队列头指针,tt为队列尾指针,ttop为栈顶指针
vector<int> res; //本次的成品松枝
int main()
{
tt = -1, ttop = -1;
int n, m, k;
cin >> n >> m >> k;
for(int i = 0; i < n; i ++) cin >> q[++ tt];
while(1)
{
res.clear();
//先从盒子中拿
while(ttop != -1)
{
if(!res.size()) res.push_back(st[ttop --]);
else
{
if(res[res.size() - 1] >= st[ttop] && res.size() < k) res.push_back(st[ttop --]);
else break;
}
}
if(res.size() == k) //松枝满了直接输出,不再从传送带上拿
{
for(int i = 0; i < res.size(); i ++)
{
if(i != res.size() - 1) cout << res[i] << " ";
else cout << res[i] << endl;
}
continue;
}
//再从传送带上拿
while(hh <= tt)
{
if(!res.size()) res.push_back(q[hh ++]); //如果当前松枝片为空,则直接将传送带上去到的松针片放上
else
{
if(res.size() == k) break; //判断当前松枝是否已满,这里一定要有该判断,否则可能会超出一个松枝上所能容纳的最大限制
else
{
if(res[res.size() - 1] >= q[hh]) res.push_back(q[hh ++]); //传送带上去到的松针片满足要求
else
{
if(ttop < m - 1) st[++ ttop] = q[hh ++]; //小盒子未满,将当前不满足要求的松枝片放到盒子中
else break;
}
}
}
}
if(!res.size()) break; //如果经过两次操作,本次制作的松枝仍没有一个松枝片,则说明盒子里 和 传送带上均没有松针
for(int i = 0; i < res.size(); i ++)
{
if(i != res.size() - 1) cout << res[i] << " ";
else cout << res[i];
}
cout << endl;
}
return 0;
}
欢迎大家批评指正!!!