bzoj 1046



记矩阵为 A ,单调队列求出 Ar,[in+1,i] 内最大值和最小值。

而最大值和最小值是满足 区间加法 的,

所以再用单调队列求出 A[in+1,i],[jn+1,j] 内最大值和最小值。

时间复杂度: O(n2)


实现时我翻转了 Ar,[in+1,i] 对应的两个矩阵,来降低编程复杂度。。。


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <iostream>
#include <algorithm>

template<class Num>void read(Num &x)
{
    char c; int flag = 1;
    while((c = getchar()) < '0' || c > '9')
        if(c == '-') flag *= -1;
    x = c - '0';
    while((c = getchar()) >= '0' && c <= '9')
        x = (x<<3) + (x<<1) + (c-'0');
    x *= flag;
    return;
}
template<class Num>void write(Num x)
{
    if(x < 0) putchar('-'), x = -x;
    static char s[20];int sl = 0;
    while(x) s[sl++] = x%10 + '0',x /= 10;
    if(!sl) {putchar('0');return;}
    while(sl) putchar(s[--sl]);
}
#define REP(__i,__start,__end) for(int __i = (__start); __i <= (__end); __i++)

const int maxn = 1005, INF = 0x3f3f3f3f;

typedef int Array[maxn][maxn];

int a, b, n, ans = INF;
Array p, _fmin, _fmax, _gmin, _gmax;

void link_min(int src[],int tar[],int len)
{
    static int line[maxn];
    int f = 0, r = 0;

    REP(i, 1, len)
    {
        if(f != r && i - line[f] >= n) line[f++] = 0;

        while(f != r && src[line[r - 1]] >= src[i]) line[--r] = 0;

        line[r++] = i, tar[i] = src[line[f]];
    }
}
void link_max(int src[],int tar[],int len)
{
    static int line[maxn];
    int f = 0, r = 0;

    REP(i, 1, len)
    {
        if(f != r && i - line[f] >= n) line[f++] = 0;

        while(f != r && src[line[r - 1]] <= src[i]) line[--r] = 0;

        line[r++] = i, tar[i] = src[line[f]];
    }   
}
void init()
{
    read(a), read(b), read(n);

    REP(i, 1, a)
        REP(j, 1, b)
            read(p[i][j]);
}
void solve()
{
    REP(i, 1, a) link_min(p[i], _fmin[i], b), link_max(p[i], _fmax[i], b);

    REP(i, 1, std::max(a, b))
        REP(j, 1, std::max(a, b))
            if(i > j)
            {
                std::swap(_fmin[i][j], _fmin[j][i]);
                std::swap(_fmax[i][j], _fmax[j][i]);
            }
    REP(i, n, b) link_min(_fmin[i], _gmin[i], a), link_max(_fmax[i], _gmax[i], a);

    REP(i, n, b)
        REP(j, n, a)
            ans = std::min(_gmax[i][j] - _gmin[i][j], ans);     
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("1047.in","r",stdin);
    freopen("1047.out","w",stdout);
#endif

    init(), solve(), write(ans);    

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值