PAT 1062 Talent and Virtue

这一题是比较简单的排序题,难点在于如何对 sage、nobleman、fool men进行排序。一开始我的想法是用多个数组进行分别存储,但是操作起来就变得繁琐,于是我看了别人的解法,设置标志就能轻松解决。

算法步骤:

  1. 建立结构体
  2. 编写比较函数(注意对标志进行比较)
  3. 将输入数据存储到结构体数组中
  4. 同时对每一条数据设置标记
  5. 对数组进行排序
  6. 输出符合条件的数据

在设置标记的过程中,我写的方法比较繁琐,而网上的标志设置过程中明显是有技巧的,首先把不符合条件数据筛选出来。

方法:

if(virtue<lowGrade||talent<lowGrade){
            people[i].flag = 5;
            cnt++;
        }else if(virtue>=highGrade&&talent>=highGrade){
            people[i].flag = 1;
        }else if(virtue>=highGrade&&talent<highGrade){
            people[i].flag = 2;
        }else if(virtue>=talent){
            people[i].flag = 3;
        }else {
            people[i].flag = 4;
        }

代码如下

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

struct person{
    char name[10];
    int virtue;
    int talent;
    int total;
    int flag;
} people[100005];

bool cmp(person a,person b){
    if(a.flag!=b.flag){
        return a.flag < b.flag;
    }else if(a.total!=b.total){
        return a.total > b.total;
    }else if(a.virtue!=b.virtue){
        return a.virtue > b.virtue;
    }else{
        int s = strcmp(a.name, b.name);
        return s < 0;
    }
}

int main(){
    int n, lowGrade, highGrade;
    scanf("%d %d %d", &n, &lowGrade, &highGrade);
    int cnt = 0;
    for (int i = 0; i < n;i++){
        scanf("%s %d %d", people[i].name, &people[i].virtue, &people[i].talent);
        people[i].total = people[i].virtue + people[i].talent;
        int virtue = people[i].virtue;
        int talent = people[i].talent;
        if(virtue<lowGrade||talent<lowGrade){
            people[i].flag = 5;
            cnt++;
        }else if(virtue>=highGrade&&talent>=highGrade){
            people[i].flag = 1;
        }else if(virtue>=highGrade&&talent<highGrade){
            people[i].flag = 2;
        }else if(virtue>=talent){
            people[i].flag = 3;
        }else {
            people[i].flag = 4;
        }
    }
    sort(people, people + n, cmp);
    int total = n - cnt;
    printf("%d\n", total);
    for (int i = 0; i < total;i++){
        printf("%s %d %d\n", people[i].name, people[i].virtue, people[i].talent);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值