牺牲空间换时间。
#include <cstdio>
#include <vector>
#include <cmath>
#include <cstring>
using namespace std ;
#define MAX 10050
typedef struct D
{
int add ;
int data ;
int next ;
}D ;
vector<D>order ;
vector<D>removed ;
int visited[MAX] ;
D ans[100000] ;
void buildList(int next)
{
if(next == -1 ) return ;
if( visited[(int)abs(ans[next].data) ] == 1 )
{
removed.push_back(ans[next]);
}
else
{
visited[ (int)abs(ans[next].data)] = 1;
order.push_back( ans[next] ) ;
}
buildList( ans[next].next ) ;
}
int main(void)
{
int start , N ;
int i ;
memset( visited , 0 , sizeof(visited) ) ;
scanf("%d %d" , &start , &N );
for( i = 0 ; i < N ; i++ )
{
D d ;
scanf("%d %d %d" , &d.add , &d.data , &d.next);
ans[d.add] = d ;
}
// to avoid the list builded is NULL
if( start == -1 || ans[start].add == ans[start].next)
{
printf("-1\n");
return 0;
}
buildList(start);
for( i = 0 ; i < order.size() ; i++)
{
if( i != 0 ) printf(" %05d\n" , order[i].add);
printf("%05d %d" , order[i].add , order[i].data);
}
printf(" -1\n");
// if the removed list is empty , then output nothing
if( removed.size() == 0 ) return 0 ;
for( i = 0 ; i < removed.size() ; i++)
{
if( i != 0 ) printf(" %05d\n" , removed[i].add);
printf("%05d %d" , removed[i].add , removed[i].data , removed[i].next);
}
printf(" -1\n");
return 0 ;
}