poj 2013 Symmetric Order 解题报告

时间:2023-03-09 23:44:31
poj 2013 Symmetric Order 解题报告

题目链接:http://poj.org/problem?id=2013

设长度非递减的字串序列为s[1]...s[n]。设计递归子程序print(n),其中n为字串序号,每分析1个字串,n=n-1。 n = 0 为边界。字串s为局部变量:

  先输入和输出当前组的第1个字串s,n = n - 1;

若n > 0,则输入当前组的第2个字符s,n = n - 1。若n > 0,则通过递归调用print(n)将字串s入栈。回溯过程相当于栈顶字串s出栈,因此直接输出s。

 #include <iostream>
#include <string>
using namespace std; void print(int n) // 输入n个字串,并按对称格式输出
{
string s; // 当前字串
cin >> s; // 输入和输出当前组的第1个字串
cout << s << endl;
if (--n)
{
cin >> s; // 输入当前组的第2个字串并通过递归压入系统栈区
if (--n)
{
print(n);
}
cout << s << endl; // 回溯,栈首字串出栈后输出
}
} int main()
{
int n, loop = ; // 字串集合序号初始化
while (cin >> n && n)
{
printf("SET %d\n", ++loop);
print(n); // 按照对称格式输出当前字串集合中的n个字串
}
return ;
}

不用递归也可以。对称的输出形式由两部分组成:

  上半部分由自上而下的奇数行组成:

s[1]

s[3]

s[5]

......

n 为奇数时为s[n],n为偶数时为s[n-1]

即执行语句 "for (int i = 1; i <= n; i += 2)    cout << s[i] << endl; "

下半部分由自下而上的偶数行组成:

s[n - (n%2)]

s[n - (n%2) - 2]

  s[n -  (n%2) - 4]

......

  s[2]

即执行语句" for (int  i = n - (n%2); i > 1; i -= 2)  cout << s[i] << endl; "。