题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1837
题目描述:一个很牛的外国人Isenbaev是ACM大神,认识他的人都想跟他沾沾边,同他一起比赛过的人跟他的亲密距离是1,跟这些距离1一起比赛过的人跟Isenbaev的亲密距离是2……以此类推;给定N支队伍以及队员名称,输出所列出的所有人员与Isenbaev的亲密距离(Isenbaev's Number)!
思路很清晰,将人名字符串 与 数字转化后,就成了以数字为基准的标准BFS模型;另外,用C++的map可以很方便的实现字典序输出;
比较坑的盲点是:给定的所有人员里可以没有Isenbaev,那么这时候所有人都应该是undefind,如果不加判断map里面找Isenbaev返回的是0;
直接上AC代码:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <queue>
#include <map>
using namespace std;
const int LIMIT = 999;
const int m_Size = 300;
bool matrix[m_Size][m_Size];
struct Node{
bool visit;
int len;
};
map<string, int> s2i;
vector<string> i2s;
vector<Node> v;
int reg(string &s, int &i){
map<string, int>::iterator it = s2i.find(s);
if (it == s2i.end()){
s2i[s] = i++;
i2s.push_back(s);
Node node;
node.visit = false;
node.len = LIMIT;
v.push_back(node);
return i - 1;
}
return it->second;
}
void link(int a, int b){
matrix[a][b] = true;
matrix[b][a] = true;
}
void func(){
int n, i, j;
cin >> n;
for (i = 0; i < 3 * n; i++)
for (j = 0; j <= i; j++)
matrix[i][j] = matrix[j][i] = false;
v.clear();
i2s.clear();
s2i.clear();
string sa, sb, sc;
int src = 0, tar = 0, ia, ib, ic;
for (i = 0; i < n; i++){
cin >> sa >> sb >> sc;
ia = reg(sa, tar);
ib = reg(sb, tar);
ic = reg(sc, tar);
link(ia, ib);
link(ia, ic);
link(ic, ib);
}
if (s2i.find(string("Isenbaev")) == s2i.end()){
map<string, int>::iterator it = s2i.begin();
while (it != s2i.end()){
cout << it->first << " undefined\n";
it++;
}
return ;
}
src = s2i[string("Isenbaev")];
v[src].visit = true;
v[src].len = 0;
queue<int> q;
q.push(src);
while (!q.empty()){
src = q.front();
q.pop();
for (i = 0; i < 3 * n; i++)
if (matrix[src][i] == true && v[i].visit == false){
v[i].visit = true;
q.push(i);
v[i].len = v[i].len <= (v[src].len + 1) ? v[i].len : (v[src].len + 1);
}
}
map<string, int>::iterator it = s2i.begin();
while (it != s2i.end()){
int delta = v[it->second].len;
cout << it->first << ' ';
if (delta == LIMIT)
cout << "undefined\n";
else
cout << delta << endl;
it++;
}
}
int main(){
freopen("out.txt", "w", stdout);
freopen("in.txt", "r", stdin);
func();
}