跳到正文

题解

CF1851G Vlad and the Mountains 题解

Rain_zyl约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年1月27日
更新
2026年1月27日
篇幅
约 4 分钟
题目
CF1851G

版本

  1. v1当前

题目大意

给定一个 nn 个节点,mm 条边的无向图,每个点有点权 hih_i,走一条边 i→ji\rightarrow j 的能量消耗为 hj−hih_j-h_i。若干次询问初始携带 ee 的能量,能否从 ss 走到 tt,使得过程中能量不会小于 00。

题目分析

典。一条路径相当于一条链,而这种相减的式子可以很容易想到通过求和消除其中的项。i→j→ki\rightarrow j\rightarrow k 可行的条件为 hj−hi≤eh_j-h_i\le e,hk−hj+hj−hi≤eh_k-h_j+h_j-h_i\le e。所以 hj,hk≤hi+eh_j,h_k\le h_i+e。所以得到路径上的点 xx 只需要满足 hx≤hs+eh_x\le h_s+e。离线查询并用并查集维护连通性即可,边 (x,y)(x,y) 的边权可以当做 max⁡(hx,hy)\max (h_x,h_y)。

C++
#include<bits/stdc++.h>
#define ll long long
#define int ll
#define L xd[x].l
#define R xd[x].r
#define mid (l+r>>1)
#define lc L,l,mid
#define rc R,mid+1,r
#define OK Ll<=l&&r<=Rr
#define Root 1,1,n
#define rep(x,y,z) for(int x=(y);x<=(z);x++)
#define per(x,y,z) for(int x=(y);x>=(z);x--)
#define pb push_back
#define ull unsigned ll
#define e(x) for(int i=h[x],y=to[i];i;i=nxt[i],y=to[i])
#define E(x) for(auto y:p[x])
#define Pi pair<int,int>
#define ui unsigned ll
inline int read(){int s=0,w=1;char c=getchar();while(c<48||c>57) {if(c=='-') w=-1;c=getchar();}while(c>=48&&c<=57)s=(s<<1)+(s<<3)+c-48,c=getchar();return s*w;}
inline void pf(ll x){if(x<0) putchar('-'),x=-x;if(x>9)pf(x/10);putchar(x%10+48);}
const int N =2e5+5,M=5e6+5,inf=(1LL<<31)-1;
const ll llf=1e18,mod=1e9+7;
using namespace std;
int T=read(),n,m,q,a[N];
struct edge{
	int x,y,w;
}e[N];
int s[N],tp,f[N],out[N];
inline int find(int x){
	return f[x]==x?x:f[x]=find(f[x]);
}
struct node{
	int s,t,w,id;
}sol[N];
inline bool cmp(edge a,edge b){
	return a.w<b.w;
}
inline bool Cmp(node c,node d){
	return a[c.s]+c.w<a[d.s]+d.w;
}
signed main(){
	while(T--){
		n=read(),m=read();
		rep(i,1,n)a[i]=read(),f[i]=i;
		rep(i,1,m)e[i].x=read(),e[i].y=read(),e[i].w=max(a[e[i].x],a[e[i].y]);
		sort(e+1,e+m+1,cmp);
		q=read();
		rep(i,1,q)sol[i].s=read(),sol[i].t=read(),sol[i].w=read(),sol[i].id=i;
		sort(sol+1,sol+q+1,Cmp);
		int Ll=1;
		rep(i,1,q){
			while(Ll<=m&&e[Ll].w<=a[sol[i].s]+sol[i].w)f[find(e[Ll].x)]=find(e[Ll].y),Ll++;
			out[sol[i].id]=(find(sol[i].s)==find(sol[i].t));
		}
		rep(i,1,q)if(out[i])cout <<"Yes\n";
		else cout <<"No\n";
		cout <<'\n';
	}
	return 0;
}
原文