【PTA/乙级】【1075】链表元素分类 (25 分)

使得所有负值元素都排在非负值元素的前面,而 [0, K] 区间内的元素都排在大于 K 的元素前面。但每一类内部元素的顺序是不能改变的。

使用使用自己定义的ran,确立优先级。优先级大的在前面,优先级相同按原来次序排列。代码中order表示链表序,ran表示题意要求顺序。

(发现pta链表全是排序题

测试样例:

00100 9 10
23333 10 27777
00000 0 99999
00100 18 12309
68237 -6 23333
33218 -4 00000
48652 -2 -1
99999 5 68237
27777 11 48652
12309 7 33218

样例输出:

33218 -4 68237
68237 -6 48652
48652 -2 12309
12309 7 00000
00000 0 99999
99999 5 23333
23333 10 00100
00100 18 27777
27777 11 -1

AC代码:

#include<iostream>
#include<iomanip>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 1e6 + 5;
#define inf 0x3f3f3f3f

struct node {
	int addr, data, next;
	int order = inf;
	int ran = -inf;

	//使用自己定义的ran确立优先级
	bool operator<(const node& t) const {
		if (ran != t.ran) //优先级大的在前面
			return ran > t.ran;
		return order < t.order; //优先级相同按原来次序排列
	}
}L[N];

int main()
{
	int h, n, k;
	cin >> h >> n >> k;
	for (int i = 0; i < n; i++) { //读入数据
		int addr;
		cin >> addr;
		cin >> L[addr].data >> L[addr].next;
		L[addr].addr = addr;
	}

	int tot = 0;
	while (h != -1) { //顺序遍历链表并按题意确定优先级
		tot++;
		L[h].order = tot;
		if (L[h].data < 0) {
			L[h].ran = 3;
		}
		else if (L[h].data >= 0 && L[h].data <= k) {
			L[h].ran = 2;
		}
		else
			L[h].ran = 1;

		h = L[h].next;
	}

	//注意排序要对五位数可能包含的所有范围排序
	sort(L, L + N);
	for (int i = 0; i < tot; i++) {
		if (i != tot - 1) {
			cout << setw(5) << setfill('0') << L[i].addr << ' ' << L[i].data << ' ' << setw(5) << setfill('0') << L[i + 1].addr << endl;
		}
		else
			cout << setw(5) << setfill('0') << L[i].addr << ' ' << L[i].data << ' ' << -1 << endl;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sophon、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值