Sicily 1090 highway + Prim + priority_queue

#include <iostream>
#include <string>
#include <cstring>
#include <queue>
using namespace std;


class edge{
public:
	int  s,t;
	edge(int s,int t){
		this->s=s;
		this->t=t;
	}
};

const int N=501;
bool visi[N];
int num,s1,t1;
int G[N][N];
priority_queue<edge>que1;

bool operator<(const edge &e1,const edge &e2)  // overload operator< when using default struct
{
	return G[e1.s][e1.t]>G[e2.s][e2.t]; //
}

void take(int vertex)
{
	visi[vertex]=true;
	for (int v=0; v<num; v++)
	{
		if (!visi[v]) que1.push(edge(vertex, v));
	}
}

int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		memset(visi,false,sizeof(visi));  //include<cstring>
		que1=priority_queue<edge>();
		cin>>num;
		int maxlen=0;
		for (int i=0;i<num;i++)
		{
			for (int j=0;j<num;j++)
			{
				cin>>G[i][j];
			}
		}
		take(0);
//		int sum=0;  //calucate the sum of MST
		for (int i=0;i<num-1;i++)
		{
			do 
			{
				s1=que1.top().s;  //not front
				t1=que1.top().t;
				que1.pop();
			} while (visi[s1]&&visi[t1]);
			if (visi[s1]==false)
			{
				take(s1);
				maxlen=max(maxlen,G[s1][t1]);
//				sum+=G[s1][t1];
			}
			else if (visi[t1]==false)
			{
				take(t1);
				maxlen=max(maxlen,G[s1][t1]);
//			    sum+=G[s1][t1];
			}
			
		}
		cout<<maxlen<<endl;
//		cout<<sum<endl;
		if (T!=0)
		{
			cout<<endl;
		}
	}
	return 0;
}


一. priority_queue 注意几点:

priority_queue<Type, Container, Functional>

Type是类型,可以是int ,可以是自定义的Node ;

Container是保存数据的容器,默认容器是vector

Functional 为元素比较方式,默认的比较方式是operator<   ,即 如果缺省后面两个参数的话,默认采用类似 less<>的方式, 优先级最高的是最大元素(大顶堆)


#include <iostream>
#include <queue>
using namespace std;

int main()
{
	priority_queue<int>que1; 

	for (int i=0;i<10;i++)
	{
		que1.push(rand());
	}
	while(!que1.empty()){
		cout<<que1.top()<<" ";
		que1.pop();
	}

	getchar();
	return 0;
}
默认采用 operator< ,产生大根堆 ,输出从大到小。

若Type存放自定义的结构体,又想得到小根堆,可以重载 函数operator<  //经常使用,特别是当元素是自定义的结构体时。

若Type存放int ,又想得到小根堆,可以使用STL里定义的一个仿函数greater<>,用这个仿函数声明小顶堆,

即将

//priority_queue<int>que1;                 
   priority_queue<int,vector<int>,greater<int>>que1;  
change default less<int> to greater<int>, greater<T> is a function object.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值