链接:http://poj.org/problem?id=2013
题目描述:
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.
输入描述:
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.
输出描述:
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.
输入样例:
7
Bo
Pat
Jean
Kevin
Claude
William
Marybeth
6
Jim
Ben
Zoe
Joey
Frederick
Annabelle
5
John
Bill
Fran
Stan
Cece
0
输出样例:
SET 1
Bo
Jean
Claude
Marybeth
William
Kevin
Pat
SET 2
Jim
Zoe
Frederick
Annabelle
Joey
Ben
SET 3
John
Fran
Cece
Stan
Bill
题意:
输入长度顺序排列的名称列表
输出看起来更对称,顶部和底部的字符串越短,中间的字符串越长。
每对名字都属于列表的两端,而这对名字中的第一个总是在列表的顶部。
数据范围:
没有字符串包含空格。每组至少有一个且不超过15个字符串。每个字符串最多25个字符。
思路:
1.递归:
将名字分为t/2个组
先输入第一组第一个名字,并输出
如果第一组有第二个名字,输入第二个名字
如果还有下一组,递归下一组
2.非递归:
在输入时将所有字符串分两组
m组存放每对名字的第一个,n组存放每对名字的第二个
先正序输出m组,再倒序输出n组
递归代码:
#include<iostream>
#include<string>
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 k = 1,t;
while(scanf("%d",&t)&&t)
{
printf("SET %d\n",k++);
print(t);
}
return 0;
}
非递归代码:
#include<stdio.h>
#include<string.h>
int main()
{
int t,k = 1;;
while(scanf("%d",&t)&&t)
{
char m[20][30],n[20][30];
for(int i = 0;i < t;i++)
{
if(i%2 == 0)
scanf("%s",m[i/2]);
else
scanf("%s",n[i/2]);
}
int q,p = t/2-1;
if(t%2 == 1)
q = t/2+1;
else
q = t/2;
printf("SET %d\n",k++);
for(int i = 0;i < q;i++)
printf("%s\n",m[i]);
for(int i = p;i >= 0;i--)
printf("%s\n",n[i]);
}
return 0;
}