Luogu P3629 [APIO2010] patrol
Diameter of ### trees
Surface problem link
to see the question should be connected to know the diameter of the tree, which is the longest chain
\ (ans = 2 (n-
1) -l1 + 1 \) but \ (k \ le2 \)
when he is \ (2 \ ) time how to deal with? ? ?
Seeking again pitted had a diameter of tree
we first obtained previously \ (L1 \) all the edges becomes \ (- 1 \)
after the re-request
\ (ans = 2 (n- 1) - (l1-1) - (l2-1) \)
If they do not overlap special treatment
because \ (l1 \) to take counter-minus after the \ (l2 \) is equivalent to adding back, two or
all of this equation is solved
code show as below:
#include<bits/stdc++.h>
using namespace std;
const int maxn=100010;
int fs,n,jk,head[maxn],tot=1,v[maxn],d[maxn],fa[maxn];
struct node{
int nxt,to,dis;
#define nxt(x) e[x].nxt
#define to(x) e[x].to
#define dis(x) e[x].dis
}e[maxn<<1];
inline void add(int from,int to){
to(++tot)=to;dis(tot)=1;nxt(tot)=head[from];head[from]=tot;
}
void dfs(int x){
v[x]=1;
for(int i=head[x];i;i=nxt(i)){
if(v[to(i)]) continue;
d[to(i)]=d[x]+dis(i);
fs=(d[to(i)]>=d[fs]) ? to(i) : fs;
fa[to(i)]=i;
dfs(to(i));
}
v[x]=0;
}
void dp(int x){
v[x]=1;
for(int i=head[x];i;i=nxt(i)){
if(v[to(i)]) continue;
dp(to(i));
fs=max(fs,d[x]+d[to(i)]+dis(i));
d[x]=max(d[x],d[to(i)]+dis(i));
}
}
int main()
{
scanf("%d%d",&n,&jk);
for(int x,y,i=1;i<n;i++){
scanf("%d%d",&x,&y);add(x,y);add(y,x);
}
fs=1;
dfs(1);
d[fs]=fa[fs]=0;
int fs1=fs;
dfs(fs1);
int ans=((n-1)<<1)-d[fs]+1;
if(jk==2){
while(fa[fs]){
dis(fa[fs])=-1;dis(fa[fs]^1)=-1;
fs=to(fa[fs]^1);
}
fs=0;memset(d,0,sizeof(d));
dp(fs1);
ans-=fs-1;
}
printf("%d\n",ans);
return 0;
}