两次dfs:
#include <iostream>
#include <cstdio>
#include <string.h>
#include <queue>
using namespace std;
int vis[101000];
int head[101000];
int cnt;
struct node{
int y;
int next;
};
node e[300000];
void insert(int i,int j){
e[cnt].y = j;
e[cnt].next = head[i];
head[i] = cnt++;
}
int start;
int depth;
int dfs(int t,int i){
vis[i] = 0;
int temp = head[i];
int a = 0;
while(temp != -1){
if(vis[e[temp].y] == -1)
a = max(a,dfs(t+1,e[temp].y));
temp = e[temp].next;
}
if(a == 0){
if(t > depth){
start = i;
depth = t;
}
return t;
}
return a;
}
int main(){
int n;
cin>>n;
memset(head,-1,sizeof(head));
memset(vis,-1,sizeof(vis));
int a,b;
for(int i = 1;i < n;i++){
scanf("%d%d",&a,&b);
insert(a,b);
insert(b,a);
}
dfs(0,1);
memset(vis,-1,sizeof(vis));
int res;
res = dfs(0,start);
printf("%d\n",res);
}
折点:
#include <iostream>
#include <cstdio>
#include <string.h>
#include <queue>
using namespace std;
int head[101000];
int cnt;
struct node{
int y;
int next;
};
node e[300000];
void insert(int i,int j){
e[cnt].y = j;
e[cnt].next = head[i];
head[i] = cnt++;
}
int res = 0;
int dfs(int t,int i){
int temp = head[i];
if(head[i] == -1){
return t;
}
priority_queue<int> q;
while(temp != -1){
q.push(dfs(t+1,e[temp].y));
temp = e[temp].next;
}
int a = q.top(),b = 0;
q.pop();
if(!q.empty()){
b = q.top();
res = max(res,a+b-2*t);
}
else{
res = max(res,a-t);
}
return a;
}
int main(){
int n;
cin>>n;
memset(head,-1,sizeof(head));
int a,b;
for(int i = 1;i < n;i++){
scanf("%d%d",&a,&b);
if(a > b)
swap(a,b);
insert(a,b);
}
dfs(0,1);
printf("%d\n",res);
}