P4149 [IOI 2011] Race 解题报告

· · 题解

题意:

给一棵树,每条边有权。求一条简单路径,权值和等于 k ,且边的数量最小,求最小边数。

思路

拿到题目后我们会发现所谓路径要么是单独的一条向上的链,要么是两条向上的链拼起来的链。于是我们可以给每个点维护一个集合,表示子树内某一点到当前的点。为了查找值为 k 的路径,我们可以在儿子向父亲转移时,暴力枚举一个集合,设值为 w 再在另一个集合中二分找到另一个值为 k-w 且深度最小的点,这样可以保证满足要求并且路径最短,计算路径使用经典公式 dep_x+dep_y-2 \times dep_{LCA}即可,保证复杂度只需要启发式合并,扫较小集合即可,复杂度 O(n\log^2 n)。

#include<bits/stdc++.h>
#define int  long long 
#define mk make_pair
using namespace std;
const int MAXN=2e5+10;
int n,k,head[MAXN],tot,d[MAXN],w[MAXN];
set<pair<int,int> >st[MAXN];
struct node{
    int to,nxt,w;
}a[MAXN<<1];
inline void add(int x,int y,int w){
    a[++tot].to=y;
    a[tot].nxt=head[x];
    a[tot].w=w;
    head[x]=tot;
}
int ans;
void dfs(int now,int f){
    d[now]=d[f]+1;
    st[now].insert(mk(w[now],d[now]));
    for(int i=head[now];i;i=a[i].nxt){
        int to=a[i].to;
        if(to==f) continue;
        w[to]=w[now]+a[i].w;dfs(to,now);
        if(st[now].size()<st[to].size()) st[now].swap(st[to]);
        for(auto x:st[to]){
            auto pos=st[now].lower_bound(mk(k+2*w[now]-x.first,0));
            if(pos==st[now].end()) continue;
            if(pos->first+x.first-2*w[now]==k){
                ans=min(ans,pos->second+x.second-2*d[now]);
            }
        }
        for(auto x:st[to]) st[now].insert(x);
    }
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL),cout.tie(NULL);
    cin>>n>>k;ans=n+1;
    for(int i=1;i<n;i++){
        int u,v,w;cin>>u>>v>>w;u++;v++;
        add(u,v,w);add(v,u,w);
    }dfs(1,0);
    cout<<(ans==n+1?-1:ans);
    return 0;
}