思路
这道题不是很好想,如果硬要做的话,就只能暴搜了。可是暴搜显然会超时,该怎么优化呢?
注意到题目中有一个很特别的条件:测试示例中的公交线路数量将 。也就是说,我们如果以公交线路的数量作为搜索树的层数,那么这个问题就变成了一个标准的 IDDFS!
我们可以将每条能覆盖所有范围内时间点的路线存储起来,并根据覆盖时间点的数量降序排序。于是在 DFS 中,我们只需要枚举要选择的线路就可以了,并在 DFS 完毕后回溯。
这里依然可以加入一个可行性剪枝:如果当前已经覆盖的结点数量加上贪心能覆盖的最多结点数量还是不能覆盖全部,就直接返回假,也就是没有找到答案,提高程序的运行效率。可行性剪枝是 IDDFS 中非常常用且实用的一种剪枝方法。
最后,完整代码如下:
#include <bits/stdc++.h>
#define debug(x) (cout << #x << " " << x << "\n")
using namespace std;
using ll = long long;
const int N = 1505;
struct node {
int x, d, num;
} q[N];
int n, s[N], lim, cnt;
bool check(int x, int d) {
for (int i = x; i < 60; i += d) if (!s[i]) {
return 0;
}
return 1;
}
bool dfs(int cur, int k, int sum) {
if (cur == lim) return sum == n;
if (sum + q[k].num * (lim - cur) < n) return 0;
for (int i = k; i <= cnt; i++) if (check(q[i].x, q[i].d)) {
for (int j = q[i].x; j < 60; j += q[i].d) s[j] --;
if (dfs(cur + 1, i, sum + q[i].num)) return 1;
for (int j = q[i].x; j < 60; j += q[i].d) s[j] ++;
}
return 0;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 1, x; i <= n; i++) cin >> x, s[x] ++;
lim = 0;
for (int i = 0; i < 60; i++) {
for (int j = i + 1; i + j < 60; j++) if (check(i, j)) {
cnt ++;
q[cnt] = {i, j, (59 - i) / j + 1};
}
}
sort(q + 1, q + 1 + cnt, [&](const node &x, const node &y) {
return x.num > y.num;
});
while (!dfs(0, 1, 0)) lim ++;
cout << lim;
return 0;
}