intmain(){ int n = rd(); for (int i = 1; i <= n; ++i) { int l = rd(), r = rd(); a[i].first = r; a[i].second = l; } sort(a + 1, a + 1 + n); int mxpos = 0, ans = 0; for (int i = 1; i <= n; ++i) { if (mxpos < a[i].second) { ++ans; mxpos = a[i].first; } } cout << ans << endl; return0; }
#include<bits/stdc++.h> usingnamespacestd; #define N 1000007 typedeflonglong ll;
inlineintrd(){ int x = 0; bool f = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) f |= (c == '-'); for (; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48); return f ? -x : x; }
intmain(){ int n = rd(); for (int i = 1; i <= n; ++i) { int l = rd(), r = rd(); a[i].first = r - 1; a[i].second = l; } sort(a + 1, a + 1 + n); int mxpos = -1, ans = 0; for (int i = 1; i <= n; ++i) { if (mxpos < a[i].second) { ++ans; mxpos = a[i].first; } } cout << ans << endl; return0; }
#include<bits/stdc++.h> usingnamespacestd; #define N 2000007 typedeflonglong ll;
inlineintrd(){ int x = 0; bool f = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) f |= (c == '-'); for (; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48); return f ? -x : x; }
intmain(){ int n = rd(); for (int i = 1; i <= n; ++i) { int l = rd(), r = rd(); if (l > r) swap(l, r); a[i].first = r - 1; a[i].second = l; } sort(a + 1, a + 1 + n); int mxpos = 0, ans = 0; for (int i = 1; i <= n; ++i) { if (mxpos < a[i].second) { ++ans; mxpos = a[i].first; } } cout << ans << endl; return0; }
最小覆盖2
最小化区间数量,使得:区间的并能覆盖整个区间。
首先 l = 1 的所有区间里,必须选一个,选哪个呢?要选 r 最大的。然后要尽可能不选,用 mxpos 记录当前可以不选的区间里 r 的最大值,r 记录当前已选区间 r 的最大值。
1 2 3 4 5 6 7 8 9
int mxpos = 0, r = 0, ans = 0;
for (int i = 1; i <= n; ++i) { if (a[i].second > r + 1) { r = mxpos; ++ans; } mxpos = max(mxpos, a[i].first); }
#include<bits/stdc++.h> usingnamespacestd; #define N 2000007 typedeflonglong ll;
inlineintrd(){ int x = 0; bool f = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) f |= (c == '-'); for (; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48); return f ? -x : x; }
intmain(){ int n = rd(), t = rd(); for (int i = 1; i <= n; ++i) { int l = rd(), r = rd(); if (l > r) swap(l, r); a[i].first = l; a[i].second = r; } sort(a + 1, a + 1 + n); int mxpos = 0, r = 0, ans = 0;
for (int i = 1; i <= n; ++i) { if (a[i].first > r + 1) {puts("-1"); return0;} r = max(r, a[i].second); } if (r != t) {puts("-1"); return0;}
r = 0; for (int i = 1; i <= n; ++i) { if (a[i].first > r + 1) { r = mxpos; ++ans; } mxpos = max(mxpos, a[i].second); } ans += (r != t); cout << ans << endl; return0; }
Post title:Greedy
Post author:Eva.Q
Create time:2022-02-28 19:30:07
Post link:https://qyy/2022/02/28/Algorithm/Greedy/
Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.