Luogu P2085 最小函数值 题解

Luogu P2085 最小函数值 题解

题目描述

有n个函数,分别为F1,F2,…,Fn。定义Fi(x)=Ai*x^2+Bi*x+Ci (x∈N*)。给定这些Ai、Bi和Ci,请求出所有函数的所有函数值中最小的m个(如有重复的要输出多个)。

输入输出格式

输入格式

第一行输入两个正整数n和m。以下n行每行三个正整数,其中第i行的三个数分别位Ai、Bi和Ci。Ai<=10,Bi<=100,Ci<=10 000。

输出格式

输出将这n个函数所有可以生成的函数值排序后的前m个元素。这m个数应该输出到一行,用空格隔开。

输入输出样例

输入样例#1:

1
2
3
4
3 10
4 5 3
3 4 5
1 7 1

输出样例#1:

1
9 12 12 19 25 29 31 44 45 54

说明

数据规模:n,m<=10000

方案1:暴力枚举。数据小了能过,但是肯定会T几个点。

方案2:采用最小堆。

  1. 保存每个函数的fi(1)值为sum,num为fi(x)中的i,step为fi(x)中的x。全部入队。

  2. 每次取队首元素,保存为t,然后pop()。

  3. 输出t.sum(此时已经是最小),t.step++(自变量+1),

    t.sum=a[t.num]t.stept.step+b[t.num]*t.step+c[t.num];(求值),push(t);

  4. 重复,直到执行了m次。

值得注意的是,此处采用了自定义类型,但普通优先队列并不支持自定义类型,只支持基本类型。此时需要重载运算符。

1
friend bool operator<(const rbq u,const rbq o){return u.sum>o.sum;}

附代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
struct rbq
{
int num,sum,step;
friend bool operator<(const rbq u,const rbq o){return u.sum>o.sum;}
}t;
priority_queue<rbq>q;
int n,m,a[10010],b[10010],c[10010];
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
{
scanf("%d %d %d",&a[i],&b[i],&c[i]);
t.num=i;t.sum=a[i]+b[i]+c[i];t.step=1;
q.push(t);
}
while(m--)
{
t=q.top();
q.pop();
cout<<t.sum<<" ";
t.step++;
t.sum=a[t.num]*t.step*t.step+b[t.num]*t.step+c[t.num];
q.push(t);
}
return 0;
}

--It's the end.Thanks for your read.--