Gym 101102D---Rectangles(单调栈)

时间:2023-03-08 22:53:45
Gym 101102D---Rectangles(单调栈)

题目链接

http://codeforces.com/gym/101102/problem/D

problem  description

Given an R×C grid with each cell containing an integer, find the number of subrectangles in this grid that contain only one distinct integer; this means every cell in a subrectangle contains the same integer.

A subrectangle is defined by two cells: the top left cell (r1, c1), and the bottom-right cell (r2, c2) (1 ≤ r1 ≤ r2 ≤ R) (1 ≤ c1 ≤ c2 ≤ C), assuming that rows are numbered from top to bottom and columns are numbered from left to right.

Input

The first line of input contains a single integer T, the number of test cases.

The first line of each test case contains two integers R and C (1 ≤ R, C ≤ 1000), the number of rows and the number of columns of the grid, respectively.

Each of the next R lines contains C integers between 1 and 109, representing the values in the row.

Output

For each test case, print the answer on a single line.

Example
input
1
3 3
3 3 1
3 3 1
2 2 5
output
16

题意:输入R C表示一个矩阵,里面每一个矩阵元素中有一个数在1~1e9之间 ,求有多少个子矩阵里面的所有数相同?

思路:先对每一列从上到下遍历,记录h[i][j]表示从当前元素往上最多有多少数相同, 然后对每一行遍历,记录ans[i][j] 表示以a[i][j]为右下角的元素的子矩阵个数,那么可以发现: 设当前元素之前同一行中小于它且最近的元素为a[i][k] 那么ans[i][j]=ans[i][k]+(j-k)*h[i][j] 为了降低复杂度可以在当前行从左向右遍历的过程中把各列的高放入单调栈中,这样可以快速知道小于当前元素最近的元素的位置,最后对ans[][]求和就是结果 ;

代码如下:

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <set>
#include <queue>
#include <vector>
using namespace std;
int a[][];
int h[][];
int ans[][];///包含某一点的贡献值;
int S[],pos[];///单调栈; int main()
{
int T;
cin>>T;
int R,C;
while(T--)
{
scanf("%d%d",&R,&C);
memset(h,,sizeof(h));
memset(a,,sizeof(a));
memset(ans,,sizeof(ans));
for(int i=;i<=R;i++)
for(int j=;j<=C;j++)
scanf("%d",&a[i][j]);
for(int j=;j<=C;j++)
{
int s;
for(int i=;i<=R;i++)
{
if(a[i][j]==a[i-][j]) s++;
else s=;
h[i][j]=s;
}
}
long long sum=;
for(int i=;i<=R;i++)
{
int num;
for(int j=;j<=C;j++)
{
if(a[i][j]!=a[i][j-]){
num=; S[]=j-; h[i][j-]=;
S[++num]=j;
pos[j]=j-;
ans[i][j]=h[i][j];
sum+=(long long)ans[i][j];
continue;
}
while(h[i][j]<=h[i][S[num]]) num--;
pos[j]=S[num];
S[++num]=j;
ans[i][j]+=h[i][j]*(j-pos[j]);
if(h[i][pos[j]]!=)
ans[i][j]+=ans[i][pos[j]];
sum+=(long long)ans[i][j];
}
}
printf("%lld\n",sum);
}
return ;
}