Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).
Print one number – the brain latency.
4 3 1 2 1 3 1 4
2
5 4 1 2 2 3 3 4 3 5
3
大意就是给你一个树,让你去算这个树的最长的一个分支(两点距离为1);
思路就是,先从任意一点开始计算出距离此点最远的一个点,然后从这一点开始计算距这一点最远的点,就是最终答案;
就是变换一下参考系就好了.
#include<stdio.h> #include<string.h> #include<algorithm> #include<queue> using namespace std; queue<int>q; int n,m; int fre=0; int head[100005]; int vis[100005]; int nd[100005]; int b[100005]; int dp[100005]; int maxx=0; struct p { int node ,next; }E[200005]; struct pp { int deep,num; }EE[100005]; void insertt(int x,int y) { E[fre].node=y; E[fre].next=head[x]; head[x]=fre; fre++; } void bfs(int root) { q.push(root); vis[root]=1; while (!q.empty()) { int fr=q.front(); q.pop(); for (int i=head[fr];i!=-1;i=E[i].next) { if (!vis[E[i].node]) { vis[E[i].node]=1; q.push(E[i].node); dp[E[i].node]=dp[fr]+1; } } } } bool cmp(pp aa,pp bb) { return aa.deep>bb.deep; } int main() { scanf("%d%d",&n,&m); memset(head,-1,sizeof(head)); int a,b; for (int i=1;i<=m;i++) { scanf("%d%d",&a,&b); insertt(a,b); insertt(b,a); } int coutt=0; memset(vis,0,sizeof(vis)); bfs(1); for (int i=1;i<=n;i++) { EE[i].num=i; EE[i].deep=dp[i]; } sort(EE+1,EE+n+1,cmp); memset(dp,0,sizeof(dp)); memset(vis,0,sizeof(vis)); bfs(EE[1].num); sort(dp+1,dp+n+1); printf("%d",dp[n]); }