题目:http://www.lydsy.com/JudgeOnline/problem.php?id=2282
答案一定是在直径上的一段,然后答案一定不会小于不在直径上的点到直径的距离(要是可以的话那当前这条直径就不是直径了)
然后二分一遍,当前段的最长答案只可能在s->l,r->t取到,其他都是取不到的所以判断这两个就可以了。
#include<cstring> #include<iostream> #include<algorithm> #include<cstdio> #include<queue> #include<set> #define rep(i,l,r) for (int i=l;i<=r;i++) #define down(i,l,r) for (int i=l;i>=r;i--) #define clr(x,y) memset(x,y,sizeof(x)) #define maxn 300500 #define inf int(1e9) #define mm 1000000007 typedef long long ll; using namespace std; struct data{int obj,pre;ll c; }e[maxn*2]; int dis[maxn],num[maxn],D,l,r,mid,S; int n,tot,cnt,s,t,st[maxn],head[maxn],fa[maxn],mark[maxn]; int read(){ int x=0,f=1; char ch=getchar(); while (!isdigit(ch)){if (ch=='-') f=-1; ch=getchar();} while (isdigit(ch)){x=x*10+ch-'0'; ch=getchar();} return x*f; } void insert(int x,int y,int z){ e[++tot].obj=y; e[tot].pre=head[x]; e[tot].c=z; head[x]=tot; } void bfs(int s){ rep(i,1,n) dis[i]=-1; dis[s]=0; queue<int> q; q.push(s); while (!q.empty()){ int u=q.front(); q.pop(); for (int j=head[u];j;j=e[j].pre){ int v=e[j].obj; if (dis[v]==-1) { fa[v]=u; if (!mark[v]) dis[v]=dis[u]+e[j].c; else dis[v]=dis[u]; q.push(v); } } } } bool jud(int D){ int l=1,r=cnt; while (l<cnt&&num[1]-num[l+1]<=D) l++; while (r>1&&num[r-1]<=D) r--; return num[l]-num[r]<=S; } int main(){ // freopen("in.txt","r",stdin); n=read(); S=read(); rep(i,1,n-1){ int x=read(),y=read(); int z=read(); insert(x,y,z); insert(y,x,z); } bfs(1); rep(i,1,n) if (dis[i]>dis[s]) s=i; bfs(s); rep(i,1,n) if (dis[i]>dis[t]) t=i; D=dis[t]; int now=t; st[++cnt]=t; num[cnt]=dis[t]; while (now!=s){ now=fa[now]; mark[now]=1; st[++cnt]=now; num[cnt]=dis[now]; } bfs(s); rep(i,1,n) l=max(l,dis[i]); r=D; if (S<D){ while (l<=r){ ll mid=(l+r)/2; if (jud(mid)) r=mid-1; else l=mid+1; } } printf("%d ",l); return 0; }