这道题目基本照着书上面的代码敲的,也没怎么过脑,简单说一下我的理解。
- 用结构体的序号也就是order巧妙的把该保留的和该去除的很好的区分了开来
- 应该留下的,从0开始编号;要去除的,从maxn开始编号。巧妙地区分开来
- 按着order排序,从小到大,刚好就是:留下的在前,删掉的在后
- 一气呵成
#include <iostream>
#include <stdio.h>
#include <map>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 100005;
const int TABLE = 1000010;
struct Node{
int address,data,next;
int order;
}node[maxn];
bool cmp(Node a,Node b)
{
return a.order<b.order;
}
bool isExist[maxn];
int main()
{
memset(isExist,false,sizeof(isExist));
for(int i = 0;i < maxn;i++)
node[i].order = 2*maxn;
int n,start,address;
scanf("%d%d",&start,&n);
for(int i = 0;i <n;i++)
{
scanf("%d",&address);
scanf("%d%d",&node[address].data,&node[address].next);
node[address].address = address;
}
int countValid, countRemoved, p = start;
while(p!=-1)
{
if(!isExist[abs(node[p].data)]){
isExist[abs(node[p].data)] = true;
node[p].order = countValid++;
}
else
{
node[p].order = maxn + countRemoved++;
}
p = node[p].next;
}
sort(node, node + maxn, cmp);
int count = countValid + countRemoved;
for(int i = 0;i < count;i++){
if(i!=countValid - 1 && i != count - 1){
printf("%05d %d %05d\n", node[i].address, node[i].data, node[i+1].address);
}
else{
printf("%05d %d -1\n", node[i].address, node[i].data);
}
}
return 0;
}