求助,关于手写堆排
查看原帖
求助,关于手写堆排
130819
Hayzeros楼主2021/8/24 17:17
#include<cstdio>
#include<queue>
#include<cmath>
using namespace std;
struct su
{
	int a,b,c,k;
}f[10010];
int len;
struct hp
{
	long long s;
	int id;
}heap[20000];
bool cmp(hp x,hp y)
{
	return x.s>y.s;
}
void push(int i)
{
	heap[++len].s=f[i].a*f[i].k*f[i].k+f[i].b*f[i].k+f[i].c;
	heap[len].id=i;
	push_heap(heap+1,heap+1+len,cmp);
}
void down()
{
	int pa=1;
	while (pa*2<=len)
	{
		int son=pa*2;
		if (son<len&&heap[son].s>heap[son+1].s) son++;
		if (heap[pa].s<=heap[son].s) break;
		swap(heap[pa],heap[son]);
		pa=son;
	}
}
int main()
{
	int n,m;
	scanf("%d%d",&n,&m);
	for (int i=1; i<=n; i++)
	{
		scanf("%d%d%d",&f[i].a,&f[i].b,&f[i].c);
		f[i].k=max(int(round(-f[i].a*2/double(f[i].b))),1);
		push(i);
	}
	while (m--)
	{
		printf("%d ",heap[1].s);
		int kh=heap[1].id;
		f[kh].k++;
		heap[1].s=f[kh].a*f[kh].k*f[kh].k+f[kh].b*f[kh].k+f[kh].c;
		down();
	}
	return 0;
}

为什么这样写的cmp是小根堆?而且反过来却不是大根堆?

2021/8/24 17:17
加载中...