PAT甲级 1028 List Sorting (25分)

1028 List Sorting (25分)

题目链接:PAT A 1028
在这里插入图片描述
在这里插入图片描述

题目大意:题目输入一个数n为学生个数,对于每个学生,给出他们的id,名字以及成绩。输入一个c代表行数,即我们需要排序的行数。如果c为1,则按照id升序排列,如果c为2,则按照名字字母序升序排列,如果名字相同,按照id升序排列,如果c为3,按照成绩升序排列,如果成绩相同,按照id升序排列。

思路分析:很简单的排序题,写好cmp函数就可以了。需要注意的是如果用字符串存储的话,用cin,cout输入输出会导致最后一组数据超时。把cout改为printf即可(printf可以输出字符串,需要加上.c_str())。这样用时将为300ms左右,如果时间限制为200ms,则不能使用string,需要使用字符数组char,然后用strcmp函数进行比较~

AC代码:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct stu{
	string id, name;
	int score;
};
int n, c;
bool cmp(stu a, stu b) {
	if(c == 1) {
		return a.id < b.id;
	}
	else if(c == 2) {
		if(a.name != b.name) //名字不同按名字升序排列 
			return a.name < b.name;
		else //名字相同按id升序排列 
			return a.id < b.id;
	}
	else if(c == 3) {
		if(a.score != b.score) //分数不同按分数升序排列 
			return a.score < b.score;
		else //分数相同按id升序排列 
			return a.id < b.id;
	}
}
int main() {
	cin >> n >> c;
	vector<stu> v(n);
	for(int i = 0; i < n; i++) 
		cin >> v[i].id >> v[i].name >> v[i].score;
	sort(v.begin(), v.end(), cmp);
	for(int i = 0; i < n; i++) 
		printf("%s %s %d\n", v[i].id.c_str(), v[i].name.c_str(), v[i].score);
	return 0;
}

ps:如果时间限制为200ms,代码如下:

#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
const int maxn = 100001;
struct NODE {
    int no, score;
    char name[10];
}node[maxn];
int c;
int cmp1(NODE a, NODE b) {
    if(c == 1) {
        return a.no < b.no;
    } else if(c == 2) {
        if(strcmp(a.name, b.name) == 0) return a.no < b.no;
        return strcmp(a.name, b.name) < 0;
    } else {
        if(a.score == b.score) return a.no < b.no;
        return a.score < b.score;
    }
}
int main() {
    int n;
    scanf("%d%d", &n, &c);
    for(int i = 0; i < n; i++)
        scanf("%d %s %d", &node[i].no, node[i].name, &node[i].score);
    sort(node, node + n, cmp1);
    for(int i = 0; i < n; i++)
        printf("%06d %s %d\n", node[i].no, node[i].name, node[i].score);
    return 0;
}

时间在100ms以内

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值