A1097

本題思路:
遍歷整個鏈表,篩選出兩個結構體數組,一個放本體,另一個放副本.通過bool類型數組中的記錄判斷當前遍歷到的key是本體還是副本,再將其放入對應的結構體中.
注意點:可能存在無效結點.

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=100010;
bool iscur[10010]={0};
struct node{
	int address,key,next;
}nodes[maxn],node1[maxn],node2[maxn];
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	int first,n,idx1=0,idx2=0;
	scanf("%d%d",&first,&n);
	for(int i=0;i<n;i++){                                 //初始化輸入 
		int address;
		scanf("%d",&address);
		scanf("%d%d",&nodes[address].key,&nodes[address].next);
		nodes[address].address=address;
	}	
	while(first!=-1){                                     //遍歷整個list,分別篩選到兩個結構體數組 
		int akey=nodes[first].key;
		if(akey<0)akey=-akey;
		if(iscur[akey]){
			node2[idx2++]=nodes[first];
		}else{
			node1[idx1++]=nodes[first];
			iscur[akey]=true;
		}
		first=nodes[first].next;
	}
	for(int i=0;i<idx1;i++){                             //輸出resulting linked list 
		printf("%05d %d ",node1[i].address,node1[i].key);
		if(i==idx1-1){
			printf("-1\n");
		}else{
			printf("%05d\n",node1[i+1].address);
		}
	}
	for(int i=0;i<idx2;i++){                             //輸出removed list 
		printf("%05d %d ",node2[i].address,node2[i].key);
		if(i==idx2-1){
			printf("-1\n");
		}else{
			printf("%05d\n",node2[i+1].address);
		}
	}
	return 0;
}

算法筆記用的方法實現空間佔用少,在一個結構體中實現.
本體結點、副本結點、無效結點三者各自在自己的大範圍內,方便通過排序將它們區分開來.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章