【牛客網 2019 多校第三場】 F - Planting Trees (思維,枚舉)

題目在這裏插入圖片描述在這裏插入圖片描述在這裏插入圖片描述

思路

瘋狂想法:66forfor循環,O(N6)O(N^6)算法。

於是,看這句話:
It is guaranteed that the sum of N3N^3over all cases does not exceed 25×10725 \times10^7
肯定是讓你想O(N3)O(N^3)算法。
首先,枚舉子矩陣的上下邊界,維護上下邊界的最大最小值。
然後接着枚舉右邊界。
可左邊界怎麼辦呢,反正不能還枚舉吧。

左邊界顯然具有單調不降性。
二分?
O(N3logN)O(N^3 log N) 還是可能超。
滑動窗口?
沒毛病。
這裏我們維護兩個單調隊列,分別記錄最大值、最小值,就可以維護左邊界的指針了。
時間複雜度O(N3)。
時限30003000毫秒。
其實也很懸,同樣的代碼,第一次超時了,第二次2529毫秒險過。

代碼

#include <bits/stdc++.h>

using namespace std;
const int M = 1010;
int a[M][M], minn[M], maxn[M], n, m, q1[M], q2[M], ans;

int main() {
    int T; scanf("%d", &T);
    while (T--) {
		scanf("%d %d", &n, &m);
	    for (int i = 1; i <= n; i++)
	        for (int j = 1; j <= n; j++)
	            scanf("%d", &a[i][j]);
	    ans = 0;
	    for (int s = 1; s <= n; s++) {
	        for (int i = 1; i <= n; i++) minn[i] = 1292371547, maxn[i] = -1;
	        for (int t = s; t <= n; t++) {
	            int l1 = 0, l2 = 0, t1 = 0, t2 = 0, left = 1;
	            for (int i = 1; i <= n; i++) {
	                minn[i] = min(minn[i], a[t][i]);
	                maxn[i] = max(maxn[i], a[t][i]);
	                while (t1 > l1 && minn[q1[t1-1]] >= minn[i]) t1--;
	                while (t2 > l2 && maxn[q2[t2-1]] <= maxn[i]) t2--;
	                q1[t1++] = q2[t2++] = i;
	                while(t1 > l1 && t2 > l2 && maxn[q2[l2]] - minn[q1[l1]] > m) {
	                    left++;
	                    while(t1 > l1 && q1[l1] < left) l1++;
	                    while(t2 > l2 && q2[l2] < left) l2++;
	                }
	                ans = max(ans, (t-s+1) * (i-left+1));
	            }
	        }
	    }
	    printf("%d\n", ans);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章