Codeforces Round #394 (Div. 2) D. Dasha and Very Difficult Problem(贪心+构造)
链接:https://codeforces.com/contest/761/problem/D
贪心+构造;
题意:给定a,b,c三个数组,规定ci=bi-ai;现在给出a和离散化的c数组(1~n的数字),问可否构造出一组b
对p排个序,ai为定值,ci=bi-ai,ci最小时,bi最小
贪心,小的显然要最小,对于每个数,二分(l~r)找一个合格的b,判断一下即可;
代码;
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn = 1e5+7; 4 long long l,r,a[maxn],b[maxn],c[maxn]; 5 int n,p[maxn]; 6 priority_queue<pair<int ,int> > s; 7 int main() 8 { 9 scanf("%d%lld%lld",&n,&l,&r); 10 for(int i=0; i<n; i++) scanf("%lld",&a[i]); 11 for(int i=0; i<n; i++) scanf("%d",&p[i]),s.push(make_pair(p[i],i)); 12 long long last=-1e16; 13 while(!s.empty()) 14 { 15 long long now=s.top().second; 16 s.pop(); 17 long long L=l,R=r,ans=r+1; 18 while(L<=R) 19 { 20 long long mid=(L+R)/2; 21 if(a[now]-mid>last) 22 { 23 ans=mid; 24 L=mid+1; 25 } 26 else 27 R=mid-1; 28 } 29 if(ans==r+1) 30 { 31 cout<<-1<<endl; 32 return 0; 33 } 34 b[now]=ans; 35 last=a[now]-ans; 36 } 37 for(int i=0; i<n; i++) 38 cout<<b[i]<<" "; 39 cout<<endl; 40 return 0;
41 }
另:bi=ai+ci,如果bi中最大和最小的差值是大于r-l,那么无论如何,都不会成功构造;
如果符合,给每个bi加上l-mi,从而使bi在l~r内;
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn = 1e5+7; 4 long long l,r,a[maxn],b[maxn],c[maxn]; 5 int n,p[maxn]; 6 int main() 7 { 8 scanf("%d%lld%lld",&n,&l,&r); 9 for(int i=0; i<n; i++) 10 scanf("%lld",&a[i]); 11 for(int i=0; i<n; i++) 12 scanf("%d",&p[i]); 13 long long ma=0,mi=1e18; 14 for(int i=0; i<n; i++) 15 { 16 b[i]=a[i]+p[i]; 17 ma=max(ma,b[i]); 18 mi=min(mi,b[i]); 19 } 20 if(ma-mi>r-l) 21 { 22 printf("-1\n"); 23 return 0; 24 } 25 int k=l-mi; 26 for(int i=0; i<n; i++) 27 printf("%lld ",b[i]+k); 28 return 0; 29 }