棧_應用_CH1101_火車進棧
阿新 • • 發佈:2018-12-19
思路分析:
n節火車, 對應2n次進出棧操作, 組織解空間樹的結構, 設解空間樹的每個葉結點對應一個進出棧方案, 按照字典序遍歷解空間樹的前20個葉結點即可, AC程式碼如下:
//CH1101_火車進棧 #include <cstdio> #include <iostream> #include <vector> using namespace std; const int MAX = 20; int t; vector<int> res;//res[0..n - 1]:出棧方案 vector<int> in, out;//in[0...]當前棧中火車棧底到棧頂, out[0...]當前未進棧火車 //, out[0]編號最小, 且初始時刻out[0...n - 1] = 1...n void solve(){ if(t == MAX) return; if(in.empty() && out.empty()){ for(int i = 0; i < res.size(); ++i) cout << res[i]; cout << endl, ++t; return; } if(!in.empty()){ int x = in.back(); res.push_back(x), in.pop_back(), solve(), in.push_back(x), res.pop_back(); } if(out.empty()) return; int x = out.back(); in.push_back(x), out.pop_back(), solve(), in.pop_back(), out.push_back(x); } int main(){ int n; scanf("%d", &n); for(int i = n; i >= 1; --i) out.push_back(i); solve(); return 0; }