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

 

 这道题,首先要确认的是用 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。。。事实证明,数组果然不能开太大

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值