Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- const int MAXN = 1000;
- int used[MAXN+1], Q[MAXN], P[MAXN], G[MAXN][MAXN], N, b, e;
- void make_empty(){
- b=0;
- e=-1;
- }
- void push(int x){
- Q[++e]=x;
- }
- int pop(){
- return Q[b++];
- }
- bool emptyQ(){
- return b>e;
- }
- void BFS(int r){
- int x,y,i;
- for(i=1;i<=N;i++) used[i]=0;
- make_empty();
- push(r);
- used[r]=1;
- P[r]=0;
- while(!emptyQ()){
- x=pop();
- for(i=1;i<=G[x][0];i++){
- y=G[x][i];
- if(!used[y]){
- push(y);
- used[y]=1;
- P[y]=x;
- cout<< y <<" ";
- }
- }
- }
- }
- int main(){
- setlocale(0,"");
- int n,x,y;
- while( cin >> n ){
- for( int i=0; i<n; i++ ){
- cin >> y >> x;
- G[x][++G[x][0]] = y;
- G[y][++G[y][0]] = x;
- }
- }
- cout << 1 << " ";
- BFS(1);
- cout << endl;
- for(int i=1; i<n; i++){
- if(used[i] != 1){
- cout << "Графа не е свързан! Следващо дърво:\n";
- cout << i << " ";
- BFS(i);
- cout << endl;
- }
- }
- return 0;
- }
- /*
- примерен вход
- 18
- 1 2
- 2 3
- 1 4
- 3 5
- 6 7
- 6 8
- 7 9
- 9 10
- 11 12
- 11 13
- 15 12
- 14 16
- 14 17
- */
Advertisement
Add Comment
Please, Sign In to add comment