C 單調佇列求特定區間最大值

2021-10-22 22:44:30 字數 1578 閱讀 3423

題目(單調佇列的應用):

用乙個長度為k的視窗在長度為n的整數數列上從左往右滑動,每次滑動乙個單位,求出每次滑動後每個視窗裡面所包含的數的最大值。例如:當數列為[1, 3, -1, -3, 5, 3, 6, 7],視窗大小k=3,可以得出,

視窗位置

視窗內最大值[1

3-1]-3

5367

31[3-1-3]

5367

313[-1-35

]367

513-1[-35

3]67

513-1-3[5

36]7

613-1-35[

367]

7樣例輸入:

8 3(分別為n和k)13

-1-353

67(整數數列)

輸出樣例:

3    3    5    5    6    7(視窗內最大值)

//單調佇列的應用

//author:mitchell_donovan

#includeusing namespace std;

class arrayqueue

front = 0;

tail = 0;

} ~arrayqueue()

deletequeue;

} bool push(int rank,int numbervalue)

tail = (tail + 1) % size;

queue[tail-1][0] = rank;

queue[tail-1][1] = numbervalue;

return true;

} bool poptail()

queue[tail-1][0] = queue[tail-1][1] = int_max;

tail = (size + tail - 1) % size;

return true;

} bool popfront()

queue[front][0]= queue[front][1] = int_max;

front = (front + 1) % size;

return true;

} bool getmax(int* array,int arraysize,int testsize)

}push(i, array[i]);

} for (int i = testsize - 1; i < arraysize; i++) //清空已經過期的元素

if (array[i] >= queue[(size + tail - 1) % size][1])

}push(i, array[i]);

cout << queue[front][1] << " ";

} return true;

}};int main()

arrayqueue test(testsize);

test.getmax(array, arraysize, testsize);

}

單調佇列(求區間最值)

p1440 求m區間內的最小值 題目描述 乙個含有n項的數列 n 2000000 求出每一項前的m個數到它這個區間內的最小值。若前面的數不足m項則從第1個數開始,若前面沒有數則輸出0。輸入輸出格式 輸入格式 第一行兩個數n,m。第二行,n個正整數,為所給定的數列。輸出格式 n行,第i行的乙個數ai,...

st表求區間最大值

第一行給出乙個數字n,接下來n 1行,每行給出乙個數字ai,0 i n 1e6 接來給出乙個數字q q 7000 代表有q個詢問 每組詢問格式為a,b即詢問從輸入的第a個數到第b個數,其中的最大值是多少 如題所述 1001 2323 4321 050 10 2 43 7 7 98 8 434 32這...

滑動視窗的最大值 單調佇列

滑動視窗最大值 給定乙個陣列和滑動視窗的大小,找出所有滑動視窗裡數值的最大值。例如,如果輸入陣列及滑動視窗的大小3,那麼一共存在6個滑動視窗,他們的最大值分別為 針對陣列的滑動視窗有以下6個 題解使用遞減的單調佇列記錄當前佇列的遞減數,佇列首元素就是當前視窗的最大值 遍歷陣列,設定i,j代表視窗起點...