题面
https://www.luogu.org/problem/P1084
题解
也算二分的经典题吧。
关于这道题有一个尴尬的故事,我口胡出了二分答案,然后以为自己做出来了,$gyf$说还要贪心,然后我把他$D$了,其实是我错了。。。。。
先二分答案,尽可能的往上走,然后让最上的支援最下的,若此时支援点只有一支队伍,必须保证其他的人到这里更近才能更新。
#include<cstdio> #include<iostream> #include<vector> #include<cstring> #include<algorithm> #include<queue> #define ri register int #define ll long long #define N 50050 using namespace std; int fa[N],n,m,f[N][17]; int que[N],nque[N],tong[N],top[N]; long long dis[N]; bool imp[N],reach[N]; vector<int> to[N],len[N]; struct node1 { int x; ll walked; bool operator < (const node1 &rhs) const { return walked>rhs.walked; } }; struct node2 { int x; bool operator < (const node2 &rhs) const { return dis[x]<dis[rhs.x]; } }; void maketree(int x,int ff,int l) { dis[x]=dis[ff]+l; f[x][0]=fa[x]=ff; for (ri i=1;i<=16;i++) f[x][i]=f[f[x][i-1]][i-1]; for (ri i=to[x].size()-1;i>=0;i--) if (to[x][i]!=ff) maketree(to[x][i],x,len[x][i]); } void dfs(int x,int tp) { imp[x]=1; top[x]=tp; if (to[x].size()>2) return; for (ri i=to[x].size()-1;i>=0;i--) if (to[x][i]!=fa[x]) dfs(to[x][i],tp); } bool can(long long cc) { priority_queue<node1> yinyu; while (!yinyu.empty()) yinyu.pop(); priority_queue<node2> ineed; while (!ineed.empty()) ineed.pop(); memset(reach,0,sizeof(reach)); memset(tong,0,sizeof(tong)); for (ri i=1;i<=m;i++) { int x=que[i],nx=x; for (ri j=16;j>=0;j--) if (f[nx][j]!=1 && dis[x]-dis[f[nx][j]]<=cc) nx=f[nx][j]; nque[i]=nx; yinyu.push((node1){nx,dis[x]}); } for (ri i=1;i<=m;i++) if (imp[nque[i]]) { int nx=nque[i]; reach[top[nx]]=1; tong[top[nx]]++; } for (ri i=to[1].size()-1;i>=0;i--) if (!reach[to[1][i]]) { ineed.push((node2){to[1][i]}); } if (ineed.empty()) return 1; while (!yinyu.empty()) { node2 need=ineed.top(); node1 cur=yinyu.top(); if (cur.walked*1LL+dis[need.x]>cc) return 0; if (tong[top[cur.x]]==1 && dis[top[cur.x]]>dis[need.x]) { yinyu.pop(); continue; } ineed.pop(); yinyu.pop(); if (--tong[top[cur.x]]==0) ineed.push((node2){top[cur.x]}); if (ineed.empty()) return 1; } return 0; } int main(){ scanf("%d",&n); for (ri i=1;i<n;i++) { int u,v,w; scanf("%d %d %d",&u,&v,&w); to[u].push_back(v); len[u].push_back(w); to[v].push_back(u); len[v].push_back(w); } maketree(1,1,0); scanf("%d",&m); for (ri i=1;i<=m;i++) scanf("%d",&que[i]); long long l=0,r=N*1e9; long long ans=-1; for (ri i=to[1].size()-1;i>=0;i--) dfs(to[1][i],to[1][i]); while (l<=r) { long long mid=(l+r)/2; if (can(mid)) ans=mid,r=mid-1;else l=mid+1; } cout<<ans<<endl; }
原文:https://www.cnblogs.com/shxnb666/p/11427129.html