“六度空间”理论又称作“六度分隔(Six Degrees of Separation)”理论。这个理论可以通俗地阐述为:“你和任何一个陌生人之间所间隔的人不会超过六个,也就是说,最多通过五个人你就能够认识任何一个陌生人。”如图1所示。 图1 六度空间示意图 “六度空间”理论虽然得到广泛的认同,并且正在得到越来越多的应用。但是数十年来,试图验证这个理论始终是许多社会学家努力追求的目标。然而由于历史的原因,这样的研究具有太大的局限性和困难。随着当代人的联络主要依赖于电话、短信、微信以及因特网上即时通信等工具,能够体现社交网络关系的一手数据已经逐渐使得“六度空间”理论的验证成为可能。
假如给你一个社交网络图,请你对每个节点计算符合“六度空间”理论的结点占结点总数的百分比。
输入格式:
输入第1行给出两个正整数,分别表示社交网络图的结点数N(1<N≤10000,表示人数)、边数M(≤33×N,表示社交关系数)。随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个结点的编号(节点从1到N编号)。
输出格式:
对每个结点输出与该结点距离不超过6的结点数占结点总数的百分比,精确到小数点后2位。每个结节点输出一行,格式为“结点编号:(空格)百分比%”。
输入样例:
10 9
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
输出样例:
1: 70.00%
2: 80.00%
3: 90.00%
4: 100.00%
5: 100.00%
6: 100.00%
7: 100.00%
8: 90.00%
9: 80.00%
10: 70.00%
Code
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MaxVertexNum 10001
typedef int Vertex
;
typedef int WeightType
;
typedef struct ENode
*Edge
;
struct ENode
{
Vertex V1
,V2
;
};
typedef struct GNode
*MGraph
;
struct GNode
{
int Ne
;
int Nv
;
WeightType G
[MaxVertexNum
][MaxVertexNum
];
};
typedef struct QNode
*Queue
;
struct QNode
{
Vertex
*Elements
;
int Front
,Rear
;
};
int visted
[MaxVertexNum
];
MGraph
Creat();
void InsertEdge(MGraph Graph
,Edge E
);
int BFS(MGraph Graph
,Vertex V
);
Queue
CreatQuene(int MaxSize
);
void AddQ(Queue Q
,Vertex V
);
Vertex
DeleteQ(Queue Q
);
int IsEmpty(Queue Q
);
int main()
{
MGraph Graph
= Creat();
Edge E
= (Edge
)malloc(sizeof(struct ENode
));
for(int i
=0;i
<Graph
->Ne
;i
++)
{
scanf("%d %d",&E
->V1
,&E
->V2
);
InsertEdge(Graph
,E
);
}
Vertex V
,W
;
int cnt
;
for(V
=1;V
<=Graph
->Nv
;V
++)
{
for(W
=1;W
<=Graph
->Nv
;W
++) visted
[W
]=0;
cnt
= BFS(Graph
,V
);
printf("%d: %.2f%%\n",V
,cnt
*1.0/Graph
->Nv
*100.0);
}
return 0;
}
MGraph
Creat()
{
MGraph Graph
;
Vertex V
,W
;
Graph
= (MGraph
)malloc(sizeof(struct GNode
));
scanf("%d %d",&Graph
->Nv
,&Graph
->Ne
);
for(V
=1;V
<=Graph
->Nv
;V
++)
{
for(W
=1;W
<=Graph
->Nv
;W
++)
Graph
->G
[V
][W
] = 0;
}
return Graph
;
}
void InsertEdge(MGraph Graph
,Edge E
)
{
Graph
->G
[E
->V1
][E
->V2
] = 1;
Graph
->G
[E
->V2
][E
->V1
] = 1;
}
int BFS(MGraph Graph
,Vertex V
)
{
visted
[V
] = 1;
int cnt
= 1;
int level
= 0,last
= V
,tail
;
Queue Q
= CreatQuene(Graph
->Nv
);
AddQ(Q
,V
);
Vertex W
;
while(!IsEmpty(Q
))
{
V
= DeleteQ(Q
);
for(W
=1;W
<=Graph
->Nv
;W
++)
{
if(Graph
->G
[V
][W
])
{
if(!visted
[W
])
{
visted
[W
] = 1;
AddQ(Q
,W
);
cnt
++;
tail
= W
;
}
}
}
if(V
== last
)
{
level
++;
last
= tail
;
}
if(level
==6) break;
}
return cnt
;
}
Queue
CreatQuene(int MaxSize
)
{
Queue Q
= (Queue
)malloc(sizeof(struct QNode
));
Q
->Elements
= malloc(sizeof(Vertex
)*MaxSize
);
Q
->Front
= Q
->Rear
= 0;
return Q
;
}
void AddQ(Queue Q
,Vertex V
)
{
Q
->Elements
[Q
->Rear
++] = V
;
}
Vertex
DeleteQ(Queue Q
)
{
return Q
->Elements
[Q
->Front
++];
}
int IsEmpty(Queue Q
)
{
return Q
->Front
==Q
->Rear
;
}