PAT A 1055 The World's Richest (25分)

一、思路

将全部记录按要求排序;
对于每个请求,遍历全表,若年龄符合要求则输出,注意输出不多于M个,且输出为0时输出None;
测试点2超时:使用scanf()、printf()输入输出;

二、代码

#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct
{
    string name;
    int age, w;
}person;
int cmp( person a, person b )
{
    if( a.w != b.w )
        return a.w > b.w;
    else if( a.age != b.age )
        return a.age < b.age;
    else return a.name < b.name;
}
int main()
{
    int N, K;
    scanf("%d %d", &N, &K);
    vector<person> rec(N);
    for( int i = 0; i < N; ++i )
    {
        rec[i].name.resize(8);
        scanf("%s %d %d", &rec[i].name[0], &rec[i].age, &rec[i].w);
    }
    sort( rec.begin(), rec.end(), cmp );
    for( int i = 0, M, min, max; i < K; ++i )
    {
        scanf("%d %d %d", &M, &min, &max);
        printf("Case #%d:\n", i + 1);
        int cnt = 0;
        for( int j = 0; j < N && cnt < M; ++j )
            if( rec[j].age >= min && rec[j].age <= max )
            {
                ++cnt;
                printf("%s %d %d\n", rec[j].name.c_str(), rec[j].age, rec[j].w);
            }
        if( !cnt )
            printf("None\n");
    }
}

发布了152 篇原创文章 · 获赞 144 · 访问量 9213

猜你喜欢

转载自blog.csdn.net/qq_43749739/article/details/103944876