Codeforces gym 101102 D 单调栈

Rectangles
time limit per test
5 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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

题意:求有多少子矩阵  元素是唯一的


题解:枚举矩阵的右下角  用单调栈维护左上角可能的点


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<deque>
using namespace std;
typedef long long ll;
int a[1005][1005],up[1005][1005];
deque<int>sp;
int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		int n,m,i,j,k;
		scanf("%d%d",&n,&m);
		for(i=1;i<=n;i++){
			for(j=1;j<=m;j++){
				scanf("%d",&a[i][j]);
				up[i][j]=(a[i][j]==a[i-1][j])?up[i-1][j]:i;
			}
		}
		ll ans=0,sum;
		for(i=1;i<=n;i++){
			for(j=1;j<=m;j++){
				int p=i-up[i][j]+1;
				if(a[i][j]!=a[i][j-1]){
					while(!sp.empty())sp.pop_front();
					sum=0;
					sp.push_back(p);
					sum+=p;
					ans+=sum;
				}
				else{
					int now=0;
					while(!sp.empty()&&sp.back()>p){
						now++;
						sum-=sp.back();
						sp.pop_back();
					}
					for(k=1;k<=now+1;k++){
						sum+=p;
						sp.push_back(p);
					}
					ans+=sum;
				}
			}
		}
		printf("%lld\n",ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值