Description
The
Bacon number of an actor is the number of degrees of separation he or she has from Bacon. For example, Tom Hanks has a Bacon number 1, because he was in Apollo 13 with Kevin Bacon. Sally Fields has a Bacon number of 2, because she was in Forrest Gump with Tom Hanks. Assume you are given a list of pair of actors who shared movie roles, compute the Bacon number for every actor.
Input
Assume that Kevin Bacon is numbered 0, other actors are numbered by positive integers between 1 to 100.
The first line is the number of test cases. Each test case start with the number m of actors in a line, then m pairs of actors are followed.
Output
For each test case, each actor's bacon number is printed out in a separate line in the form "actor number:Bacon number" in the order of increasing actor number, and finally a dotted line "---" is printed out in a separate line.
Sample Input
2 1 0 1 3 0 4 0 2 2 3
Sample Output
1:1 --- 2:1 3:2 4:1 ---
无向图的最短路径问题,用dijkstra算法,注意下面代码中图用的是邻接表存储。
#include <iostream>
#include <vector>
#include <list>
using namespace std;
#define MAX 100
#define INFINITE 9999
struct Graph {
int max; //记录最大的结点下标
vector<list<int> > adj;
int v, e;
};
//获得其他与结点a之间的距离
vector<int> getDistance(Graph* &g, int a) {
vector<int> distance;
distance.resize(MAX);
list<int>::iterator it = g->adj[a].begin();
while (it != g->adj[a].end()) {
distance[*it] = 1;
++it;
}
for (int i = 0; i <= g->max; ++i) {
if (distance[i] != 1) {
distance[i] = INFINITE;
}
}
return distance;
}
//用于记录结点是否被访问
bool visited[MAX];
vector<int> dijkstra(Graph* &g, int a) {
//初始化结点访问状态
for (int i = 0; i <= g->max; ++i) {
visited[i] = 0;
}
vector<int> distance = getDistance(g, a);
distance[a] = 0;
visited[a] = 1;
//进行(g->max - 1)次循环,获得其他结点与a的最短距离;
//至于为什么是(g->max -1),此处为了保证结点名称和下标的统一,将未输入的结点作为孤立结点
for (int i = 1; i <= g->max; ++i) {
int min = INFINITE;
int v = a;
//找出未被访问的,与a距离最近的一个结点
for (int j = 0; j <= g->max; ++j) {
if (!visited[j] && distance[j] <= min) {
v = j;
min = distance[j];
}
}
visited[v] = 1;
//更新其他未被访问的结点到a的距离
for (int j = 0; j <= g->max; ++j) {
vector<int> temp = getDistance(g, v);
if (!visited[j] && distance[v] + temp[j] < distance[j]) {
distance[j] = distance[v] + temp[j];
}
}
}
return distance;
}
int main(int argc, const char * argv[]) {
int cases;
cin >> cases;
for (int i = 0; i < cases; ++i) {
Graph *g = new Graph;
g->adj.resize(MAX);
int m;
cin >> m;
g->v = m+1;
g->e = m;
g->max = 0;
for (int j = 0; j < g->e; ++j) {
int a, b;
cin >> a >> b;
if (a > g->max) {
g->max = a;
}
if (b > g->max) {
g->max = b;
}
g->adj[a].push_back(b);
g->adj[b].push_back(a);
}
vector<int> distance = dijkstra(g, 0);
for (int j = 1; j <= g->max; ++j) {
if (distance[j] != INFINITE) {
cout << j << ':' << distance[j] << endl;
}
}
cout << "---" << endl;
}
}