0
点赞
收藏
分享

微信扫一扫

2021 年百度之星·程序设计大赛 - 初赛二 1002 随机题意(区间贪心)

玉新行者 2023-03-12 阅读 73


problem

随机题意 Accepts: 1411 Submissions: 3641
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem Description
给一个整数数组 a_1,a_2,\cdots,a_na
1

,a
2

,⋯,a
n

和 kk ,你想要找到一个最大的值 xx ,使得存在另一个整数数组 b_1,b_2,\cdots, b_nb
1

,b
2

,⋯,b
n

满足 |a_i-b_i|\leq k(1\leq i\leq n)∣a
i

−b
i

∣≤k(1≤i≤n) 且 {b_n}b
n

中共有 xx 个不同的数。

Input
第一行一个正整数 T(1\leq T\leq 10)T(1≤T≤10) ,代表测试组数。

接下来 TT 组数据中,每组数据的第一行包含包含两个整数 n,k(1\leq n\leq 100000,0\leq k\leq 10^9)n,k(1≤n≤100000,0≤k≤10
9
) 。

第二行包含 nn 个整数 a_1,a_2,\cdots,a_n(1\leq a_i\leq 10^9)a
1

,a
2

,⋯,a
n

(1≤a
i

≤10
9
) 。

Output
TT 行,每行一个整数 xx ,代表每组数据的答案。

Sample Input
1
6 1
1 2 2 2 2 3
Sample Output
Copy
5

solution

  • 考虑到ai-k<=bi<=ai+k,可以将n个输入的ai转换为n个区间,原题目转换为在n个区间中选尽可能多的区间。
  • 可以贪心的按照左端点从小到大排序,然后从左往右选。

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 998244353;
const int maxn = 1e5+10;
struct node{LL l, r;}a[maxn];
bool cmp(node x, node y){return x.l!=y.l?x.l<y.l:x.r<y.r;}
int main(){
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int T; cin>>T;
while(T--){
LL n, k; cin>>n>>k;
for(int i = 1; i <= n; i++){
LL x; cin>>x;
a[i] = (node){x-k,x+k};
}
sort(a+1,a+n+1,cmp);
//for(int i = 1; i <= n; i++)
// cout<<a[i].l<<" "<<a[i].r<<"\n";
LL t = a[1].l, cnt = 1;//t表示上一次选的位置
for(int i = 2; i <= n; i++){
if(a[i].l>t){
cnt++;
t = a[i].l;
}else if(a[i].r>t){
cnt++;
t = t+1;
}
}
cout<<cnt<<"\n";
}
return 0;
}

/*
ai-k<=bi<=ai+k

*/


举报

相关推荐

0 条评论