题目描述
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.
翻译:给定一条包含整数关键字的线性表L,你需要移除那些关键字的绝对值重复的节点。这就是说,对于每个值K,只有第一个关键字绝对值为K的节点将会被保留。与此同时, 所有的被移除的节点需要保留在一条分离出的链表上。例如,给定的L为21→-15→-15→-7→15, 你需要输出21→-15→-7, 和被移除的链表-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 (≤105) 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 104, and Next is the position of the next node.
翻译:每个输入文件包含一组测试数据。对于每组测试数据,第一行包括第一个节点的地址和一个正整数N (≤105) ,表示节点总数。一个节点的地址为一个5位非负整数,并且NULL用-1表示。
接下来N行,每一行按照以下格式描述一个节点:
地址 关键字 Next
地址为节点的位置,关键字是一个绝对值小于104的整数,Next为下一个节点的位置。
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
解题思路
注意当没有移除的节点时的输出即可,会卡一个点。详见代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<vector>
#include<algorithm>
#define INF 99999999
#define bug puts("Hello\n")
using namespace std;
bool v[10010];
int nextNode[100000],key[100000];
int keepNo[100000];
int kpCount=0;
int removeNo[100000];
int rmCount=0;
int main(){
int start=0,n;
for(int i=0;i<10010;i++)v[i]=false;
scanf("%d%d",&start,&n);
int a,b,c;
for(int i=0;i<n;i++){
scanf("%d%d%d",&a,&b,&c);
nextNode[a]=c;
key[a]=b;
}
while(start!=-1){
int absKey=abs(key[start]);
if(!v[absKey])v[absKey]=true,keepNo[kpCount++]=start;
else removeNo[rmCount++]=start;
start=nextNode[start];
}
for(int i=0;i<kpCount-1;i++)printf("%05d %d %05d\n",keepNo[i],key[keepNo[i]],keepNo[i+1]);
if(kpCount)printf("%05d %d -1\n",keepNo[kpCount-1],key[keepNo[kpCount-1]]);
for(int i=0;i<rmCount-1;i++)printf("%05d %d %05d\n",removeNo[i],key[removeNo[i]],removeNo[i+1]);
if(rmCount)printf("%05d %d -1\n",removeNo[rmCount-1],key[removeNo[rmCount-1]]);
return 0;
}