LUOGU P2085 最小函数值

来源:互联网 发布:vue.js 手风琴菜单 编辑:程序博客网 时间:2024/06/09 13:41

题目描述

有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个数应该输出到一行,用空格隔开。

写了几道堆排,感觉顺手多了。。。这道题题目中有一个描述是a,b,c都是正整数。根据初中数学之二次函数的顶点,则函数的最小值的x肯定是在负半轴(我就是一开始没想到),然后在定义域(0,+∞)上单调递增。
其实因为这道题数据很水(应该是的),然后暴力就能过,建一个大根堆,枚举每一个函数的1~m的值,如果满足条件就入堆(有没有这个名词。。)然后如果已经堆中的数大于等于了要求数,而且这个数大于堆顶那么就跳过这个函数。就这样。

#include<iostream>#include<cstdio>#include<cmath>#include<algorithm>#include<cstring>using namespace std;const int MAXN=10005;int n,m;//int a[MAXN],b[MAXN],c[MAXN],cnt[MAXN];int t;int  hp[MAXN];int ans[MAXN];struct O {    int a,b,c;} h[MAXN];int del() { //大根堆    int res=hp[1];    hp[1]=hp[t];    t--;    int now=1;    while(now*2<=t) {        int tp=now*2;        if(tp<t&&hp[tp]<hp[tp+1])tp++;        if(hp[tp]>hp[now])swap(hp[tp],hp[now]);        else break;        now=tp;    }    return res;}bool cmp(O x,O y) {    return x.c<y.c;}void pus(int x) {    hp[++t]=x;    int now=t;    while(now>1) {        int tp=now/2;        if(hp[now]>hp[tp])swap(hp[now],hp[tp]);        else break;        now=tp;    }}int f(int i,int x) {    return h[i].a*x*x+h[i].b*x+h[i].c;}int main() {    scanf("%d%d",&n,&m);    memset(hp,0x7f,sizeof hp);    for(register int i=1; i<=n; i++) {        scanf("%d%d%d",&h[i].a,&h[i].b,&h[i].c);    }//  sort(h+1,h+n,cmp);    for(register int i=1; i<=n; i++) {        for(register int j=1; j<=m; j++) {            int r=f(i,j);            while(t>m) {//堆内元素数量不大于m                del();            }            if(r<hp[1]||t<m) {                pus(r);            } else break;        }    }    while(t>m) {        del();    }    for(int i=1; i<=m; i++) {        ans[i]=del();    }    for(int i=m; i>=1; i--)cout<<ans[i]<<" ";//倒序输出}

马上就12月月考了。。。square

原创粉丝点击