贪心
贪心算法(Greedy Algorithm)是一种基于逐步构建解决方案的算法设计思想。它在每一步选择中,都采取当前状态下的局部最优解,以期最终得到问题的全局最优解。贪心算法通常用于解决优化问题,例如最小生成树、最短路径问题和活动选择问题等。
经典问题
井然有序之窗
https://ac.nowcoder.com/acm/contest/95323/H
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include <bits/stdc++.h> using namespace std;
struct space { int l; int r; int id; };
bool cmp1 (space a, space b) { if (a.l != b.l) return a.l < b.l; return a.r < b.r; }
struct cmp2{ bool operator()(const space& a, const space& b) { return a.r > b.r; } };
void solve() { int n; cin >> n; vector<space> s(n + 1); for (int i = 1; i <= n; i++) { cin >> s[i].l >> s[i].r; s[i].id = i; } sort(s.begin() + 1, s.end(), cmp1); priority_queue<space, vector<space>, cmp2> pq; vector<int> ans; map<int, int> cnt; for (int i = 1, j = 1; i <= n; i++) { while (s[j].l == i && j <= n) { pq.push(s[j]); j++; } if (!pq.empty()) { ans.push_back(pq.top().id); pq.pop(); } while (!pq.empty() && pq.top().r == i) { pq.pop(); } } if (ans.size() == n) { for (int i = 0; i < ans.size(); i++) { cnt[ans[i]] = i + 1; } for (auto x : cnt) { cout << x.second << " "; } cout << endl; } else { cout << -1 << endl; } cout << endl; }
signed main() { ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); int t = 1;
while(t--){ solve(); } return 0; }
|