PAT (Advanced) 1052. Linked List Sorting (25)

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Node
{
	int addr, key, next;
}node[100000];

vector<Node> listNode;

bool cmp(const Node &a, const Node &b)
{
	return a.key < b.key;
}

int main()
{
//	freopen("in.txt", "r", stdin);
	int n, start;
	cin >> n >> start;
	if (start == -1)
	{
		cout << "0 -1" << endl;
		return 0;
	}
	int Address, Key, Next;
	for (int i = 0; i < n; i++)
	{
		cin >> Address >> Key >> Next;
		node[Address].addr = Address;
		node[Address].key = Key;
		node[Address].next = Next;
	}
	int cnt = 0;
	int cur = start;
	do
	{
		cnt++;
		listNode.push_back(node[cur]);
		cur = node[cur].next;
	} while (cur != -1);
	
	sort(listNode.begin(), listNode.end(), cmp);
	printf("%d %05d\n", cnt, listNode[0].addr);
	for (int i = 0; i < cnt - 1; i++)
		printf("%05d %d %05d\n", listNode[i].addr, listNode[i].key, listNode[i + 1].addr);
	printf("%05d %d -1\n", listNode[cnt - 1].addr, listNode[cnt - 1].key);

	return 0;
}


再贴一个之前的代码,不知道为什么有几个测试点不能过。留此存照。以后再来仔细看看。

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>

using namespace std;

struct Node
{
	int key, next;
}node[100005];

int main()
{
	freopen("in.txt", "r", stdin);
	int n, start;
	cin >> n >> start;
	if (start == -1)
	{
		cout << "0 -1" << endl;
		return 0;
	}
	int Address, Key, Next;
	for (int i = 0; i < n; i++)
	{
		scanf("%d %d %d", &Address, &Key, &Next);
	//	cin >> Address >> Key >> Next;
		node[Address].key = Key;
		node[Address].next = Next;
	}
	int cur = start;
	int next = node[cur].next;
	int cnt = 0;
	while (cur != -1)
	{
		cnt++;
		if (node[cur].key < node[next].key)
		{
			cur = next;
			next = node[cur].next;
		}
		else
		{
			node[cur].next = node[next].next;
			if (node[start].key > node[next].key)
			{
				node[next].next = start;
				start = next;
			}
			else
			{
				int pos = start;
				while (node[next].key > node[node[pos].next].key)
					pos = node[pos].next;
				node[next].next = node[pos].next;
				node[pos].next = next;
			}
			cur = node[cur].next;
			next = node[cur].next;
		}
	}
	printf("%d %05d\n", cnt, start);
	do
	{
		printf((node[start].next != -1 ? "%05d %d %05d\n" : "%05d %d %d\n"), start, node[start].key, node[start].next);
		start = node[start].next;
	} while (start != -1);

	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值