这道题,首先要确认的是用 DFS还是BFS,考虑到你要找的人,可能是你朋友的朋友的朋友。。每个人都有自己的交际圈,所以把每个人(结点)的交际圈看成一层,那么只要不超过六层的结点就是符合要求的,因此应用BFS。下图是根据题目要求对BFS进行改造:
【以上源自中国mooc大学浙大数据结构姥姥的课件*_* 有些截图我没说(因为懒,但是大家都懂吧。。】
#include<cstdio>
#include<queue>
#include<string.h>
using namespace std;
int const maxn=10000;
int N, M;
int visit[maxn];
int arr[maxn][maxn];
int BFS(int v){
queue<int> q;
int temp, level=0, tail, last=v, count=1;
q.push(v);
visit[v]=1;
while(!q.empty()){
temp=q.front();
q.pop();
for(int i=1; i<=N; i++){
if(arr[temp][i]&&visit[i]==0){
count++;
tail=i;
visit[i]=1;
q.push(i);
}
}
if(temp==last){
level++;
last=tail;
}
if(level==6)break;
}
return count;
}
int main(){
scanf("%d%d", &N, &M);
int a, b;
for(int i=0; i<M; i++){
scanf("%d%d", &a, &b);
arr[a][b]=1;
arr[b][a]=1;
}
for(int i=1; i<=N; i++){
int cnt=BFS(i);
memset(visit, 0, sizeof(visit));
double f=100.00*cnt/N;
printf("%d: %.02f%%\n", i, f);
}
return 0;
}
P.S. 题外话,这道题我写的时候,因为看到题目上有个M>=33*N,所以就开了330000*330000的二维数组,然后就很华丽丽的error了,而且devcpp是检测不出来的,codeblocks会显示The size of array 'arr' is too large。。。事实证明,数组果然不能开太大