邻接表中判边(邻接表+无向图)

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;
}





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值