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
|
#include<stdio.h>
#include<iostream>
#include<queue>
#include<list>
#include <map>
#define WHITE 0
#define BLACK 1
#define GRAY 2
using namespace std;
struct vertex {
int color,d,pred,name,part;
}v[10];
multimap< int,int > m;
multimap< int,int > :: iterator it1;
multimap< int,int > :: iterator it2;
void BFS(int n) {
int i;
for(i=2;i<=n;i++) {
v[i].color=WHITE;
v[i].d=-100;
v[i].pred=-10;
v[i].name=i;
}
v[1].color=GRAY;
v[1].d=0;
v[1].pred=-10;
v[1].name=1;
queue<vertex> q;
q.push(v[1]);
printf("1 ");
vertex u;
while(!q.empty()) {
u=q.front();
q.pop();
it1=m.lower_bound(u.name);
it2=m.upper_bound(u.name);
while(it1!=it2) {
i=it1->second;
if(v[i].color==WHITE){
v[i].color=GRAY;
v[i].d=u.d+1;
v[i].pred=u.name;
q.push(v[i]);
printf("%d ",v[i].name);
}
it1++;
}
u.color=BLACK;
}
}
int main() {
freopen("in.in","r",stdin);
int i,j,n;
cout<<"vertex count:";
cin>>n;
cout<<"\nEdges: ";
cin>>i>>j;
m.insert( pair<int ,int>(i,j));
m.insert( pair<int ,int>(j,i));
while(i!=-1 && j!=-1) {
m.insert( pair<int ,int>(i,j));
m.insert( pair<int ,int>(j,i));
cout<<"\nEdges: ";
cin>>i>>j;
}
/* cout<<"Adjacency list";
for(it1=m.begin();it1!=m.end();it1++) {
cout<<"\n"<<it1->first<<" "<<it1->second;
}*/
cout<<endl<<"BFS"<<"\n";
BFS(n);
return 0;
}
|