1. 程式人生 > >1097 Deduplication on a Linked List (25 分)

1097 Deduplication on a Linked List (25 分)

1097 Deduplication on a Linked List (25 分)

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

第二個測試點錯誤,也許輸入的是無效的呢/?  比如輸入10個,但是隻有8個可以找到。。。。是這個原因發現這種題好多這種原因

程式碼

#include<bits/stdc++.h> 
using namespace std;
const int maxn=100000;
map<int,int>mp;
struct node{
	int add,data,nxt;
	int cnt;
	node(){cnt = 2 * maxn;}
}s[maxn];
bool cmp(node a,node b){
	return a.cnt<b.cnt;
}
int main(){
	int n, beginn,x;
	scanf("%d%d", &beginn, &n);
	for(int i = 0;i < n; i++)
	{
		scanf("%d", &x);
		s[x].add = x;
		scanf("%d%d", &s[x].data, &s[x].nxt);
	}
	int cnt1 = 0 , cnt2 = 0;
	int size = 0;
	for(int i = beginn ; i != -1; i = s[i].nxt){
		if(mp[abs(s[i].data)] == 0){
			mp[abs(s[i].data)] = 1;
			s[i].cnt = cnt1++;
		}else 
			s[i].cnt = maxn + cnt2;
			cnt2++; 
		size++;
	}
	sort(s, s + maxn, cmp);
	for(int i = 0; i < size; i ++){
		if(i != cnt1 - 1 && i != size - 1)
            printf("%05d %d %05d\n", s[i].add, s[i].data, s[i+1].add);
        else
			printf("%05d %d -1\n", s[i].add, s[i].data);
	}
	return 0;
}