链接
https://ac.nowcoder.com/acm/contest/180/C
题意
有1-n共n个城市,城市i与城市i-1相连接,现在有m个要求,每个要求包含两个城市x、y,即它们二者不能相通,问要满足这些要求,最小需要断掉几个城市的连接;
分析
考虑一个很显然的 O ( m l o g m ) O(mlogm) O(mlogm)的做法,首先对所有线段按照右端点排序,然后每次在右端点处切,但是m达到了107,级别,所以不能通过此题
由于题目保证所有线段的值域为1−n,我们可以对所有左端点,直接记录出右端点最靠左的位置同样每次切右端点,扫一遍即可,时间复杂度: O ( m ) O(m) O(m)
代码
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map>
#define INF 0x7f7f7f7f
#define MAXN 100005
#define N 200005
#define P 2
#define MOD 99991
typedef long long ll;
namespace fastIO {
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? EOF : *p1++)
char buf[(1 << 22)], *p1 = buf, *p2 = buf;
inline int read() {
char c = getchar(); int x = 0, f = 1;
while (c < '0' || c > '9') { if (c == '-') f = -1; c = getchar(); }
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
}
using namespace fastIO;
using namespace std;
int n, m, R[10000077];
int main() {
n = read(), m = read();
int l, r;
for (int i = 1; i <= n; i++)
R[i] = n + 1;
for (int i = 1; i <= m; i++) {
l = read(), r = read();
R[l] = min(r, R[l]);
}
int res = 0;
r = 0;
for (int i = 1; i < n; i++) {
if (R[i] == n + 1)continue;
if (i >= r) {
res++;
r = R[i];
}
else r = min(r, R[i]);
}
cout << res << endl;
}