程序员

PAT Basic 1055. 集体照 (25)(C语言实现)

2017-05-04  本文已影响437人  OliverLew

我的PAT系列文章更新重心已移至Github,欢迎来看PAT题解的小伙伴请到Github Pages浏览最新内容。此处文章目前已更新至与Github Pages同步。欢迎star我的repo

题目

拍集体照时队形很重要,这里对给定的 N 个人 K 排的队形设计排队规则如下:

现给定一组拍照人,请编写程序输出他们的队形。

输入格式:

每个输入包含 1 个测试用例。每个测试用例第 1 行给出两个正整数 N\le 10^4 ,总人数)和 K\le 10
,总排数)。随后 N 行,每行给出一个人的名字(不包含空格、长度不超过 8 个英文字母)和身高([30, 300] 区间内的整数)。

输出格式:

输出拍照的队形。即K排人名,其间以空格分隔,行末不得有多余空格。注意:假设你面对拍照者,后排的人输出在上方,前排输出在下方。

输入样例:

10 3
Tom 188
Mike 170
Eva 168
Tim 160
Joe 190
Ann 168
Bob 175
Nick 186
Amy 160
John 159

输出样例:

Bob Tom Joe Nick
Ann Mike Eva
Tim Amy John

思路

代码

最新代码@github,欢迎交流

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct student{
    char name[9];
    int height;
}student, *Student;

int cmp(const void *a, const void *b)
{
    Student s1 = *(Student*)a;
    Student s2 = *(Student*)b;
    if(s1->height != s2->height)
        return s2->height - s1->height;
    return strcmp(s1->name, s2->name);
}

/**
 * Print one row
 * Return the address of the beginning of next line
 **/
Student *printrow(Student *s, int num)
{
    for(int i = num / 2 * 2 - 1; i > 0; i -= 2)  /* the left half */
        printf("%s ", s[i]->name);
    for(int i = 0; i < num; i += 2)              /* the right half */
        printf("%s%c", s[i]->name, i + 2 < num ? ' ' : '\n');
    return s + num;
}

int main()
{
    /* read and sort data */
    int N, K;
    student students[10000] = {0};
    Student sp[10000] = {0}, *p = sp;

    scanf("%d %d", &N, &K);
    for(int i = 0; i < N; i++)
    {
        sp[i] = students + i;
        scanf("%s %d", sp[i]->name, &sp[i]->height);
    }

    qsort(sp, N, sizeof(Student), cmp);

    /* print */
    p = printrow(p, N - N / K * (K - 1));   /* the last row */
    while(p < sp + N)
        p = printrow(p, N / K);

    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读