PAT-L2-002. 链表去重

 

链接:https://www.patest.cn/contests/gplt/L2-002

这是一道简单题,用结构体记录各个地址和key的值,用vector建立的邻接表,来记录结点之间的连接关系,

最后用两个vector v1和v2分别记录不同的连接关系

<textarea readonly="readonly" name="code" class="c++">

#include <bits/stdc++.h> 
using namespace std;
struct edge {
	int name;
	int key;
	int abs1;
};



edge ee[100010];



int book[10010];
vector<int> G[100010]; 
vector<int> V2,V1;
int main() {
	int S,n,s1,k1,k2,s2;
	cin>>S>>n;


	memset(book,0,sizeof(book));
//	memset(G,-1,sizeof(G));
	for( int i = 0; i < n ; i++ ) {
		cin>>s1>>k1>>s2;
		k2 = abs(k1);
		
		ee[s1].name = s1;
		ee[s1].key = k1;
		ee[s1].abs1 = k2;
		


		G[s1].push_back(s2);
	}
	
	for( int head = S; head != -1; head = G[head][0] ) {


		int vis = ee[head].abs1;
		
		if( book[vis] == 1 )  {
		
			V2.push_back(ee[head].name);
		}
		else {
			book[vis] = 1;
			V1.push_back(ee[head].name);
		}
		
	}	
	
	for(int i=0;i<V1.size();i++){
		int k = ee[V1[i]].key;
		if(i==V1.size()-1){
			printf("%05d %d -1",V1[i],k);
			break;
		}
		printf("%05d %d %05d\n",V1[i],k,V1[i+1]);
	}
	
	for(int j=0;j<V2.size();j++){
		int k = ee[V2[j]].key;
		if(j==V2.size()-1){
			printf("\n%05d %d -1",V2[j],k);
			break;
		}
		printf("\n%05d %d %05d",V2[j],k,V2[j+1]);
	}
	return 0;
}

</textarea>

猜你喜欢

转载自blog.csdn.net/Dream_your/article/details/79568240