06-图3 六度空间 (30分)

BFS
key:记录BFS的层数,在BFS层数为6的时候计算count/Nv
ac代码

#include
#include
#include

using namespace std;

int G[10005][10005];
bool Visited[10005];
int Nv,Ne;

void CreateGraph()
{
    scanf("%d %d",&Nv,&Ne);
    for(int i=0;ifalse;
        for(int j=0;j0;
        }
    }
    for(int i=0;iint x,y;
        scanf("%d %d",&x,&y);
        G[x-1][y-1] = G[y-1][x-1] = 1;
    }
}

void BFS(int n)
{
    int level = 0,last = n,rail;
    queue<int> Q;
    Q.push(n);
    Visited[n] = true;
    int count = 1;
    while(!Q.empty()){
        int temp = Q.front();
        Q.pop();
        for(int i=0;iif(!Visited[i]&&G[temp][i]){
                Q.push(i);
                Visited[i] = true;
                count++;
                rail = i;
            }
        }
        if(temp == last){
            level++;
            last = rail;
        }
        if(level == 6){
            break;
        }
    }
    printf("%d: %.2f%%\n", n+1, (count * 100.00) / Nv); 
}

int main()
{
    CreateGraph();
    for(int i=0;ifor(int j=0;jfalse;
        }
        BFS(i);
    }

    return 0;
}














你可能感兴趣的:(PAT(A))