Stay Real HDU - 6645(优先队列贪心)

本文介绍了一种使用优先队列优化算法的方法,通过将插入操作的时间复杂度降低到logn,从而实现整体算法效率的提升。相较于传统的排序算法,这种方法在处理大量数据时能有效减少时间开销。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

优先队列来存储因为优先队列的插入是logn的这样就是nlogn了不然用排序的话变成n2logn

#include <iostream>
#include <algorithm>
#include <stack>
#include <cstring>
#include <queue>
using namespace std;

int num[111111];
int num1[111111];


struct node{
	int id,n1;
	bool operator <(const node & b)const{
		return n1<b.n1;
	}
};

bool cmp(node a,node b)
{
	return a.n1<b.n1;
}
int main()
{
	int T;scanf("%d",&T);
	while(T--)
	{
		//memset(num1,0,sizeof(num1));
		priority_queue<node> pq;
		int k;
		scanf("%d",&k);
		long long k1=0;
		long long k2=0;
		for(int i=1;i<=k;i++)
		{
			scanf("%d",&num[i]);
		}
		int k3=k/2;
		if(k%2==0) num1[k3]=1;
		else num1[k3]=2;
		for(int i=1;i<k3;i++)
			num1[i]=2;
		int cont=0;
		for(int i=k3+1;i<=k;i++)
		{
			node ans;
			ans.id=i;
			ans.n1=num[i];
			pq.push(ans);
		}
		int rr=1;
		while(!pq.empty())
		{
			node t=pq.top();pq.pop();
			if(rr&1) k1+=t.n1;
			else k2+=t.n1;
			int fa=t.id/2;
			if((--num1[fa])==0)
			{
				node ans;
				ans.id=fa;
				ans.n1=num[fa];
				pq.push(ans);
			}	
			rr++;		
		}
		printf("%lld %lld\n",k1,k2);
		
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值