30Pts求条
查看原帖
30Pts求条
716006
Yamchip楼主2024/8/11 21:02
#include<bits/stdc++.h>
using namespace std;
const int N = 1005;
int a, b, n, ans = 2e9, s[N][N], f[N][N], x[N][N], g[N][N], y[N][N];
deque<int> q;
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> a >> b >> n;
    for(int i = 1;i <= a;i++)
        for(int j = 1;j <= b;j++)
            cin >> s[i][j];
    for(int i = 1;i <= a;i++)
        for(int j = 1;j <= b;j++)
        {
            while(!q.empty() && q.front() <= j - n) q.pop_front();
            while(!q.empty() && s[i][q.back()] <= s[i][j]) q.pop_back();
            q.push_back(j);
            if(j >= n) f[i][j - n + 1] = s[i][q.front()];
        }
    while(!q.empty()) q.pop_back();
    for(int i = 1;i <= b - n + 1;i++)
        for(int j = 1;j <= a;j++)
        {
            while(!q.empty() && q.front() <= j - n) q.pop_front();
            while(!q.empty() && f[q.back()][i] <= f[j][i]) q.pop_back();
            q.push_back(j);
            if(j >= n) x[j - n + 1][i] = f[q.front()][i];
        }
    while(!q.empty()) q.pop_back();
    for(int i = 1;i <= a;i++)
        for(int j = 1;j <= b;j++)
        {
            while(!q.empty() && q.front() <= j - n) q.pop_front();
            while(!q.empty() && s[i][q.back()] >= s[i][j]) q.pop_back();
            q.push_back(j);
            if(j >= n) g[i][j - n + 1] = s[i][q.front()];
        }
    while(!q.empty()) q.pop_back();
    for(int i = 1;i <= b - n + 1;i++)
        for(int j = 1;j <= a;j++)
        {
            while(!q.empty() && q.front() <= j - n) q.pop_front();
            while(!q.empty() && g[q.back()][i] >= g[j][i]) q.pop_back();
            q.push_back(j);
            if(j >= n) y[j - n + 1][i] = g[q.front()][i];
        }
    for(int i = 1;i <= a - n + 1;i++)
        for(int j = 1;j <= b - n + 1;j++)
            ans = min(ans, x[i][j] - y[i][j]);
    cout << ans;
    return 0;
}
2024/8/11 21:02
加载中...