区间覆盖问题
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic Discuss
Problem Description
设x1 , x2 ,…… , xn 是实直线上的n 个点。用固定长度的闭区间覆盖这n 个点,至少需要多少个这样的固定长度闭区间?
对于给定的实直线上的n个点和闭区间的长度k,设计解此问题的有效算法,计算覆盖点集的最少区间数,并证明算法的正确性。
对于给定的实直线上的n个点和闭区间的长度k,设计解此问题的有效算法,计算覆盖点集的最少区间数,并证明算法的正确性。
Input
输入数据的第一行有2 个正整数n和k(n≤10000,k≤100),表示有n个点,且固定长度闭区间的长度为k。接下来的1 行中,有n个整数,表示n个点在实直线上的坐标(可能相同)。
Output
输出一个整数,表示计算出的最少区间数输出。
Sample Input
7 3 1 2 3 4 5 -2 6
Sample Output
3
解题报告:水题不解释。
ac代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>using namespace std;int a[10000 + 5];
int main()
{int n,k;scanf("%d %d",&n,&k);for(int i = 0; i<n; i++) {scanf("%d",&a[i]);}sort(a,a+n);int ans=1,cur=a[0]+k;for(int i = 0; i<n; i++) {if(a[i]<=cur) continue;else {cur=a[i]+k;ans++;}}printf("%d\n",ans); return 0 ;
}
总结: