“使得所有负值元素都排在非负值元素的前面,而 [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;
}