【PAT数据结构与算法题目集】六度空间(多源最短路径)
题目
六度空间”理论又称作“六度分隔(Six Degrees of Separation)”理论。这个理论可以通俗地阐述为:“你和任何一个陌生人之间所间隔的人不会超过六个,也就是说,最多通过五个人你就能够认识任何一个陌生人。”
“六度空间”理论虽然得到广泛的认同,并且正在得到越来越多的应用。但是数十年来,试图验证这个理论始终是许多社会学家努力追求的目标。然而由于历史的原因,这样的研究具有太大的局限性和困难。随着当代人的联络主要依赖于电话、短信、微信以及因特网上即时通信等工具,能够体现社交网络关系的一手数据已经逐渐使得“六度空间”理论的验证成为可能。
假如给你一个社交网络图,请你对每个节点计算符合“六度空间”理论的结点占结点总数的百分比。
输入格式:
输入第1行给出两个正整数,分别表示社交网络图的结点数N(
1
<
N
≤
10
4
1<N≤10^4
1<N≤104,表示人数)、边数M(
≤
33
×
N
≤33×N
≤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%
思路
这题的思路就是对每个结点,求其到其余各结点的最短距离,然后求最短距离不超过6的结点数占结点总数的百分比,因此其实就是一个多源最短路径问题,只需对每个结点进行单源最短路径查找即可。
代码
#include <iostream>
#include <stdio.h>
#include <string>
#include<string.h>
#include <vector>
#include <map>
#include <stack>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
int graph[1005][1005];
int shortest[1005];
int tip[1005];
int Biggest = 10005;
double node_short_path(int node, int n) {
int i, j, k;
memset(tip, 0, sizeof(tip));
for(i=1; i<=n; i++) {
shortest[i] = Biggest;
}
shortest[node] = 0;
int ans = 0;
while(ans <= n) {
int small = 10005;
int this_node;
for(i=1; i<=n; i++) {
if(tip[i]==0 && small > shortest[i]) {
small = shortest[i];
this_node = i;
}
}
tip[this_node] = 1;
ans++;
for(i=1; i<=n; i++) {
if(tip[i]==0 && graph[this_node][i]) {
if(shortest[i] > shortest[this_node] + 1) {
shortest[i] = shortest[this_node] + 1;
}
}
}
}
ans = 0;
for(i=1; i<=n; i++) {
if(shortest[i] < 7) {
ans++;
}
}
double a = (double)ans / (double)n;
return a;
}
int main() {
int i, j, k, n, e, m;
while(~scanf("%d %d", &n, &m)) {
memset(graph, 0, sizeof(graph));
while(m--) {
scanf("%d %d", &i, &j);
graph[i][j] = graph[j][i] = 1;
}
for(i=1; i<=n; i++) {
double a = node_short_path(i, n)*100;
printf("%d: %.2lf%%\n", i, a);
}
}
return 0;
}