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
| #include <bits/stdc++.h> using namespace std; typedef struct Arcnode{ int vertex,data; struct Arcnode *nextArc; }Arcnode; typedef struct vernode{ int data; Arcnode *nextArc; }vernode; typedef struct { vernode vertex[1001]; int vernum,arcnum; }Graph; typedef struct Qnode{ int data; struct Qnode *next; }Qnode,*Qptr; typedef struct { Qptr front; Qptr rear; }Linkqueue; int vis[1001]; int locate(Graph G, int x) { for(int i = 1 ; i <= G.vernum; ++i) { if(G.vertex[i].data == x) { return i; } } } void create(Graph &G) { int a,b,w; cin >> G.vernum >> G.arcnum; for(int i = 1; i <= G.vernum ; ++i) { cin >> G.vertex[i].data; G.vertex[i].nextArc = NULL; } for(int i = 1; i <= G.arcnum; ++i) { cin >> a >> b >> w; int A = locate(G,a); int B = locate(G,b); Arcnode *p,*p1; p = new Arcnode; p -> vertex = B; p -> nextArc = G.vertex[A].nextArc; p -> data = w; G.vertex[A].nextArc = p; p = new Arcnode; p -> vertex = A; p -> nextArc = G.vertex[B].nextArc; p -> data = w; G.vertex[B].nextArc = p; } } void init(Linkqueue &Q) { Q.front = new Qnode; Q.front -> next = NULL; Q.rear = Q.front; } void push(Linkqueue &Q, int p) { Qnode *q; q = new Qnode; q -> data = p; q -> next = NULL; Q.rear -> next = q; Q.rear = q; } int emptyqueue(Linkqueue Q) { if(Q.front == Q.rear) return 1; else return 0; } void pop(Linkqueue &Q, int &p) { Qnode *q; q = Q.front -> next; p = q -> data; Q.front -> next = q -> next; if(q == Q.rear) Q.rear = Q.front; } void bfs(Graph G,int v) { int p; vis[v] = 1; Linkqueue Q; init(Q); push(Q,v); while(!emptyqueue(Q)) { pop(Q,p); cout << p << '\n'; Arcnode *q; q = G.vertex[p].nextArc; while(q != NULL) { if(!vis[q -> vertex]) { vis[q -> vertex] = 1; push(Q,q -> vertex); } q = q -> nextArc; } } } int main() { memset(vis,0,sizeof(vis)); Graph G; create(G); int v; cin >> v; bfs(G,v); }
|