}
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#define N 1010
using namespace std;
int sum[N][N];
int C;
vector< pair<int,int> >spot;
vector<int>a;
int query(int x){
return lower_bound(a.begin(),a.end(),x)-a.begin();
}
bool check(int len){
for(int x1=1,x2=1;x2<a.size();x2++){
while(a[x2]-a[x1]+1>len) x1++;
for(int y1=1,y2=1;y2<a.size();y2++){
while(a[y2]-a[y1]+1>len) y1++;
if(sum[x2][y2]-sum[x1-1][y2]-sum[x2][y1-1]+sum[x1-1][y1-1]>=C) return true;
}
}
return false;
}
int main(){
int n;
scanf("%d %d",&C,&n);
a.push_back(0);
for(int i=1;i<=n;i++){
int x,y;
scanf("%d %d",&x,&y);
a.push_back(x);
a.push_back(y);
spot.push_back(make_pair(x,y));
}
sort(a.begin(),a.end());
a.erase(unique(a.begin(),a.end()),a.end());
for(int i=0;i<n;i++){
int x=query(spot[i].first);
int y=query(spot[i].second);
sum[x][y]++;
}
for(int i=1;i<a.size();i++){
for(int j=1;j<a.size();j++){
sum[i][j]=sum[i][j]+sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1];
}
}
int l=1,r=10000;
while(l<r){
int mid=(l+r)/2;
if(check(mid)) r=mid;
else l=mid+1;
}
printf("%d",l);
return 0;
}
/*
11 12 13 23 11 11 12 24 24 21
*/
该代码运用了离散化知识:
离散化就是将一些较大的数映射为较小的数,若要查询数字x被映射成哪个数,可通过二分查找,
通常可使用lower_bound或者upper_bound
int query(int x){
return upper_bound(a.begin(),a.end(),x)-a.begin();
}
int main(){
for(int i=1;i<=10;i++){
int x;
scanf("%d",&x);
a.push_back(x);
}
sort(a.begin(),a.end());
a.erase(unique(a.begin(),a.end()),a.end());
for(int i=1;i<=3;i++){
int x;
scanf("%d",&x);
printf("%d\n",query(x));
}
printf("%d",a[1]);
数据如下,用可变数组vector,查询时返回的下标是从0开始编号
可按顺序访问时,是从0开始编号upper是查找第一个大于x的数
可有时候为防止越界,常需要让数组从1开始编号,通常的做法就是插入一个0进去如最上面的代码所示
使用vector数组的好处就是减少一个数组的开销,能够配合unique和erase一起使用
将数据进行离散化的最大好处就是能够节约数组空间,防止runtime