1052 Linked List Sorting
题目大意
对列表进行排序,但是坑非常难
算法思想
- 注意有多余的结点,不属于列表,需要排除,可以先用map遍历,将属于列表的元素加到数组中
- 注意最后一个测试点是列表为空
- 注意倒数第二个测试点数据量非常大
代码
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
struct node {
string address, Next;
int key;
bool operator< (const node& t) const//按从小到大,如果用cmp会超时
{
return key < t.key;
}
};
int n, x, i;
string head,ad, e;
map<string, node>all;
int main() {
cin >> n >> head;
vector<node>list;
for (int i = 0; i < n; i++) {
cin >> ad >> x >> e;
all[ad].address = ad;
all[ad].key = x;
all[ad].Next = e;
}
for (e = head; e != "-1"; e = all[e].Next)//将列表元素Push进来
list.push_back(all[e]);
if (list.empty()) {//最后测试点为空
cout << 0 << " " << -1;
return 0;
}
sort(list.begin(), list.end());//排序
cout << list.size() << " " << list[0].address << endl;
for (i = 0; i < list.size()-1; i++)
cout << list[i].address << " " << list[i].key << " " << list[i+1].address << endl;
cout << list[i].address << " " << list[i].key << " -1";
return 0;
}