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