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。

   

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 void print(int n)      // 输入n个字串,并按对称格式输出
 6 {
 7     string s;      // 当前字串
 8     cin >> s;    // 输入和输出当前组的第1个字串
 9     cout << s << endl;
10     if (--n)
11     {
12         cin >> s;     // 输入当前组的第2个字串并通过递归压入系统栈区
13         if (--n)
14         {
15             print(n);
16         }
17         cout << s << endl;      // 回溯,栈首字串出栈后输出
18     }
19 }
20 
21 int main()
22 {
23     int n, loop = 0;      // 字串集合序号初始化
24     while (cin >> n && n)     
25     {
26         printf("SET %d\n", ++loop);
27         print(n);      // 按照对称格式输出当前字串集合中的n个字串
28     }
29     return 0;
30 } 


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

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

      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; "。

原文地址:https://www.cnblogs.com/windysai/p/3231430.html