【華爲機試題】【棧】【全排列】火車進站

鏈接:https://www.nowcoder.com/questionTerminal/97ba57c35e9f4749826dc3befaeae109
來源:牛客網

火車進站

給定一個正整數N代表火車數量,0<N<10,接下來輸入火車入站的序列,一共N輛火車,每輛火車以數字1-9編號。要求以字典序排序輸出火車出站的序列號。

輸入描述:

有多組測試用例,每一組第一行輸入一個正整數N(0<N<10),第二行包括N個正整數,範圍爲1到9

輸出描述:

輸出以字典序從小到大排序的火車出站序列號,每個編號以空格隔開,每個輸出序列換行,具體見sample。

示例1

輸入

3
1 2 3

輸出

1 2 3
1 3 2
2 1 3
2 3 1
3 2 1

問題分析:

                    1.全排列

                    2.根據棧 後進先出的特點篩去 原始進站順序無法出棧得到的排列

方法要點:

                    std::next_permutation() 排序函數的使用                  

default (1)
template <class BidirectionalIterator>
  bool next_permutation (BidirectionalIterator first,
                         BidirectionalIterator last);
custom (2)
template <class BidirectionalIterator, class Compare>
  bool next_permutation (BidirectionalIterator first,
                         BidirectionalIterator last, Compare comp);
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

//is_order函數用來判斷當前排序即v1數組是否可以通過數組v壓棧得出
bool is_order(vector<int> &v, vector<int> &v1, int n)
{
	if (v.size() == 0 || v1.size() == 0 || n <= 0)
		return false;
	stack<int> s;
	int j = 0;
	for (size_t i = 0; i < v.size(); i++)
	{
		s.push(v[i]);
		while (j < n && s.size() != 0 && v1[j] == s.top())
		{
			s.pop();
			j++;
		}
	}
	return s.empty();
}
int main()
{
	int n;
	while (cin >> n)
	{
		vector<int> v(n),v1(n);
		for (int i = 0; i < n;i++)
			cin >> v[i];
		//把輸入的數據數組複製一份到v1
		v1.assign(v.begin(),v.end());
		//對v1進行排序 ----------由題目輸出要以字典序排序輸出可知
		sort(v1.begin(), v1.end());
		do
		{
			if (is_order(v, v1, n))
			{
				for (auto e : v1)
					cout << e << " ";
				cout << endl;
			}
		} while (next_permutation(v1.begin(), v1.end()));
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章