POJ - 3190 贪心+优先队列

版权声明:博主的博客不值钱随便转载但要注明出处 https://blog.csdn.net/easylovecsdn/article/details/83719269

今天,吃饭,被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;
}

猜你喜欢

转载自blog.csdn.net/easylovecsdn/article/details/83719269