水P1589 【泥泞路】
greenheadstrange · · 题解
贪心大法好啊好,不卡常,不超时,简单代码就AC。
言归正传,首先将每条线段按照起始端点进行从小到大的排序。然后在一个for循环搜一遍。
时间复杂度O(nlogn)
废话少说,直接上代码:
#include<bits/stdc++.h>
using namespace std;
struct note{
int l,r;
}a[10005];//定义结构体
int n,m,ans;
bool cmp(const note&aa,const note&bb){
return aa.l<bb.l;
}//按照始端点从小到大排序
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)scanf("%d%d",&a[i].l,&a[i].r);
sort(a+1,a+n+1,cmp);
int x=0;//x表示当前的木板铺到了哪里
for(int i=1;i<=n;i++){
x=max(x,a[i].l);//如果x小于当前泥泞路的始端点
while(x<a[i].r){
x+=m;//加上木板长度
ans++;//答案总数加1
}
}
printf("%d",ans);
return 0;
}
结束语:OI路上困难重重,唯有静下来,才能成为顶尖高手