1052 Linked List Sorting

博客围绕1052 Linked List Sorting展开,主要讲述对列表排序的算法。算法思想上,需用map遍历排除不属于列表的多余结点,将属于列表的元素加到数组中。同时要注意最后一个测试点列表为空,倒数第二个测试点数据量大的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值