题目链接:http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1550 分析:枚举环的缺口,其中在每一次枚举中我用线段树做的统计。另一个优化是线段树更新时,如果区间已经被全部覆盖,就不必更新了(不加这个优化会TLE)。 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define mp make_pair #define X first #define Y second #define LL(x) ((x) << 1) #define RR(x) ((x) << 1 | 1) #define MEMSET(a, b) memset(a, b, sizeof(a)) using namespace std; typedef unsigned int ui; typedef long long ll; typedef unsigned long long ull; typedef pair pii; typedef vector vi; typedef vi::iterator vi_it; typedef map mii; typedef priority_queue pqi; typedef priority_queue , greater > rpqi; typedef priority_queue pqp; typedef priority_queue , greater > rpqp; const int MAX_N = 1000 + 2; const int MAX_P = 10000 + 2; pii edge[MAX_P]; struct { int left; int right; int cnt; int sum; inline int mid() { return (left + right) >> 1; } } st[MAX_N * 6]; void build(int l, int r, int idx) { st[idx].left = l; st[idx].right = r; st[idx].cnt = st[idx].sum = 0; if (l != r) { int mid = st[idx].mid(); build(l, mid, LL(idx)); build(mid + 1, r, RR(idx)); } } inline void update(int idx) { if (st[idx].cnt) { st[LL(idx)].cnt += st[idx].cnt; st[LL(idx)].sum = st[LL(idx)].right - st[LL(idx)].left + 1; st[RR(idx)].cnt += st[idx].cnt; st[RR(idx)].sum = st[RR(idx)].right - st[RR(idx)].left + 1; st[idx].cnt = 0; } } void update(int l, int r, int v, int idx) { if (st[idx].sum == st[idx].right - st[idx].left + 1) { return; } if (l <= st[idx].left && st[idx].right <= r) { st[idx].cnt += v; st[idx].sum = st[idx].right - st[idx].left + 1; return; } update(idx); int mid = st[idx].mid(); if (l <= mid) update(l, r, v, LL(idx)); if (r > mid) update(l, r, v, RR(idx)); st[idx].sum = st[LL(idx)].sum + st[RR(idx)].sum; } int main(int argc, char *argv[]) { // freopen("D:\\in.txt", "r", stdin); int n, p; cin >> n >> p; for (int i = 0; i < p; ++i) { scanf("%d%d", &edge[i].X, &edge[i].Y); } int ans = n - 1; for (int i = 1; i <= n; ++i) { int s = i, t = s + n - 1; build(s, t - 1, 1); for (int j = 0; j < p; ++j) { int x = edge[j].X, y = edge[j].Y; if (x < s) x += n; if (y < s) y += n; if (x > y) x += y, y = x - y, x -= y; update(x, y - 1, 1, 1); } if (ans > st[1].sum) ans = st[1].sum; } cout << ans << endl; return 0; }