题解:CF1851G Vlad and the Mountains

· · 题解

大佬们都说这题简单,但我感觉还是有点小难的。

问题分析

本题要求判断 Vlad 能否从山 a 出发到达山 b,给定初始能量 e。

关键约束是:当从山 i 移动到山 j 时,需要消耗 h_i-h_j 单位能量,如果该值为正,则当前能量必须足够覆盖这个消耗;如果为负,则能量会增加。

解题思路

本题可以通过并查集实现高效求解。

对于一条连接 u 和 v 的边,能通过这条边的能量约束可以转化为约束。

我们可以按能量约束从小到大处理所有查询,动态添加满足当前约束的边。

不难发现,对于每两个山之间,理论的能量最大值是 h_a+e(这个不懂可以看下面)。

具体分析:

对于边 (u,v),通过这条边的最大能量门槛是 \max (h_u,h_v)。

若 h_u \ge h_v,从 u 到 v 不需要消耗能量(实际会恢复)。

若 h_v \ge h_u,从 u 到 v 需要消耗 h_v-h_u 能量。

对于查询 (a,b,e),Vlad 能到达的最大高度是 h_a+e 所有最大高度不超过 h_a+e 的边都可以被使用。

代码

可以看看那几个大佬的代码,也可以看看我的(本人码风不好,见谅)。

//byjiygzwyzshwsf
#include<bits/stdc++.h>
#define int long long 
using namespace std;
typedef pair<int,int> PLL;
int n,m;
int f[200010];
int h[200010];
int find(int x){
    if(f[x]!=x){
        f[x]=find(f[x]);
    }
    return f[x];
}
struct node{
    int u,v,w,idx;
};
vector<node>vv;
vector<node>ed;
bool cmp(node x,node y){
    return x.w<y.w;
}
bool cmpp(node x,node y){
    return h[x.u]+x.w<h[y.u]+y.w;
}
void init(){
    vv.clear();
    ed.clear();
}
int ans[200010];
signed main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int T;
    cin>>T;
    while(T--){
        init();
        cin>>n>>m;
        for(int i=1;i<=n;i++){
            cin>>h[i];
            f[i]=i;
        }
        for(int i=1;i<=m;i++){
            int u,v;
            cin>>u>>v;
            vv.push_back({u,v,max(h[u],h[v]),0ll});
        }
        sort(vv.begin(),vv.end(),cmp);
        int q;
        cin>>q;
        for(int i=0;i<q;i++){
            int a,b,e;
            cin>>a>>b>>e;
            ed.push_back({a,b,e,i});
        }
        sort(ed.begin(),ed.end(),cmpp);
        int cnt=0;
        for(int i=0;i<ed.size();i++){
            int a=ed[i].u;
            int b=ed[i].v;
            int sum=ed[i].w;
            int idx=ed[i].idx;
            while(cnt<m&&vv[cnt].w<=h[a]+sum){
                int fa=find(vv[cnt].u);
                int fb=find(vv[cnt].v);
                if(fa!=fb){
                    f[fa]=fb;
                }
                cnt++;
            }
            if(find(a)==find(b)){
                ans[idx]=1;
            }
            else ans[idx]=0;
        }
        for(int i=0;i<q;i++){
            if(ans[i]){
                cout<<"YES\n";
            }
            else cout<<"NO\n";
        }
        cout<<"\n";
    }
    return 0;
}