out(easy) 【题目描述】 给你一个长度为n的排列a,一个空的栈s和一个空的数组b,你每次可以做两种操作中的一种: 将数组a最前面的数压到栈s中 如果栈s中有数,将栈顶元素弹到b的末尾 最终你需要使得a中没有数且栈s中的数也全部弹到b中,请问构成字典序最小的b是什么。 【输入文件】 out.in 第一行输入一个正整数n(1≤n≤100)。 第二行输入a(1≤a[i]≤n,且所有a[i]不相同)。 【输出文件】 out.out 输出字典序最小的b。 【样例输入1】 3 2 3 1 【样例输出1】 1 3 2 【样例输入2】 3 3 1 2 【样例输出2】 1 2 3#include<bits/stdc++.h> using namespace std; vector<int> p(vector<int>& a,int n1) { stack<int> s; vector<int> b; for (int i = 0; i < n1; i++) { while (!s.empty() && s.top() >= a[i]) { b.push_back(s.top()); s.pop(); } s.push(a[i]); } while (!s.empty()) { b.push_back(s.top()); s.pop(); } return b; } int main() { int n; cin >> n; vector<int> a(n); for(int i = 0; i < n; i++){ cin >> a[i]; } vector<int> t = p(a,n); for(int i = 0; i < n; i++){ cout << t[i] << " "; } return 0; }
时间: 2024-04-16 13:23:49 浏览: 19
你可以使用以下代码解决这个问题:
```cpp
#include<bits/stdc++.h>
using namespace std;
vector<int> p(vector<int>& a,int n1) {
stack<int> s;
vector<int> b;
for (int i = 0; i < n1; i++) {
while (!s.empty() && s.top() >= a[i]) {
b.push_back(s.top());
s.pop();
}
s.push(a[i]);
}
while (!s.empty()) {
b.push_back(s.top());
s.pop();
}
return b;
}
int main()
{
int n;
cin >> n;
vector<int> a(n);
for(int i = 0; i < n; i++){
cin >> a[i];
}
vector<int> t = p(a,n);
for(int i = 0; i < n; i++){
cout << t[i] << " ";
}
return 0;
}
```
将上述代码保存到名为 `out.cpp` 的文件中。
然后,你可以使用以下命令来编译和运行代码:
```
g++ out.cpp -o out
./out < out.in > out.out
```
这将使用输入文件 `out.in` 中的数据运行代码,并将输出保存到 `out.out` 文件中。你可以检查 `out.out` 文件以获取结果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)