3361: [Usaco2004 Jan]培根距离
Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 88 Solved: 70
[ Submit][ Status][ Discuss]
Description
贝茜和其他奶牛联系是通过一连串的中间奶牛传递的,所以当第一头牛和贝茜联系,第二头牛和第一头牛联系,第三头牛和第二头牛联系,…一贝茜就能依次联系到其中的每一头奶牛. 联系长度是指传递过程中涉及的奶牛的数目(不包括贝茜).任何一头奶牛(不包括贝茜)的培根距离是指从贝茜到该奶牛的最小联系长度.最小的培根距离是1(当贝茜能够直接与该奶牛联系时).约输有C头牛,编号1到C,贝茜是1号.有P(1≤P≤10000)组奶牛相互联系.请找到最大的培根距离.
Input
第1行:C和P.
第2到P+1行:每行两头牛,它们之间有联系.
Output
输出最大培根距离.
Sample Input
6 7
1 2
2 3
2 4
3 4
3 5
4 5
6 5
Sample Output
4
答案就是1到所有点最短路中最长的那个
#include<vector>
#include<queue>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
vector<int> G[10005];
queue<int> q;
int dp[10005];
int main(void)
{
int n, m, i, x, y, ans;
scanf("%d%d", &n, &m);
for(i=1;i<=m;i++)
{
scanf("%d%d", &x, &y);
G[x].push_back(y);
G[y].push_back(x);
}
memset(dp, 52, sizeof(dp));
dp[1] = 0;
q.push(1);
while(q.empty()==0)
{
x = q.front();
q.pop();
for(i=0;i<G[x].size();i++)
{
y = G[x][i];
if(dp[y]>dp[x]+1)
{
dp[y] = dp[x]+1;
q.push(y);
}
}
}
ans = 0;
for(i=1;i<=n;i++)
ans = max(ans, dp[i]);
printf("%d\n", ans);
return 0;
}