UVa OJ 1451 - Average

UVa OJ 1451 - Average

Problem

給定一個長度爲n的01串,選一個長度至少爲L的連續子串,使得子串中數字的平均值最 大。如果有多解,子串長度應儘量小;如果仍有多解,起點編號儘量小。序列中的字符編號 爲1~n,因此[1,n]就是完整的字符串。1≤n≤100000,1≤L≤1000。

例如,對於如下長度爲17的序列00101011011011010,如果L=7,最大平均值爲6/8(子 序列爲[7,14],其長度爲8);如果L=5,子序列[7,11]的平均值最大,爲4/5。

Input

Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case starts with a line containing two integers n (1 ≤ n ≤ 100, 000) and L (1 ≤ L ≤ 1, 000) which are the length of a binary sequence and a length lower bound, respectively. In the next line, a string, binary sequence, of length n is given.

Output

Your program is to write to standard output. Print the starting and ending index of the subsequence.

Sample Input

2
17 5
00101011011011010
20 4
11100111100111110000

Sample Output

7 11
6 9

Solution

說來慚愧,這道題目我WA了快一面了。一開始看錯題目,提交了好多次都錯了,自己還沒反應過來,一個勁傻傻地改。後來發現的時候,已經沒有做下去的興致了。

不過最終還是把題目完成了的。總的來說,這道題目還是讓我有些收穫的。題目的解題思路是通過將數列轉化成座標軸上的圖像,平均值這時候也就變成了斜率了。然後一個個點去維護下凸函數的單調數列,找到最優解。

一開始我的cntAverage()這個函數只有三個參數,使用的是除法,提交之後花了0.1s,自己感覺慢了。於是把除法改成了現在的乘法,時間縮短一半,變成了0.05s。可見乘法和除法在計算的效率上還是相差很多的。

#include <iostream>
#include <string>
using namespace std;

const int maxn = 100005;
int n, L, start, ending,temp;
double maxd;
int DNA[maxn],cav[maxn];
string str;

inline int cntAverage(int L, int r, int LL, int rr, int DNA[]){
    return (DNA[r]-DNA[L])*(rr-LL) - (DNA[rr]-DNA[LL])*(r-L);
}

inline void changePoint(int pits,int bump){
    double temp;
    temp = cntAverage(pits, bump, start-1, ending, DNA);
    if (temp < 0) return;
    if (temp || (bump-pits) < (ending-start+1)){
        maxd = temp;
        start = pits + 1;
        ending = bump;
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);

    int cas;
    cin >> cas;
    while (cas--){
        int find = 0, cor = -1;
        cin >> n >> L; cin.get();
        getline(cin, str);
        for (int i = 1; i <= n; ++i)
            DNA[i] = DNA[i-1] + (str[i-1] == '1');
        maxd = DNA[L] / L, start = 1, ending = L;
        for (int i = L; i <= n; ++i){
            temp = i - L;
            while (find < cor && cntAverage(cav[cor], temp, cav[cor - 1], cav[cor], DNA) <= 0)
                --cor;
            cav[++cor] = temp;
            while (find < cor && cntAverage(cav[find], i, cav[find + 1], i, DNA) <= 0)
                ++find;
            changePoint(cav[find],i);
        }
        cout << start << ' ' << ending << '\n';
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章