对称排序(包含结构体,以及sort中的comp,字符串数组,以及字符串数组按长度排序等内容)

对称排序

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 1
描述
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, NOT SORTED. 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.
If length of two strings is equal,arrange them as the original order.(HINT: StableSort recommanded)
样例输入
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

不用看题了,直接看输入和输出

需要注意的题意中的一点是:首先应该把这些字符串排成由小到大的顺序,然后再对这些由小到大的字符串进行对称排序

不要因为样例中给出的输入就是从小到大排好的,就不用写程序进行排序了,可是不是所有输入都是从小到大排好的,输入是可以随便输的,样例只是为了说明对称排序的规则而已。所以要先对这些数组进行从小到大的排序。

代码:

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
struct f//定义结构体含两个变量,字符串的长度和字符串
{
    int length;
    char a[30];
}s[17];
int cmp(struct f a,struct f b)//对结构体中的字符串部分进行排序
{
    if(a.length<b.length)
        return 1;
    return 0;
}
int main()
{
    int n,i,k=1;
    while(~scanf("%d",&n)&&n)
    {
        printf("SET %d\n",k++);
        for(i=0;i<n;i++)
        {
            scanf("%s",s[i].a);//向结构体输入字符串并将其长度也存入结构体
            s[i].length=strlen(s[i].a);
        }
        sort(s,s+n,cmp);
        for(i=0;i<n;i++)//以下两个for循环为对称排序的实现,先正着输偶(从0开始),再倒着输奇
            if(i%2==0)
                printf("%s\n",s[i].a);
        for(i=n-1;i>=0;i--)
            if(i&1)
            printf("%s\n",s[i].a);
    }
    return 0;
}

注意;

基础知识:

(观察表达)

 for(i=0;i<n;i++)
        {
            scanf("%s",s[i].a);//向结构体输入字符串并将其长度也存入结构体
            s[i].length=strlen(s[i].a);
        }

猜你喜欢

转载自blog.csdn.net/nanfengzhiwoxin/article/details/80189746