日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

【附段错误原因,最后两个测试点】1052 Linked List Sorting (25 分)【链表类题目总结】

發(fā)布時間:2024/2/28 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【附段错误原因,最后两个测试点】1052 Linked List Sorting (25 分)【链表类题目总结】 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

立志用最少的代碼做最高效的表達


PAT甲級最優(yōu)題解——>傳送門


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 [?10^5,10^5], 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


題意:給定一些節(jié)點,要求將鏈表按值升序排序并輸出。

鏈表類型題總結(jié)(適用所有鏈表題):
1. 一定要將鏈表構(gòu)造出來再進行操作,因為樣例中有很多無效節(jié)點。
2. 考慮頭結(jié)點為-1的情況
3. 輸出單一頭結(jié)點時注意頭結(jié)點的也要使用%05d


#include<bits/stdc++.h> using namespace std; struct lnode{int value = 0, next = -1; }node[100010];bool cmp(int x1, int x2) {return node[x1].value < node[x2].value; }int main() {int n, fir; scanf("%d%d", &n, &fir);//頭結(jié)點為-1的特殊情況 if(fir == -1) { printf("0 -1\n"); return 0; }//構(gòu)建鏈表。這一步的目的是去除無效節(jié)點。 for(int i = 0; i < n; i++) {int x; cin >> x;cin >> node[x].value >> node[x].next;}//遍歷鏈表,將鏈表中的節(jié)點壓入vector。 //注意這里只存儲地址即可。因為可以通過地址找到value vector<int>v;while(fir != -1) {v.push_back(fir); //只存儲地址即可。fir = node[fir].next;}sort(v.begin(), v.end(), cmp);int len = v.size();//注意這里頭結(jié)點的輸出也要用%05d,別忘了 printf("%d %05d\n", len, v[0]);for(int i = 0; i < len-1; i++) printf("%05d %d %05d\n", v[i], node[v[i]].value, v[i+1]);printf("%05d %d -1\n", v[len-1], node[v[len-1]].value);return 0; }

耗時:


求贊哦~ (?ω?)

總結(jié)

以上是生活随笔為你收集整理的【附段错误原因,最后两个测试点】1052 Linked List Sorting (25 分)【链表类题目总结】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。