题目链接:泥泞路
主要用到的算法就是:贪心算法。
一开始我的想法是,用一个数组,模拟木板所铺出的路。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
// #define int long long
#define xx first
#define yy second
pair<int, int> f[N];
int street[N];
int ans, cnt;
bool cmp(pair<int, int> p1, pair<int, int> p2)
{
if (p1.xx == p2.xx)
return p1.yy < p2.yy;
return p1.xx < p2.xx;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n, l;
cin >> n >> l;
for (int i = 0; i < n; i++)
cin >> f[i].xx >> f[i].yy;
sort(f, f + n, cmp);
for (int i = 0; i < n; i++)
{
cnt = f[i].xx+1;
while (street[f[i].yy] == 0)
{
if (street[cnt])
cnt++;
else
{
for (int j = 0; j < l; j++)
{
street[cnt++] = 1;
}
ans++;
}
}
}
cout << ans << endl;
return 0;
}
但是这个代码有一个问题,题目的数据范围
对于 100 % 100 \% 100% 的数据, n , L ≤ 10000 n,L \leq 10000 n,L≤10000, s ≤ e ≤ 1 0 9 s \leq e \leq 10^9 s≤e≤109。
这个代码仅能够解决,,s,e在1e6以下时的情况。所以用数组模拟整个铺路的状况是不可以的(数组大小无法开到1e9)
所以这个题目,应该是针对每一段泥泞路进行处理,不能对整个路段用数组进行模拟。
#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;
}
其中x=max(x,a[i].l),这一行代码是关键,能够时刻更新x,使用x对下一段泥泞路进行处理。