洛谷P2680 [NOIP2015 提高组] 运输计划(树上差分 + 二分)
题意:
一棵带权树,有m个点对(S,T),其中你可以选择把任意一条的边权改为0,求点对dis(S,T)距离的最大值
思路
边差分
二分答案,把
d
i
s
(
s
,
t
)
>
a
n
s
dis(s,t)>ans
dis(s,t)>ans的全部标记,假设有
n
u
m
num
num个点对,用树上差分标记
(
c
[
x
]
+
+
,
c
[
y
]
+
+
,
c
[
l
c
a
]
−
=
2
)
(c[x]++, c[y]++, c[lca]-=2)
(c[x]++,c[y]++,c[lca]−=2),统计每条边标记的权值
(
v
a
l
)
=
=
n
u
m
(val)==num
(val)==num的该边的初始权值的最大值,最后
d
i
s
m
a
x
(
s
,
t
)
−
v
a
l
m
a
x
<
=
a
n
s
dis_{max}(s,t)-val_{max}<=ans
dismax(s,t)−valmax<=ans则符合二分check
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int maxn = 600000 + 5;
const int inf = 0x3f3f3f3f;
int n, m, cnt, num, c[maxn], deep[maxn], pre[maxn][21], head[maxn],a[maxn];
ll he,mp,dis[maxn];
struct node{
int to, next;
ll w;
}edge[maxn << 1];
struct nod{
int x,y,lca;
}data[maxn];
void addedge(int u, int v,ll w){
edge[++cnt].to = v;
edge[cnt].next = head[u];
edge[cnt].w=w;
head[u] = cnt;
}
void dfs(int x, int f){
pre[x][0] = f;
for(int i = head[x]; i; i = edge[i].next){
if(edge[i].to != f){
deep[edge[i].to] = deep[x] + 1;
dis[edge[i].to] =dis[x]+edge[i].w;
dfs(edge[i].to, x);
}
}
}
void solve(){
for(int j = 1; j <= 18; j++)
for(int i = 1; i <= n; i++)
pre[i][j] = pre[pre[i][j - 1]][j - 1];
}
int LCA(int u, int v){
if(deep[u] < deep[v]) swap(u, v);
int dc = deep[u] - deep[v];
for(int i = 0; i <= 18; i++){
if((1 << i) & dc) u = pre[u][i];
}
if(u == v) return u;
for(int i = 18; ~i; i--){
if(pre[u][i] != pre[v][i]){
u = pre[u][i];
v = pre[v][i];
}
}
return pre[u][0];
}
void dfs1(int x, int f,ll val){
for(int i = head[x]; i; i = edge[i].next) {
if(edge[i].to != f){
dfs1(edge[i].to, x,edge[i].w);
c[x] += c[edge[i].to];
}
}
if(c[x]==num)he=max(he,val);
}
bool check(ll mid){
he=num=mp=0;
memset(c,0,sizeof(c));
for(int i=1;i<=m;i++){
int x=data[i].x,y=data[i].y,lca=data[i].lca;
ll d=dis[x]+dis[y]-2*dis[lca];
if(d>mid) c[x]++, c[y]++, c[lca]-=2, num++,mp=max(mp,d);
}
dfs1(1,0,0);
if(mp-he<=mid)return 1;
return 0;
}
int main(){
scanf("%d%d",&n,&m);
for(int i = 1; i < n; i++){
ll x,y,z;
scanf("%lld%lld%lld", &x, &y,&z);
addedge(x, y, z), addedge(y, x, z);
}
dfs(1, -1);
solve();
ll l=0,r=0,ans=0;
for(int i = 1,x,y; i <= m; i++){
scanf("%d%d",&x,&y);
data[i]={x,y,LCA(x,y)};
r=max(r,dis[x]+dis[y]-2*dis[LCA(x,y)]);
}
while(l<=r){
ll mid=(l+r)>>1;
if(check(mid))ans=mid,r=mid-1;
else l=mid+1;
}
printf("%lld\n",ans);
return 0;
}