题目链接:https://www.patest.cn/contests/gplt/L2-002
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
#define INF 0x3f3f3f3f
#define N 100005
typedef long long ll;
int firstAddress[10005];
int key[N];
int next[N];
bool duplicate[N]={false};
int main()
{
int s,n;
scanf("%d%d",&s,&n);
memset(firstAddress,-1,sizeof firstAddress);
for(int i=0;i<n;i++){
int a,k,n;
scanf("%d%d%d",&a,&k,&n);
key[a]=k;
next[a]=n;
}
int a=s; int s1=-1;
while(a!=-1){ //检测结点是否为重复的
if(firstAddress[abs(key[a])]==-1)
firstAddress[abs(key[a])]=a;
else{
duplicate[a]=true;
if(s1==-1) s1=a;
}
a=next[a];
}
a=s;
int lastFalse=-1,lastTrue=-1;
while(a!=-1){ //因为是向前更新指针,所以在对链表向后遍历的时候并不会断节
if(!duplicate[a]){
if(lastFalse!=-1)
next[lastFalse]=a;
lastFalse=a;
}
else{
if(lastTrue!=-1)
next[lastTrue]=a;
lastTrue=a;
}
a=next[a];
}
next[lastFalse]=-1; next[lastTrue]=-1;
a=s;
while(a!=-1){
printf("%05d %d ",a,key[a]);
if(next[a]==-1)
printf("-1\n");
else
printf("%05d\n",next[a]);
a=next[a];
}
a=s1;
while(a!=-1){
printf("%05d %d ",a,key[a]);
if(next[a]==-1)
printf("-1\n");
else
printf("%05d\n",next[a]);
a=next[a];
}
return 0;
}
PAT上的编译器不允许用next变量名,换一个名称就行。