1. 程式人生 > >最小函數值(堆)

最小函數值(堆)

輸入 之一 getch ont 我們 描述 a* algorithm int

最小函數值

題目描述

有n個函數,分別為F1,F2,...,Fn。定義Fi(x)=Aix^2+Bix+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: 復制

3 10
4 5 3
3 4 5
1 7 1

輸出樣例#1:

復制

9 12 12 19 25 29 31 44 45 54

說明

數據規模:n,m<=10000


題解

這道題好像是超級鋼琴的解法思路之一呢。。
我們只要模擬一下就好了。
這次選哪一個方程式。
然後讓方程式的x++。
game over


代碼

#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<iostream>
#include<algorithm>
using namespace std;
priority_queue<pair<long long,int> >q;
long long n,m;
struct node{
    long long a,b,c,cnt;
}ch[500010];
int read(){
    int x=0,w=1;char ch=getchar();
    while(ch>'9'||ch<'0'){if(ch=='-')w=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
    return x*w;
}

void solve(){
    printf("%lld ",-q.top().first);//q.pop();
    int i=q.top().second;q.pop();
    ch[i].cnt++;
    long long x=ch[i].a*ch[i].cnt*ch[i].cnt+ch[i].b*ch[i].cnt+ch[i].c;
    q.push(make_pair(-x,i));
}

int main(){
    n=read();m=read();
    for(int i=1;i<=n;i++){
        ch[i].a=read();ch[i].b=read();ch[i].c=read();ch[i].cnt=1;
        q.push(make_pair(-(ch[i].a+ch[i].b+ch[i].c),i));
    }
    while(m--)solve();
    return 0;
}

最小函數值(堆)