POJ - 3190 貪心+優先佇列
阿新 • • 發佈:2018-11-10
今天,吃飯,被SW教育了一波,堆是完全二叉樹,堆是完全二叉樹,堆是完全二叉樹,重要的事情說三遍。
優先佇列是堆,priority_queue——一個強大的STL,下面先介紹priority_queue的用法。
#include <iostream> #include <queue> using namespace std; typedef struct Test { int a; int b; bool operator < (const Test t) const //過載“<”號——實現b小優先原則 { return b > t.b; } }Test; priority_queue<Test> q; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { Test buf; cin >> buf.a >> buf.b; q.push(buf); } while (!q.empty()) { cout << "(" << q.top().a << ", " << q.top().b << ")" << endl; q.pop(); } return 0; }
測試資料:
/*
input:
5
1 2
2 6
1 0
3 7
4 5
output:
(1, 0)
(1, 2)
(4, 5)
(2, 6)
(3, 7)
*/
關於本題:
#include <iostream> #include <algorithm> #include <queue> #include <set> using namespace std; const int maxn = 50005; typedef struct Test { int a; int b; int n; int r; Test() {} Test(int aa, int bb, int nn, int rr) { a = aa; b = bb; n = nn; r = rr; } bool operator < (const Test &t) const { return b > t.b; } }Test; priority_queue<Test> q; set< pair<int, int> > s; bool cmp(const Test &t1, const Test &t2) { if (t1.a == t2.a) return t1.b < t2.b; return t1.a < t2.a; } Test t[maxn]; int N; int main() { ios::sync_with_stdio(false); while (cin >> N && N) { for (int i = 0; i < N; i++) { cin >> t[i].a >> t[i].b; t[i].n = i + 1; } sort(t, t + N, cmp); int ans = 1; while (!q.empty()) q.pop(); s.clear(); q.push(Test(t[0].a, t[0].b, t[0].n ,t[0].r = 1)); s.insert(make_pair(t[0].n, t[0].r)); for (int i = 1; i < N; i++) { if (t[i].a > q.top().b) { //cout << "(" << t[i].n << ", " << q.top().n << ")" << endl; t[i].r = q.top().r; s.insert(make_pair(t[i].n, t[i].r)); q.pop(); q.push(Test(t[i].a, t[i].b, t[i].n, t[i].r)); } else { ans++; t[i].r = ans; s.insert(make_pair(t[i].n, t[i].r)); q.push(Test(t[i].a, t[i].b, t[i].n, t[i].r)); } } cout << ans << endl; set< pair<int, int> >::iterator it = s.begin(); while (it != s.end()) { cout << it->second << endl; it++; } } return 0; }