STL 中优先队列的使用方法(priority_queue)

1、基本操作:

empty() 如果队列为空返回真

pop() 删除对顶元素

push() 加入一个元素

size() 返回优先队列中拥有的元素个数

top() 返回优先队列对顶元素

在默认的优先队列中,优先级高的先出队。在默认的int型中先出队的为较大的数。


2、使用方法:

头文件:

#include <queue>

声明方法:
(1) 普通方法

priority_queue<int> q;

// 通过操作,按照元素从大到小的顺序出队
(2) 自定义优先级
struct cmp
{
bool operator () (int x, int y)
{
return x > y; // x小的优先级高
//也可以写成其他方式,如: return p[x] > p[y];表示p[i]小的优先级高
}
};
priority_queue<int, vector<int>, cmp>q;//定义方法
//其中,第二个参数为容器类型。第三个参数为比较函数。
(3) 结构体声明方式

struct node
{
int x, y;
friend bool operator < (node a, node b)
{
return a.x > b.x; //结构体中,x小的优先级高
}
};
priority_queue<node>q;//定义方法
//在该结构中,y为值, x为优先级。
//通过自定义operator<操作符来比较元素中的优先级。
//最好不要重载”>”,可能会发生编译错误


//#pragma comment(linker, "/STACK:61400000,61400000")
#include <set>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;

#define pi 3.1415926535897932385
#define LL64 __int64
#define LL long long
#define oo 2147483647
#define N 10000100
#define M 2100
#define INF 1e9

double rate[110][110];
double dij[110][110];
int s;

struct cmp
{
bool operator () (int x, int y)
{
return dij[s][x] > dij[s][y];
}
};

priority_queue<int, vector<int>, cmp> p;

int main()
{
int n;

//freopen("data.in", "r", stdin);
//freopen("data.out", "w", stdout);
//int _case = 1;
//scanf("%d", &t);
//while (t--)
//for (int _case = 1; _case <= t; _case++)
while (~scanf("%d", &n))
{
while (!p.empty())
{
p.pop();
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i == j) dij[i][j] = 0;
else dij[i][j] = INF;
scanf("%lf", &rate[i][j]);
}
}

for (int i = 0; i < n; i++)
{
s = i;
p.push(i);
dij[i][i] = 0;
while (!p.empty())
{
int tp = p.top();
p.pop();
for (int j = 0; j < n; j++)
{
if (j == tp) continue;
if (dij[i][j] > dij[i][tp] + rate[tp][j])
{
dij[i][j] = dij[i][tp] + rate[tp][j];
p.push(j);
}
}
}
}

for (int i = 0; i < n; i++)
{
double x = INF;
for (int j = 0; j < n; j++)
{
if (i == j) continue;
x = min(x, dij[i][j] + rate[j][i]);
}
printf("%.2lf\n", x);
}
}

return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值