-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path5-3-2.cpp
131 lines (131 loc) · 2.72 KB
/
5-3-2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include<iostream>
#include<queue>
using namespace std;
#define MAXSIZE 50
#define DATATYPE int
//邻接表表示的图 无向图arcnum等于2×边数
typedef struct ArcNode{
int value;
int adjvex;
struct ArcNode *next;
}ArcNode,*Arc;
typedef struct VNode{
ArcNode *next;
DATATYPE data;
}VNode,AdjList[MAXSIZE];
typedef struct{
AdjList vertices;
int vexnum,arcnum;
}Graph;
void AddArc(Graph &G,int x,int y,int value){
Arc p,pre=NULL,s;
for(p=G.vertices[x].next;p;pre=p,p=p->next){
if(p->adjvex==y)return;
}
s=(Arc)malloc(sizeof(ArcNode));
s->adjvex=y;
s->value=value;
s->next=NULL;
if(pre)pre->next=s;
else{
G.vertices[x].next=s;
}
}
void InitGraph(Graph &g){
int vn,an,x=0,num1,num2,value;
cin>>vn;
cin>>an;
g.vexnum=vn;
g.arcnum=an;
for(int i=0;i<g.vexnum;i++){
g.vertices[i].next=NULL;
}
for(x=0;x<an;x++){
cin>>num1;
cin>>num2;
cin>>value;
AddArc(g,num1,num2,value);
}
}
void PrintAdjList(Graph g){
Arc p,tmp;
for(int i=0;i<g.vexnum;i++){
p=g.vertices[i].next;
while(p){
cout<<i<<"-"<<p->adjvex<<":"<<p->value<<" ";
tmp=p->next;
free(p);
p=tmp;
}
cout<<endl;
}
}
int FirstNeighbor(Graph &G,int v){
if(G.vertices[v].next)return G.vertices[v].next->adjvex;
else return -1;
}
int NextNeighbor(Graph &G,int v,int w){
Arc p;
for(p=G.vertices[v].next;p;p=p->next){
if(p->adjvex==w){
if(p->next){
return p->next->adjvex;
}else return -1;
}
}
return -1;
}
bool visted[MAXSIZE];
void BFS(Graph &G,int v){
queue<int> q;
cout<<v<<" ";
visted[v]=true;
int p,w;
q.push(v);
while(!q.empty()){
w=q.back();
q.pop();
for(p=FirstNeighbor(G,w);p!=-1;p=NextNeighbor(G,w,p)){
if(!visted[p]){
cout<<p<<" ";
visted[p]=true;
q.push(p);
}
}
}
}
int count=0;
void DFS(Graph &G,int v){
int p;
cout<<v<<" ";
visted[v]=true;
for(p=FirstNeighbor(G,v);p!=-1;p=NextNeighbor(G,v,p)){
count++;
if(!visted[p]){
DFS(G,p);
}
}
}
int main(){
for(int i=0;i<MAXSIZE;i++)visted[i]=false;
Graph G;
InitGraph(G);
DFS(G,0);
cout<<endl;
for(int i=0;i<G.vexnum;i++)if(!visted[i]){
cout<<"false"<<endl;
PrintAdjList(G);
return 1;
}
if((count/2)!=G.vexnum-1){
cout<<"false"<<endl;
PrintAdjList(G);
return 1;
}
cout<<"true";
for(int i=0;i<MAXSIZE;i++)visted[i]=false;
//BFS(G,0);
cout<<endl;
PrintAdjList(G);
return 0;
}