题目:http://codeforces.com/problemset/problem/690/C2
题意:求树的直径。
思路:两遍bfs,先任取一点作为起点s1,走到离它最远的点s2。再把s2作为起点走到最远的点即可。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> P;
const int maxn = 1e5+5;
vector<int>vec[maxn];
int n, m, u, v, ans, vis[maxn];
P bfs(int u){
P sum(-1, -1);
queue<P> que; memset(vis, 0, sizeof vis);
que.push(P(u, 0)); vis[u] = 1;
while(que.size()){
P now = que.front(); que.pop();
u = now.first; int w = now.second;
for(auto it : vec[u]){
if(vis[it]) continue;
if(sum.second < w+1) sum = P(it, w+1);
que.push(P(it, w+1));
vis[it] = 1;
}
}
return sum;
}
int main()
{
cin >> n >> m;
for(int i=1; i<=m; i++){
cin >> u >> v;
vec[u].push_back(v); vec[v].push_back(u);
}
int ans = 0;
u = bfs(1).first; ans = bfs(u).second;
cout << ans << endl;
}