关于优先队列priority_queue及其简单应用UVa 136

目录

一. priority_queue

二. UVa 136 Ugly Number


一. priority_queue

对象的声明 priority_queue<T, container<T>=vector<T> , cmp=less > ,T即优先队列元素的类型

其特点是“越小的整数优先级越低” ,即不再按先进后出或先进先出的顺序而是按照其优先级

故对自定义类型重载小于运算符 ,类似与sort()函数

尝试了一下以vector<T> 做元素,其自动排序的方式是地址越小的数组越靠后

如果只想简单的让“越大的整数优先级越低” ,第三个参数可以用greater<T>

对系统自带的封装好了的数据类型想实现自己的排序规则,可以用仿函数

即用一个结构体重载 ()运算符

仿函数示例:

#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;

typedef vector<int> T;
static int i = 1;

// 本质都用仿函数实现顺序的比较
template<typename Func>void showPriority(priority_queue<T,vector<T>,Func> pq)
{
	cout << endl << "pq " << i++ << ":" << endl;
	while (!pq.empty())
	{
		vector<int> it = pq.top(); 
		cout << endl << &pq.top() << endl; // 这里可以发现相同queue的top的地址都一样
		while (!it.empty()) { cout << it.back()<<' '; it.pop_back(); }
		cout << endl;
		pq.pop();
	}
}

// 自定义的cmp类,以数组长度作为优先级
struct cmp
{
	bool operator()(vector<int,allocator<int>> pq1,vector<int, allocator<int>> pq2)
	{
		return pq1.size() < pq2.size();
	}
};

int main()
{
	priority_queue<T,vector<T>,less<T>> pq1; // 地址小优先级小
	priority_queue<T, vector<T>, greater<T>> pq2; // 地址小优先级大
	priority_queue<T, vector<T>,cmp> pq3; // 长度小优先级小
	freopen("in.txt", "r", stdin);
	int n = 10;
	while (n--) {
		int length;
		cin >> length; T temp(length, 0);
		for (int i = 0; i < length; i++)cin >> temp[i];
		pq1.push(temp);
		pq2.push(temp);
		pq3.push(temp);
	}
	showPriority(pq1);
	showPriority(pq2);
	showPriority(pq3);
	return 0;
}

二. UVa 136 Ugly Number

即找出第1500个不能被2,3,5以外的素数整除的数

代码如下:


const long long multiple[] = { 2,3,5 };

int main()
{
	int  count = 0,number;
    set<long long>haveAdd; // 用一个set来保证数不重复
	priority_queue<long long, vector<long long>, greater<long long>> pq;
	pq.push(1); haveAdd.insert(1);
	while (true)
	{
		int i = 0; number = pq.top(); pq.pop(); count++;
// 小的数在前,则pop出的第1500个数即为所求
		if (count == 1500) { cout << "The 1500\'th ugly number is " << number; break; }
		while (i < 3)
		{
			long long add = number * multiple[i++];
			if (!haveAdd.count(add))pq.push(add), haveAdd.insert(add);
		}
	}
	return 0;
}

这个题用这种做法没什么技术含量,消耗内存解决问题,注意数据类型用long long防止溢出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值