洛谷P2085 最小函數值 堆

題目鏈接:https://www.luogu.com.cn/problem/P2085

根據題目,我們可以很容易知道,一個函數F(x),F(1)一定數所有函數值裏最小的並且,F(1)<F(2)<F(3)<…<F(n)。我們先將所有函數的F(1)放入堆中,按函數值從小到大排序,然後每次取出堆頂heap[1],放入F(x+1),更新小根堆,重複m次即可。
代碼如下(這裏手寫堆,優先隊列也可以)

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e4+5;
struct node
{
    long long a,b,c;
    long long x,y;
}heap[maxn];
bool cmp(node t1,node t2)
{
    return t1.y<t2.y;
}
long long func(node t)
{
    long long y=t.a*t.x*t.x+t.b*t.x+t.c;
}
void Swap(node &t1,node &t2)
{
    node temp=t1;
    t1=t2;
    t2=temp;
}
int n,m;
int main()
{
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        scanf("%lld %lld %lld",&heap[i].a,&heap[i].b,&heap[i].c);
        heap[i].x=1;
        heap[i].y=heap[i].a+heap[i].b+heap[i].c;
    }
    sort(heap+1,heap+1+n,cmp);
    for(int i=1;i<=m;i++)
    {
        printf("%lld ",heap[1].y);
        heap[1].x++;
        heap[1].y=func(heap[1]);
        int j=1;
        while((j<<1)<=n)//更新小根堆
        {
            int temp=j<<1;
            if(temp<n&&heap[temp].y>heap[temp+1].y)
            temp++;
            if(heap[temp].y<heap[j].y)
            {
                Swap(heap[temp],heap[j]);
                j=temp;
            }
            else
            break;
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章