算法竞赛打卡

 
}

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

deep_Miner

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值