鄰接表中判邊(鄰接表+無向圖)

1、題目:


 Problem Description

設有一無向圖G,其頂點值爲字符型並假設各值互不相等,採用鄰接表表示法存儲。設計一個算法,判斷該無向圖中是否存在某一特定邊。

 Input

有多組測試數據,每組數據的第一行爲兩個整數n和e,表示n個頂點和e條邊(0<n<20);第二行爲其n個頂點的值,按輸入順序進行存儲;後面有e行,表示e條邊的信息,每條邊信息佔一行,包括邊所依附的頂點下標i和j,數據之間用空格隔開(注:要求採用頭插法建立邊表);最後一行爲兩個下標s和t(假設s和t均有效)。

 Output

若下標s和t對應的頂點間有邊,輸出1;若無,輸出0。

 Sample Input

4 4
ABCD
0 1
0 3
1 2
1 3
0 3
4 4
ABCD
0 1
0 3
1 2
1 3
0 2

 Sample Output

1
0



2、參考代碼:

#include <iostream>
using namespace std;

struct ArcNode{
	int adjvex;
	ArcNode* next;
};

struct VertexNode{
	char vertex;
	ArcNode* firstedge;
};

class ALGraph{
private:
	int vertexNum;
	VertexNode adjlist[111];
public:
	ALGraph(char* a,int n);
	~ALGraph();
	void InsertArc(int i,int j);
	int judge(int i,int j);
};

ALGraph::ALGraph(char* a,int n){
	vertexNum=n;
	for(int i=0;i<vertexNum;i++){
		VertexNode temp;
		temp.vertex=a[i];
		temp.firstedge=NULL;
		adjlist[i]=temp;
	}
}

ALGraph::~ALGraph(){
	for(int i=0;i<vertexNum;i++){
		ArcNode* p=adjlist[i].firstedge;
		while(p){
			adjlist[i].firstedge=p->next;
			delete p;
			p=adjlist[i].firstedge;
		}
	}
}

void ALGraph::InsertArc(int i,int j){
	ArcNode* p=new ArcNode;
	p->adjvex=j;
	p->next=adjlist[i].firstedge;
	adjlist[i].firstedge=p;
}

int ALGraph::judge(int i,int j){
	ArcNode* p=adjlist[i].firstedge;
	while(p){
		if(p->adjvex==j)
			return 1;
		else
			p=p->next;
	}
	return 0;
}

int main()
{
	int i,j,n,e;
	char a[111];
	while(cin>>n>>e)
	{
		cin>>a;
		ALGraph w(a,n);
		while(e--){
			cin>>i>>j;
			w.InsertArc(i,j);
			w.InsertArc(j,i);
		}
		cin>>i>>j;
		cout<<w.judge(i,j)<<endl;
	}
	return 0;
}





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