【洛谷P2085】最小函数值【堆】
题目大意:
题目链接:https://www.luogu.org/problemnew/show/P2085
有个函数,分别为。定义。给定这些、和,请求出所有函数的所有函数值中最小的个(如有重复的要输出多个)。
思路:
作为一道正常的题目,肯定是满足的。否则越大函数值就越小。
显然。所以最基本的思路就是维护个指针,每个指针指向函数的有多大。
每次选择个函数值里面最小的,并且将这格函数的下一个计算出来。
这样时间复杂度是的。
我们发现查找最小值这一部分是可以用堆来维护的。这样每次的时间复杂度就是,总的时间复杂度是
代码:
#include <queue>
#include <cstdio>
#define mp make_pair
using namespace std;
const int N=10010;
int n,m,a[N],b[N],c[N],cnt[N];
priority_queue<pair<int,int> > q;
int f(int x,int y)
{
return a[x]*y*y+b[x]*y+c[x];
}
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++)
{
scanf("%d%d%d",&a[i],&b[i],&c[i]);
q.push(mp(-f(i,1),i));
cnt[i]=1;
}
while (m--)
{
int x=-q.top().first,y=q.top().second;
printf("%d ",x);
q.pop();
q.push(mp(-f(y,++cnt[y]),y));
}
return 0;
}