PAT A1052 Linked List Sorting
Sample Input:
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
Sample Output:
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
-
思路1:
同1032,在静态链表中设置标记位,并先后以标记位(筛选出有效节点),data(使有效节点排序)排序 -
code1:
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 100010;
struct Node{
int address, data, next;
bool flag;
}node[maxn];
bool cmp(Node a, Node b){
if(a.flag == false || b.flag == false)
return a.flag > b.flag;
else
return a.data < b.data;
}
int main(){
// //初始化:
for(int i = 0; i < maxn; ++i)
node[i].flag = false;
int n, s, pos;
scanf("%d%d", &n, &s);
// int pos, data, next;
for(int i = 0; i < n; ++i){
// scanf("%d%d%d", &pos, &data, &next);
// node[pos].address = pos;
// node[pos].data = data;
// node[pos].next = next;
scanf("%d", &pos);
scanf("%d%d", &node[pos].data, &node[pos].next);
node[pos].address = pos;
}
int count = 0;
while(s != -1){
count++;
node[s].flag = true;
s = node[s].next;
}
// printf("%d", count);
if(count == 0)
//特殊情况:没有有效节点,链表位空
printf("0 -1");
else{
sort(node, node+maxn, cmp);
for(int i = 1; i <= count; ++i){
node[i-1].next = node[i].address;
}
node[count-1].next = -1;
printf("%d %05d\n", count, node[0].address);
//注意!!:输出第一行的5是指有效节点数即count,而不是总节点数n
for(int i = 0; i < count-1; ++i){
printf("%05d %d %05d\n", node[i].address, node[i].data,
node[i].next);
}
printf("%05d %d -1", node[count-1].address, node[count-1].data);
}
return 0;
}
- 思路:链表模板 + 下标排序
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
struct Node{
int data, next;
}node[maxn];
void Print(vector<int> v){
int last = v.size() - 1;
if(last < 0) printf("0 -1"); //Wrong 1:样例4
else{
printf("%d %05d\n", v.size(), v[0]);
for(int i = 0; i < v.size()-1; ++i){
printf("%05d %d %05d\n", v[i], node[v[i]].data, v[i+1]);
}
printf("%05d %d -1", v[last], node[v[last]].data);
}
}
bool cmp(int a, int b){
return node[a].data < node[b].data;
}
int main(){
int n, head;
scanf("%d %d", &n, &head);
for(int i = 0; i < n; ++i){
int t_add;
scanf("%d", &t_add);
scanf("%d %d", &node[t_add].data, &node[t_add].next);
}
vector<int> ans;
while(head != -1){
ans.push_back(head);
head = node[head].next;
}
sort(ans.begin(), ans.end(), cmp);
Print(ans);
return 0;
}