单调队列

单调队列

Given a matrix of size n\times mn×m and an integer {k}k, where A[i,j] = lcm(i, j)=lcm(i,j), the least common multiple of {i}i and {j}j. You should determine the sum of the maximums among all k\times kk×k submatrices.
输入描述:
Only one line containing three integers n,m,k(1≤n,m≤5000,1≤k≤min{n,m}).
输出描述:
Only one line containing one integer, denoting the answer.

示例1
输入
3 4 2
输出
38

说明
The given matrix is:
1 2 3 4
2 2 6 4
3 6 3 12
The maximums among all 2×2 submatrices are {2, 6, 6, 6, 6, 12}respectively, and their sum is 38.

题解:一维单调队列来扩展到二维,首先通过一维单调队列来求解,单调队列需要一个双端口队列,并且这个队列是单调递减(后面进入大的数要把前面小的数覆盖掉),队尾把这个数加入后,队头通过验证que[head]是否是该数j-k个数之内的数来吧无用的pop掉,因为他是递减序列,所以队头就是她所要的最大数。最后就是行最一遍,列做一遍,就是k*k矩阵内的最大了。

#include
using namespace std;
int a[5005][5005];
int que[5005],n,m,k,h,t,b[5005][5005];
int main()
{
    while(~scanf("%d%d%d",&n,&m,&k))
    {
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
              a[i][j]=i/__gcd(i,j)*j;
        for(int i=1;i<=n;i++){
              h=1,t=0;
              for(int j=1;j<=m;j++){
                    while(h<=t&&a[i][j]>=a[i][que[t]])
                        t--;  //队尾pop这里就是简单的维护一个单调递减队列
                    que[++t]=j;
                    while(h<=t&&que[h]<=j-k)
                        h++; //这里就是通过队头pop,将j-k个之前的数全部弄掉。
                               //这样队头就是k个数值内的最大值
                    if(j>=k){
                        b[j-k+1][i]=a[i][que[h]];
                    }
                }
        }
        for(int i=1;i<=m-k+1;i++){
            h=1,t=0;
            for(int j=1;j<=n;j++){
                while(h<=t&&b[i][j]>=b[i][que[t]])
                    t--;
                que[++t]=j;
                while(h<=t&&que[h]<=j-k)
                    h++;
                if(j>=k){
                    a[i][j-k+1]=b[i][que[h]]; 
               //内存不够,就直接放原来的数组里了,反正没用了
                }
            }
        }
    long long sum=0;
      for(int i=1;i<=m-k+1;i++)
        for(int j=1;j<=n-k+1;j++)
           sum+=a[i][j];
      printf("%lld\n",sum);
    }
}

你可能感兴趣的:(单调队列)