POJ2013 ZOJ2172 UVALive3055 Symmetric Order【遞迴+堆疊】
阿新 • • 發佈:2019-01-06
Time Limit:1000MS | Memory Limit:30000K |
Total Submissions:14431 | Accepted:8559 |
Description
In your job at Albatross Circus Management (yes, it's run by a bunch of clowns), you have just finished writing a program whose output is a list of names in nondescending order by length (so that each name is at least as long as the one preceding it). However, your boss does not like the way the output looks, and instead wants the output to appear more symmetric, with the shorter strings at the top and bottom and the longer strings in the middle. His rule is that each pair of names belongs on opposite ends of the list, and the first name in the pair is always in the top part of the list. In the first example set below, Bo and Pat are the first pair, Jean and Kevin the second pair, etc.Input
Output
Sample Input
7 Bo Pat Jean Kevin Claude William Marybeth 6 Jim Ben Zoe Joey Frederick Annabelle 5 John Bill Fran Stan Cece 0
Sample Output
SET 1 Bo Jean Claude Marybeth William Kevin Pat SET 2 Jim Zoe Frederick Annabelle Joey Ben SET 3 John Fran Cece Stan Bill
Source
問題簡述:(略)
問題分析:這個問題是要把輸入的字串改變一個順序輸出,使用遞迴來實現則比較方便。遞迴函式把先輸入後輸出的的字串暫時儲存在變數中,等處理完其他的字串,再輸出先輸入的字串。
可以用遞迴實現的功能,往往也可以用堆疊來實現。
程式說明:(略)
給出兩個程式,一個是用堆疊實現,另外一個是用遞迴實現。
題記:(略)
參考連結:(略)
AC的C++語言程式如下(堆疊):
/* POJ2013 ZOJ2172 UVALive3055 Symmetric Order */
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
int n, caseno = 0;
string s;
while(cin >> n && n) {
stack<string> stk;
cout << "SET " << ++caseno << endl;
while(n) {
cin >> s;
cout << s << endl;
if(--n) {
cin >> s;
stk.push(s);
n--;
}
}
while(!stk.empty()) {
cout << stk.top() << endl;
stk.pop();
}
}
return 0;
}
AC的C++語言程式如下(遞迴):
/* POJ2013 ZOJ2172 UVALive3055 Symmetric Order */
#include <iostream>
using namespace std;
void print(int n)
{
string s;
cin >> s;
cout << s << endl;
if(--n) {
cin >> s;
if(--n)
print(n);
cout << s << endl;
}
}
int main()
{
int n, caseno = 0;
while(cin >> n && n) {
cout << "SET " << ++caseno << endl;
print(n);
}
return 0;
}