SSL 1411 洛谷 2085 信息学奥赛一本通 1370 最小函数值#堆#

题目

求前 m m m个最小函数值


分析

用堆实现,首先把每一种函数的最小值 ( x = 1 ) (x=1) x=1加入堆,再把这种函数增加1。


优先队列STL代码

#include <cstdio>
#include <cctype>
#include <queue>
#define M 10001
#define yi p.first
#define er p.second
using namespace std;
priority_queue <pair<int,int> >heap;
int a[M],b[M],c[M],now[M],n,m;
int in(){
    int ans=0; char c=getchar();
    while (!isdigit(c)) c=getchar();
    while (isdigit(c)) ans=ans*10+c-48,c=getchar();
    return ans;
}
int main(){
    n=in(); m=in();
    for (int i=1;i<=n;i++) 
	a[i]=in(),b[i]=in(),c[i]=in(),now[i]=1,heap.push(make_pair(-a[i]-b[i]-c[i],i));//小根堆
    for (int i=1;i<=m;i++){
    	pair<int,int>p=heap.top(); //弹出
		heap.pop();	printf("%d ",-yi);//小根堆时改变符号,so取相反数
    	int x=++now[er];//现在这个函数的x增加
    	heap.push(make_pair(-a[er]*x*x-b[er]*x-c[er],er));//插入
    }
    return 0;
} 

小根堆代码

#include <cstdio>
#include <cctype>
#include <algorithm>
#define M 10010
using namespace std;
struct dui{int val,num;}heap[M];
int a[M],b[M],c[M],now[M],n,m;
int in(){
    int ans=0; char c=getchar();
    while (!isdigit(c)) c=getchar();
    while (isdigit(c)) ans=ans*10+c-48,c=getchar();
    return ans;
}
void up(int x){while (x>1&&heap[x].val<heap[x>>1].val) swap(heap[x],heap[x>>1]),x>>=1;}
void down(int x){ int y;
    while ((x<<1)<=n){
        if ((x<<1)==n||heap[x<<1].val<heap[(x<<1)+1].val) y=x<<1; else y=(x<<1)+1;
        if (heap[x].val>heap[y].val) swap(heap[x],heap[y]); x=y;
    }
}
int main(){
    n=in(); m=in();
    for (int i=1;i<=n;i++) 
    a[i]=in(),b[i]=in(),c[i]=in(),now[i]=1,
    heap[i].num=i,heap[i].val=a[i]+b[i]+c[i],up(i);//上移 
    for (int i=1;i<=m;i++){
    	printf("%d ",heap[1].val);
    	int x=++now[heap[1].num];//增加
    	heap[1].val=a[heap[1].num]*x*x+b[heap[1].num]*x+c[heap[1].num];//改变
    	down(1);//下移
    }
    return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值