天天看點

1097 Deduplication on a Linked List (25 分)(連結清單)

Description

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 (<= 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.

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

生詞

英文 解釋
deduplication 去重
duplicated 重複的
At the mean time 與此同時

題目大意:

給一個連結清單,去重(去掉值或者絕對值相等的),先輸出删除後的連結清單,再輸出删除了的連結清單。

分析:

用結構體數組存儲這個連結清單,大小為maxn = 100000,node[i]表示位址為i的結點。在結構體中定義一個num變量,将num變量先初始化為2 * maxn。通過改變num變量的值最後sort排序來改變連結清單的順序

題解

#include <bits/stdc++.h>

using namespace std;
const int maxn=100000;
struct NODE
{
    int address,key,next,num=2*maxn;
}node[maxn];
bool exist[maxn];
bool cmp(NODE a,NODE b)
{
    return a.num<b.num;
}
int main()
{
    #ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif
    int first,n,num,cnt1=0,cnt2=0;
    scanf("%d %d",&first,&n);
    for(int i=0;i<n;i++){
        scanf("%d",&num);
        scanf("%d%d",&node[num].key,&node[num].next);
        node[num].address=num;
    }
    for(int i=first;i!=-1;i=node[i].next){
        if(exist[abs(node[i].key)]==false){
            exist[abs(node[i].key)]=true;
            node[i].num=cnt1;
            cnt1++;
        }else{
            node[i].num=maxn+cnt2;
            cnt2++;
        }
    }
    //注意這裡應該是maxn而不是n,因為node的長度為maxn
    sort(node,node+maxn,cmp);
    int cnt=cnt1+cnt2;
    for(int i=0;i<cnt;i++){
        //注意這裡應該是&&而不是||。
	//從離散數學的角度來看,該語句的反命題為:i==非cnt1-1 || i==非cnt2-1 
        if(i!=cnt1-1&&i!=cnt-1){
            printf("%05d %d %05d\n",node[i].address,node[i].key,node[i+1].address);
        }else
            printf("%05d %d -1\n",node[i].address,node[i].key);
    }
    return 0;
}
           
下一篇: Vue 元件注冊