0%

Surveillance 题解

Surveillance 题解

$\color{lightgreen}Status: OK$

题目大意

给你一个环和若干条覆盖环的线段,求覆盖整个环所需的最小的线段数量。

解题思路

看到环,就要化环为链,先复制一份在后面,之后再把线段存进去。

于是,问题变成了,在长度为 $2n$ 的链上,选出一些线段,使其能覆盖大于等于 $n$ 的链。

这个问题是可以贪心的。假设现在在位置 $i$,那么要选的线段一定是覆盖位置 $i$,且右端点最大的线段,这样才能最优。

这个东西可以用一个 set 或优先队列维护。

但是,直接枚举起点,再这样搞,时间复杂度可能达到 $O(n^2\log n)$,无法通过。

我们可以对每一个位置,把它能跳到的最远的位置算出来,时间复杂度为 $O(n\log n)$。

之后利用倍增的思想,把每个位置跳 $2^i$ 次到达的位置算出来,这样枚举起点之后,每个起点的求解就是 $O(n\log n)$ 了。

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<bits/stdc++.h>
using namespace std;
const int N = 2e6+10;
int n,k,st[N][21],ans;
set<int> s;
struct lin{
int l,r;
} l[N];
bool cmp(lin x,lin y){
return x.l<y.l;
}
void pre(){
for (int i=1;i<=20;i++){
for (int j=1;j<=n*2;j++){
if (st[j][i-1]) st[j][i] = st[st[j][i-1]+1][i-1];
}
}
}
void chk(int x){
int cnt = 1,tmp = x;
for (int i=20;i>=0;i--){
if (st[x][i]>=x && st[x][i]<tmp+n-1) x = st[x][i]+1,cnt+=(1<<i);
}
if (st[x][0]>=tmp+n-1) ans = min(ans,cnt);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
while (cin>>n>>k){
int x,y;
ans = 0x3f3f3f3f;
s.clear();
for (int i=1;i<=k;i++){
cin>>x>>y;
if (x>y) y+=n;
l[i].l = x;
l[i].r = y;
}
sort(l+1,l+1+k,cmp);
int now = 1;
for (int i=1;i<=n*2;i++){
while (l[now].l == i && now<=k){
s.insert(l[now].r);
now++;
}
st[i][0] = 0;
if (!s.empty()){
auto it = s.end();
it--;
if (*it>=i) st[i][0] = *it;
}
}
pre();
for (int i=1;i<=n;i++) chk(i);
if (ans == 0x3f3f3f3f) cout<<"impossible"<<"\n";
else cout<<ans<<"\n";
for (int i=1;i<=2*n;i++) for (int j=1;j<=20;j++) st[i][j] = 0;
}
return 0;
}