题目
Time Limit: 1sec Memory Limit:256MB
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 Copy
2
1
0 1
3
0 4
0 2
2 3
Sample Output Copy
1:1
2:1
3:2
4:1
Hint
This is a single source shortest path problem. You may use Dijkstra’s algorithm, or BFS because the graph is unweighted.
Problem Source: testF
学习
/*
2018年11月23日16:54:49
1010. Bacon Number
无向图的最短路径问题
采用了1005中的算法,注意序号 循环条件
*/
code
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define MAX 101
#define INFINITE 9999
int edges;
bool visited[MAX];
int move[MAX];
bool mat[MAX][MAX];
int main()
{
int t;
cin >> t;
while(t--)
{
memset(visited, false, sizeof(visited));
memset(move, -1, sizeof(move));
memset(mat, false, sizeof(mat));
cin >> edges;
while(edges--)
{
int a, b;
cin >> a >> b;
mat[a][b] = mat[b][a] = true;
}
// for(int i = 0; i < MAX; ++i)
// for(int j = 0; j < MAX; ++j)
// if(mat[i][j])cout << i << " " << j << endl;
queue<int> q;
int dist = 0;
q.push(0);
visited[0] = true;
while(!q.empty())
{
int count = q.size();
dist++;
// cout << "dist=" << dist << endl;
while(count--)
{
int front = q.front();
q.pop();
for(int i = 1; i < MAX; ++i)//MAX = 101
{
if(mat[front][i] && !visited[i])
{
q.push(i);
visited[i] = true;
move[i] = dist;
}
}
}
}
for(int i = 1; i < MAX; ++i)
{
if(move[i] > 0){
cout << i << ":" << move[i] << endl;
}
}
cout << "---" << endl;
}
return 0;
}