POJ 2013 Symmetric Order (递归做法)
| Describe: |
| 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: |
| The input consists of one or more sets of strings, followed by a final line containing only the value 0. Each set starts with a line containing an integer, n, which is the number of strings in the set, followed by n strings, one per line, sorted in nondescending order by length. None of the strings contain spaces. There is at least one and no more than 15 strings per set. Each string is at most 25 characters long. |
| Output: |
| For each input set print "SET n" on a line, where n starts at 1, followed by the output set as shown in the sample 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 |
题目传送门: POJ 2013
题目大意:输入是一些长度为非递减的字符串,让你把这些字符串按照对称的方式输出,就是长度最短的,输出的位置应该在第一行和最后一行(英语不好,翻译能力有限)。
输入有多个测试用例,每个用例第一行给出一个整数n,n为0时程序结束,接下来n行是字符串,长度不超过25,n不超过15。
解题思路:
递归方法:
可以把输入的字符串,分为两个一组,比如s[0]和s[1]是一组,s[2]和s[3]是一组。。。。 对于每一组,首先输入这一组第一个,然后输出,如果这一组还有第二个(有可能出现一组只有一个的情况,比如n是奇数的话)就输入,入栈,递归去找下一组,最后,一个接一个出栈,并输出。
AC代码如下:
1 #include <stdio.h> 2 #include <iostream> 3 #include <cstring> 4 using namespace std; 5 int n; 6 int cnt = 0; 7 char s[15][30]; 8 void print(int i) //函数参数是数组下标,从零开始 print(0); 9 { 10 // 下面的为一组,或者一对名字,如果n>0,先输入这组的第一个并输出 11 // 这组的第二个,在输出前开始递归,去操作第二组 12 if(n>0) 13 { 14 printf("%s\n",s[i]); 15 n--; 16 i++; 17 } 18 if(n > 0) 19 { 20 n--; // 注意这里,没有i++,以为上面的条件判断已经加过 21 print(i+1); // 这里要去找下一组,需要加一,不要++,加一就好 22 printf("%s\n",s[i]); 23 } 24 if(n == 0) return; 25 } 26 int main() 27 { 28 while(~scanf("%d",&n) && n) // 注意输入条件,n不为0 29 { 30 for(int i = 0; i < n; i++) scanf("%s",s[i]);//提前输入,存入数组 31 printf("SET %d\n",++cnt); // 按要求打印 32 print(0); // 进入递归函数 33 } 34 return 0; 35 }
另:
另一种非递归做法思路与此类似,都是交替输出,先把对称的上半部分输出,下标是奇数,然后再把对称的下半部分输出,代码有机会再补上。
(第一篇博客)
2020/8/3 9:40

浙公网安备 33010602011771号