1097 Deduplication on a Linked List (25 分)_35行代码AC
立志用最少的代碼做最高效的表達(dá)
PAT甲級(jí)最優(yōu)題解——>傳送門
Given a singly linked list L with integer keys, you are supposed to remove the nodes with duplicated absolute values of the keys. That is, for each value K, only the first node of which the value or absolute value of its key equals K will be kept. At the mean time, all the removed nodes must be kept in a separate list. For example, given L being 21→-15→-15→-7→15, you must output 21→-15→-7, and the removed list -15→15.
Input Specification:
Each input file contains one test case. For each case, the first line contains the address of the first node, and a positive N (≤10^?5) which is the total number of nodes. The address of a node is a 5-digit nonnegative integer, and NULL is represented by ?1.
Then N lines follow, each describes a node in the format:
Address Key Next
where Address is the position of the node, Key is an integer of which absolute value is no more than 10^4, and Next is the position of the next node.
Output Specification:
For each case, output the resulting linked list first, then the removed list. Each node occupies a line, and is printed in the same format as in the input.
Sample Input:
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854
Sample Output:
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1
題意:去重鏈表,絕對(duì)值相等的值都算重復(fù)。
具體算法邏輯見(jiàn)代碼。
#include<bits/stdc++.h> using namespace std; int main() {int fir, n;//1、構(gòu)建鏈表 vector<int>add(100010), val(100010);cin >> fir >> n;for(int i = 0; i < n; i++) {int address; cin >> address;cin >> val[address] >> add[address];}//2、篩出無(wú)效節(jié)點(diǎn),將鏈表存入v vector<int>v;unordered_map<int, int>um;while(fir != -1) {v.push_back(fir);fir = add[fir];}//3、遍歷,不重復(fù)的入v1,重復(fù)的入v2 vector<int>v1, v2;for(auto i : v) {if(um[abs(val[i])] == 0) {v1.push_back(i);} else v2.push_back(i);um[abs(val[i])]++;} //若為非空,則輸出。 if(!v1.empty()) {for(int i = 0; i < v1.size()-1; i++) printf("%05d %d %05d\n", v1[i], val[v1[i]], v1[i+1]);printf("%05d %d -1\n", v1[v1.size()-1], val[v1[v1.size()-1]]);}if(!v2.empty()) {for(int i = 0; i < v2.size()-1; i++) printf("%05d %d %05d\n", v2[i], val[v2[i]], v2[i+1]);printf("%05d %d -1\n", v2[v2.size()-1], val[v2[v2.size()-1]]);}return 0; }
耗時(shí):
總結(jié)
以上是生活随笔為你收集整理的1097 Deduplication on a Linked List (25 分)_35行代码AC的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 1096 Consecutive Fac
- 下一篇: 【已解决】width与max-width