PAT A 甲级 1052 Linked List Sorting (25分)

1052 Linked List Sorting (25分)

吐槽

我最怕的就是用时极限的题目。不仅难想,而且凡改必大改,极度耗时。

思路

本题的主干部分非常简单,就是个排序。重点是超时问题以及大量没有明说的测点问题。

先说明测点问题,因为超时问题中有一部分是测点导致的。
首先,仅从题目来看,input中的“next”似乎是没用的——反正后面也要按key重新排序。然而实际上,这是有用的——有些数据并不在从给定的head开头的链上,且它们也不应被连入链和在之后输出。

超时问题使用的是……空间换时间的基操。node[100000]而不是vector。但是发生了一件玄妙的事:同样是node[100000],我在结构体后面直接定义可以通过,但在main函数里定义程序就会在定义这一步直接卡死。可能和局部变量全局变量的空间分配有关吧大概。

然后还有一个测点——最后一个。这个点的head是-1,也就是NULL。所以链上没有节点,应该直接输出“0 -1”。

代码

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

struct Node{
	int id;
	int key;
	int next;
	bool in = false;
}node[100000];

bool cmp(Node n1, Node n2)
{
	if (n1.in && !n2.in)
		return true;
	else if (n1.in && n2.in)
		return n1.key < n2.key;
	else
		return false;
}

int main()
{
	int n, i;
	int temp;
	int head;
	cin >> n >> head;
	for (i = 0; i < n; i++)
	{
		cin >> temp;
		node[temp].id = temp;
		cin >> node[temp].key >> node[temp].next;
	}
	if (head == -1)
	{
		cout << "0 -1";
		return 0;
	}
	temp = 0;
	while (head != -1)
	{
		node[head].in = true;
		temp++;
		head = node[head].next;
	}
	sort(node, node + 100000, cmp);
	printf("%d %05d\n", temp, node[0].id);
	for (i = 0; i < temp - 1 ; i++)
	{
		printf("%05d %d %05d\n", node[i].id, node[i].key, node[i + 1].id);
	}
	printf("%05d %d -1", node[i].id, node[i].key);
	cin >> i;
	return 0;
}

题目

A linked list consists of a series of structures, which are not necessarily adjacent in memory. We assume that each structure contains an integer key and a Next pointer to the next structure. Now given a linked list, you are supposed to sort the structures according to their key values in increasing order.

Input Specification:
Each input file contains one test case. For each case, the first line contains a positive N (<10​5) and an address of the head node, where N is the total number of nodes in memory and the address of a node is a 5-digit positive integer. NULL is represented by −1.

Then N lines follow, each describes a node in the format:

Address Key Next

where Address is the address of the node in memory, Key is an integer in [−105,105], and Next is the address of the next node. It is guaranteed that all the keys are distinct and there is no cycle in the linked list starting from the head node.

Output Specification:
For each test case, the output format is the same as that of the input, where N is the total number of nodes in the list and all the nodes must be sorted order.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值