1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| #include <stdio.h> #include <deque> #include <algorithm> using namespace std; #define MAX_N (1000000 + 100) int nNum[MAX_N]; int nN, nK;
struct Small { int nValue; int nIndex; Small(int nV, int index):nValue(nV), nIndex(index) {} bool operator < (const Small a) const { return nValue < a.nValue; } };
struct Big { int nValue; int nIndex; Big(int nV, int index):nValue(nV), nIndex(index) {} bool operator < (const Big a) const { return nValue > a.nValue; } };
template <typename T> class Monoque { deque<T> dn;
public: void Insert(T node) { int nPos = dn.size() - 1; while (nPos >=0 node < dn[nPos]) { --nPos; dn.pop_back(); } dn.push_back(node); }
int Top() { return dn.front().nValue; }
void Del(int nBeg, int nEnd) { if (dn.size() > 0) { if (dn.front().nIndex < nBeg || dn.front().nIndex > nEnd) { dn.pop_front(); } } } };
int main() { while (scanf("%d%d", &nN, &nK) == 2) { int i; for (i = 0; i < nN; ++i) { scanf("%d", &nNum[i]); } Monoque<Small> minQ; Monoque<Big> maxQ;
for (i = 0; i < nK; ++i) { minQ.Insert(Small(nNum[i], i)); }
for (i = 0; i < nN - nK; ++i) { printf("%d ", minQ.Top()); minQ.Insert(Small(nNum[i + nK], i + nK)); minQ.Del(i + 1, i + nK); } printf("%d\n", minQ.Top());
for (i = 0; i < nK; ++i) { maxQ.Insert(Big(nNum[i], i)); }
for (i = 0; i < nN - nK; ++i) { printf("%d ", maxQ.Top()); maxQ.Insert(Big(nNum[i + nK], i + nK)); maxQ.Del(i + 1, i + nK); } printf("%d\n", maxQ.Top()); }
return 0; }
|