A1097 Deduplication on a Linked List (25 point(s))

链表问题

1. 原文

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 Kwill 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:

1
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:

1
2
3
4
5
6
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854

Sample output:

1
2
3
4
5
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1

2. 解析

防断链

1
for (int i = first; i != -1; i=nextAddress[i])

绝对值防重复

1
if (exist[abs(data[i])]==0)

将不重复的值,重复的值放于不同vector中

1
2
3
4
5
6
if (exist[abs(data[i])]==0){
v.push_back(i);
exist[abs(data[i])]++;
}else{
other.push_back(i);
}

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<cstdio>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
map<int,int> address,data,nextAddress,exist;
vector<int> v,other;
int main()
{
int first,n;
scanf("%d%d",&first,&n);
int a;
for (int i = 0; i < n; ++i)
{
scanf("%d",&a);
address[a]=a;
scanf("%d%d",&data[a],&nextAddress[a]);
}
for (int i = first; i != -1; i=nextAddress[i])
{
if (exist[abs(data[i])]==0)
{
v.push_back(i);
exist[abs(data[i])]++;
}else{
other.push_back(i);
}
}
for (int i = 0; i < v.size(); ++i)
{
if (i<v.size()-1)
{
printf("%05d %d %05d\n",address[v[i]],data[v[i]],address[v[i+1]]);
}else{
printf("%05d %d -1\n",address[v[i]],data[v[i]]);
}
}
for (int i = 0; i < other.size(); ++i)
{
if (i<other.size()-1)
{
printf("%05d %d %05d\n",address[other[i]],data[other[i]],address[other[i+1]]);
}else{
printf("%05d %d -1\n",address[other[i]],data[other[i]]);
}
}

return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1097/
  • 发布时间: 2019-09-03 12:31
  • 更新时间: 2021-10-29 14:07
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!