题目描述
贝茜知道这样一个游戏,电影明星和电影明星通过同一部电影联系再一起。
专横的培根女士是一只猪,她想证明牛和猪一样好。
贝茜从来没看过电影,传说中说她和其它的奶牛在月圆之夜是通过彼此的叫声联系的。
一种贝茜和其他奶牛联系的方式是通过一连串的中间奶牛传递的,所以当第一头牛和贝茜一起叫,第二头牛和第一头牛一起叫,第三头牛和第二头牛一起叫,......,贝茜就能依次联系到其中的每一头奶牛。
将有多种顺序把贝茜与其他奶牛联系,每头牛都至少有一种方式与贝茜联系。
联系的长度是指传递过程中涉及的奶牛的数目(不包括贝茜),任何一头奶牛的培根索引是指从贝茜到该奶牛的最小的长度。
最小的凯文培根索引是1(当贝茜能够直接与该奶牛联系时)。
约翰有C头牛,编号从1..C(1<=C<=1000)。
自然贝茜是1号,共有P(1<=P<=10,000)组奶牛联系。
找到从贝茜开始的最大的培根索引。
输入
第1行:C,P
第2..P+1行:每行两头牛,它们相互之间有联系,输入数据没有先后顺序之分。
输出
最大的培根索引
样例
输入
6 7
1 2
2 3
2 4
3 4
3 5
4 5
6 5
输出
4
AC代码:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main() {
int C, P;
cin >> C >> P;
vector<vector<int> > graph(C + 1);
for (int i = 0; i < P; i++) {
int cow1, cow2;
cin >> cow1 >> cow2;
graph[cow1].push_back(cow2);
graph[cow2].push_back(cow1);
}
vector<int> dist(C + 1, -1);
queue<int> q;
q.push(1);
dist[1] = 0;
while (!q.empty()) {
int curr = q.front();
q.pop();
for (int neighbor : graph[curr]) {
if (dist[neighbor] == -1) {
dist[neighbor] = dist[curr] + 1;
q.push(neighbor);
}
}
}
int maxBaconIndex = 0;
for (int i = 1; i <= C; i++) {
maxBaconIndex = max(maxBaconIndex, dist[i]);
}
cout << maxBaconIndex << endl;
return 0;
}