【優先隊列】百度2018校招編程題—序列合併

0x00 前言

又一次當槍手的經歷,但是,說實話好久沒敲C++了有些手生,一個是freopen傳參是啥來着想半天沒想起來,一個是居然忘記優先隊列的pop是不return的了……

哦對了這題我也放在新搭建的主頁上了,也可以去那兒看看~ 傳送門

此題爲:

  • 百度2018校招
  • 機器學習/數據挖掘/自然語言處理方向
  • 編程題 第2題

0x01 題目描述

定義函數

f(n)=a7n7+a6n6+a5n5+a4n4+a3n3+a2n2+a1n+a0

其中係數 ai 都是整數,滿足 0ai1000 且至少有兩個係數嚴格大於0,分別將 n=1,n=2,n=3,... 代入以上函數可以得到無窮長度的證書序列,即用8個係數 a7,a6,...a0 可以唯一確定一個無窮長度的整數序列。現在給出k個通過以上方法定義的無窮序列,你需要求出將這些所有數字放在一起後,第n小的數字是多少。

0x02 解題思路

首先理解題意,有k個數列,找出其中第n小。
那麼每次定位從哪個數列要數字,是本題的時間限,那……就用最小堆就行了,找個在C++的STL裏等價的,那就用優先隊列吧。

於是我們先把每個 f 函數的參數讀進來,用一個a[a_idx]來存這8個數字,並且把n等於1時的狀態放進優先隊列裏,這樣我們讀完就有了一個最小堆,堆頂是所有數列中最小的一個:

for(int j=0; j<8; j++)
    scanf("%lld", &a[i][j]);
q.push(T(calc(a[i], 1), 1, i));

我們得到了數,但是還需要知道這個數是從哪個隊列來的,以及這是當前數列的第幾個數了,所以我們用一個結構體來記錄這些事情:

class T
{
public:
    ll value;
    int n;
    int a_idx;
    T(ll a, int b, int c):value(a),n(b),a_idx(c){}
};

於是,題目就演變成了:每次取數列中最小的那個,並且計算這個數列(第a_idx組參數對應的函數)下一個(n+=1)是什麼數字(value),把他們包裝好,再放進優先隊列裏(此處需要注意優先隊列默認是大頂堆,需要小頂堆時需要如下定義)

priority_queue<T, vector<T>, greater<T> > q;

0x03 Source Code

#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
using namespace std;
typedef long long ll;

class T
{
public:
    ll value;
    int n;
    int a_idx;
    T(ll a, int b, int c):value(a),n(b),a_idx(c){}
};

bool operator > (const T &t1, const T &t2) 
{
     return t1.value > t2.value;
} 

ll calc(ll* a, int n)
{
    ll ret = 0LL;
    for(int i=0;i<8;i++)
        ret += a[i] * pow(ll(n), ll(7-i));
    return ret;
}

int main()
{
    freopen("./in.txt", "r", stdin);
    ll a[10001][8]={0};

    priority_queue<T, vector<T>, greater<T> > q;
    while(!q.empty()) q.pop();

    int n; scanf("%d", &n);
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<8; j++)
            scanf("%lld", &a[i][j]);
        q.push(T(calc(a[i], 1), 1, i));
        //cout<<q.top().value<<endl;
    }
    int k; scanf("%d", &k);
    ll ret = 0LL;
    for(int i=0; i<k; i++)
    {
        T cur = q.top();
        q.pop();
        int _n = cur.n;
        int _i = cur.a_idx;
        ret = cur.value;

        T inp = T( calc(a[_i], _n+1), _n+1, _i );
        q.push(inp);
    }
    cout<<ret<<endl;

    fclose(stdin);
    return 0;
}

/*
Sample input:
3
0 0 0 0 1 2 0 0
0 0 0 0 0 0 10 6
0 0 0 0 0 0 25 1
9

Sample output:
51
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章