1052. Linked List Sorting (25)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
A linked list consists ofa series of structures, which are not necessarily adjacent in memory. We assume that each structure containsaninteger key anda Next pointer tothe next structure. Now given a linked list, you are supposed tosortthe structures according to their key values in increasing order.
Input Specification:
Each input filecontainsone test case. For eachcase, thefirstlinecontainsa positive N (< 105) andan address ofthe head node, where N is the total numberof nodes in memory andthe address ofa node is a5-digit positive integer. NULL is represented by -1.
Then N lines follow, each describes a node intheformat:
Address Key Next
where Address is the address ofthe node in memory, Key is anintegerin [-105, 105], and Next is the address ofthe next node. It is guaranteed that all thekeys are distinct and there is no cycle inthe linked list starting fromthe head node.
Output Specification:
For each test case, the output format is the same as that ofthe input, where N is the total numberof nodes inthe list and all the nodes must be sorted order.
Sample Input:
50000111111100 -100001022222333331000001111112345 -13333322222100012345
Sample Output:
51234512345 -1000010000101111111111100222222222210003333333333100000 -1
解题思路
1.先根据头地址保存这个链表所有有效的队列,然后在排序就行了。
2.输出的时候要注意保存的链表为空的情况。
代码
#include<iostream>#include<cstdio>#include<algorithm>#include<vector>usingnamespacestd;
int nx[99999],va[99999];
struct node{
int ad,v;
node(){}
node(int _ad,int _v){
this->ad = _ad;
this->v = _v;
}
};
bool cmp(const node &a, const node &b){
return a.v<b.v;
}
int main(int argc, char *argv[])
{
int n,f;
scanf("%d %d",&n,&f);
vector<node> b;
int tem_a,tem_b,tem_c;
for (int i = 0; i < n; ++i) {
scanf("%d %d %d",&tem_a,&tem_b,&tem_c);
nx[tem_a] = tem_c;
va[tem_a] = tem_b;
}
//将有效的链表存好int now = f;
while (now != -1) {
b.push_back(node(now,va[now]));
now = nx[now];
}
//输出if (!b.empty()) {
sort(b.begin(),b.end(),cmp);
printf("%d %05d\n",b.size(),b[0].ad);
for (int i = 0; i < b.size()-1; ++i) {
printf("%05d %d %05d\n",b[i].ad,b[i].v,b[i+1].ad);
}
printf("%05d %d %d\n",b[b.size()-1].ad,b[b.size()-1].v,-1);
}else {
printf("%d %d\n",0,-1);
}
return0;
}
题目1052. Linked List Sorting (25)时间限制400 ms内存限制65536 kB代码长度限制16000 B判题程序Standard作者CHEN, YueA linked list consists of a series of structures, which are not necessarily adjacent in memory. We as