题目大意:
给出若干个区间,每次在一个区间内选择一个数 x x x后,那么该数的波动范围 [ x − k , x + k ] [x-k,x+k] [x−k,x+k]必须和下一个区间有交集,然后可以从交集中任取一个数再判断下下一个区间,以此类推…
思路
假设我们从第一个区间 [ a , b ] [a,b] [a,b]内开始取数,那么第一个区间的最大取值范围是 [ m a x ( 0 , a − k ) , b + k ] [max(0,a-k),b+k] [max(0,a−k),b+k],我们要保证取得的数既在下一个区间内,然后又对下下一个区间不会产生不可取数的影响,这样单方向的贪心似乎行不通。从前向后看的话,后面的取数依赖于前面的取数,如果从后向前,那么就是前面的取数依赖于后面的取数,假设我们从后向前求出每个集合在当前位置的可取区间,这个区间仅仅是保证了后面不会对前面产生影响,此时一个必须且大胆的想法是,我再从前向后地求出每个集合的可取区间,这样两者取交集,得到的是既不会对后面产生影响,也不会对前面产生依赖。显然这种贪心方法是正确的
p r e pre pre数组表示每个区间的前一区间的波动区间, s u b sub sub数组表示每一区间的后一个波动区间; L L L数组表示每个位置从前向后可取的区间, R R R数组表示从后向前可取的区间,最后只需对 L , R L,R L,R取交集然后随便取一个数输出
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int Mod=1e9+7;
typedef long long ll;
typedef pair<ll,ll> pii;
const int maxn=1e5+10;
pii a[maxn],pre[maxn],sub[maxn],L[maxn],R[maxn];
vector<int> ans;
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int t,n;
ll k;
cin>>t;
while(t--){
cin>>n>>k;
for(int i=1,x,y;i<=n;i++){
cin>>x>>y;
a[i]={x,y};
}
for(int i=1;i<=n;i++){
if(i==1){
pre[i]={max(0LL,a[i].first-k),a[i].second+k};
L[i]={a[i].first,a[i].second};
}else if(i==n){
int l=max(pre[i-1].first,a[i].first),r=min(pre[i-1].second,a[i].second);
if(l>r) goto undone;
pre[i]=L[i]={l,r};
}else{
int l=max(pre[i-1].first,a[i].first),r=min(pre[i-1].second,a[i].second);
if(l>r) goto undone;
L[i]={l,r};
pre[i]={max(0LL,l-k),r+k};
}
//cout<<"pre: "<<pre[i].first<<" "<<pre[i].second<<"\n";
}
for(int i=n;i>=1;i--){
if(i==n){
sub[i]={max(0LL,a[i].first-k),a[i].second+k};
R[i]={a[i].first,a[i].second};
}else if(i==1){
int l=max(sub[i+1].first,a[i].first),r=min(sub[i+1].second,a[i].second);
if(l>r) goto undone;
sub[i]=R[i]={l,r};
}else{
int l=max(sub[i+1].first,a[i].first),r=min(sub[i+1].second,a[i].second);
if(l>r) goto undone;
R[i]={l,r};
sub[i]={max(0LL,l-k),r+k};
}
//cout<<"sub: "<<sub[i].first<<" "<<sub[i].second<<"\n";
}
ans.clear();
for(int i=1;i<=n;i++){
int l=max(L[i].first,R[i].first),r=min(L[i].second,R[i].second);
//cout<<l<<" "<<r<<endl;
if(l>r) goto undone;
ans.push_back(l);
}
cout<<"YES\n";
for(auto i: ans) cout<<i<<" ";
cout<<"\n";
continue;
undone:
cout<<"NO\n";
}
return 0;
}