PAT甲级-排序类型-1062 Talent and Virtue解题思路

1062 Talent and Virtue (25 分)

在这里插入图片描述
在这里插入图片描述

思路

这题的文言文给我看懵了,排来排去的
核心就是sort排序,需要提前分组,我针对四个类型开了四个数组,其实可以再struct里面加个flag标记不同组,进行分类,代码可以更简洁。

代码

#include<bits/stdc++.h>
using namespace std;

struct stu{

    int id;
    int vir,tal;
    int sum;
}good1[100005],good2[100005],good3[100005],good4[100005];

bool cmp(stu a,stu b)//int为数组数据类型
{
    if(a.sum !=b.sum)return a.sum>b.sum;//降序排列
    else if(a.vir !=b.vir)return a.vir>b.vir;
    else return a.id<b.id;
//return a<b;//默认的升序排列
}
//输入先分好类 再调用sort进行排序
int main()
{
    int id,n,grade1,grade2;
    cin>>n>>grade1>>grade2;

    int n1=0,n2=0,n3=0,n4=0;
    int g1,g2;
    int abc = n;
    for(int i=0;i<n;i++)
    {
        cin>>id>>g1>>g2;
        if(g1<grade1 || g2<grade1)
        {   
            abc--;
            continue;     
        }

        else if(g1>=grade2 && g2>=grade2)
        {
            good1[n1].id = id;
            good1[n1].vir = g1;
            good1[n1].tal = g2;
            good1[n1++].sum = g1 +g2;
        }
        else if(g1>=grade2  && g2<grade2)
        {
            good2[n2].id = id;
            good2[n2].vir = g1;
            good2[n2].tal = g2;
            good2[n2++].sum = g1 +g2;
        }
        else if(g1<grade2 && g1>=g2 && g2<grade2)
        {
            good3[n3].id = id;
            good3[n3].vir = g1;
            good3[n3].tal = g2;
            good3[n3++].sum = g1 +g2;
        }
        else 
        {
            good4[n4].id = id;
            good4[n4].vir = g1;
            good4[n4].tal = g2;
            good4[n4++].sum = g1 +g2;
        }
    }
    sort(good1,good1+n1,cmp);
    sort(good2,good2+n2,cmp);
    sort(good3,good3+n3,cmp);
    sort(good4,good4+n4,cmp);

    cout<<abc<<endl;
    for(int i =0;i<n1;i++)
        cout<<good1[i].id<<" "<<good1[i].vir<<" "<<good1[i].tal<<endl;
    for(int i =0;i<n2;i++)
        cout<<good2[i].id<<" "<<good2[i].vir<<" "<<good2[i].tal<<endl;
    for(int i =0;i<n3;i++)
            cout<<good3[i].id<<" "<<good3[i].vir<<" "<<good3[i].tal<<endl;
    for(int i =0;i<n4;i++)
            cout<<good4[i].id<<" "<<good4[i].vir<<" "<<good4[i].tal<<endl;


    
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页