Problem
有一条长为l的公路(可看为数轴),n盏路灯,每盏路灯有照射区间且互不重叠。
有个人要走过这条公路,他只敢在路灯照射的地方唱歌,固定走p唱完一首歌,歌曲必须连续唱否则就要至少走t才能继续唱。
问最多能唱多少首歌
Solution
贪心:对于一段照射区间要么不唱歌要么能唱多久唱多久
提早结束,后面提早开始,和延迟结束,准时开始效果是一样的
DP,f[i]表示到第 i 段为止最多能唱多少首歌,g[i]表示唱完f[i]首歌的最左的端点。
f[i]=f[j]+(r-max(l,g[j]+t))/p
g[i]=r-(r-max(l,g[j]+t))%p
这样时间复杂度是O(N^2)
我们可以发现,转移必定来源于最后一个g[j] + t <= l[i]到最后一个g[j] + t <= r[i]的j
又因为r[i] < l[i + 1],所以每次转移的第一个必定是前一个转移的最后一个或后面的j
Notice
注意当f相等时但g更小是也要更新
Code
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define sqz main
#define ll long long
#define reg register int
#define rep(i, a, b) for (reg i = a; i <= b; i++)
#define per(i, a, b) for (reg i = a; i >= b; i--)
#define travel(i, u) for (reg i = head[u]; i; i = edge[i].next)
const int INF = 1e9, N = 100000;
const double eps = 1e-6, phi = acos(-1.0);
ll mod(ll a, ll b) {if (a >= b || a < 0) a %= b; if (a < 0) a += b; return a;}
ll read(){ ll x = 0; int zf = 1; char ch; while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
if (ch == '-') zf = -1, ch = getchar(); while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return x * zf;}
void write(ll y) { if (y < 0) putchar('-'), y = -y; if (y > 9) write(y / 10); putchar(y % 10 + '0');}
int f[N + 5], g[N + 5], Left[N + 5], Right[N + 5], ans = 0;
int sqz()
{
int l = read(), n = read(), p = read(), t = read();
rep(i, 1, n) Left[i] = read(), Right[i] = read();
int last = 0;
g[0] = -t;
rep(i, 1, n) g[i] = INF;
rep(i, 1, n)
{
while (g[last + 1] + t <= Left[i] && last < n) last++;
while (g[last] + t <= Right[i] && last <= n)
{
if (f[last] + (Right[i] - max(Left[i], g[last] + t)) / p > f[i] ||
f[last] + (Right[i] - max(Left[i], g[last] + t)) / p == f[i] &&
Right[i] - (Right[i] - max(Left[i], g[last] + t)) % p < g[i])
{
f[i] = f[last] + (Right[i] - max(Left[i], g[last] + t)) / p;
g[i] = Right[i] - (Right[i] - max(Left[i], g[last] + t)) % p;
}
last++;
}
last--;
if (f[i - 1] > f[i] || f[i - 1] == f[i] && g[i - 1] < g[i])
{
f[i] = f[i - 1];
g[i] = g[i - 1];
}
ans = max(ans, f[i]);
}
printf("%d
", ans);
}