题意:给定n个泥坑路面的初末位置,判断最少需要几个桥才能覆盖这些路面。
贪心法,从每个泥坑的开始位置建桥,然后判断是否覆盖后面的路面,就是分类讨论了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
struct Seg{
int l, r;
Seg(int l = 0, int r = 0) :l(l), r(r){}
bool operator < (const Seg & rhs) const {
return l < rhs.l;
}
};
Seg v[10240];
int main()
{
ios::sync_with_stdio(false);
int n, l; cin >> n >> l;
for (int i = 0; i < n; ++i) cin >> v[i].l >> v[i].r;
sort(v, v + n);
int cnt = 0, pos = 0;
for (int i = 0; i < n; ++i){
if (pos >= v[i].r) continue;
if (pos <= v[i].l) {
int len = v[i].r - v[i].l;
int cur = (len + l - 1) / l;
pos = v[i].l + cur * l;
cnt += cur;
}
else{
int len = v[i].r - pos;
int cur = (len + l - 1) / l;
pos += cur * l;
cnt += cur;
}
}
cout << cnt << endl;
return 0;
}