题目链接:https://codeforc.es/contest/1461/problem/B
Holidays are coming up really soon. Rick realized that it’s time to think about buying a traditional spruce tree. But Rick doesn’t want real trees to get hurt so he decided to find some in an n×m matrix consisting of “*” and “.”.
To find every spruce first let’s define what a spruce in the matrix is. A set of matrix cells is called a spruce of height k with origin at point (x,y) if:
All cells in the set contain an “*”.
For each 1≤i≤k all cells with the row number x+i−1 and columns in range [y−i+1,y+i−1] must be a part of the set. All other cells cannot belong to the set.
Examples of correct and incorrect spruce trees:
Now Rick wants to know how many spruces his n×m matrix contains. Help Rick solve this problem.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1≤t≤10).
The first line of each test case contains two integers n and m (1≤n,m≤500) — matrix size.
Next n lines of each test case contain m characters ci,j — matrix contents. It is guaranteed that ci,j is either a “.” or an “*”.
It is guaranteed that the sum of n⋅m over all test cases does not exceed 5002 (∑n⋅m≤5002).
Output
For each test case, print single integer — the total number of spruces in the matrix.
Example
input
4
2 3
.*.
***
2 3
.*.
**.
4 5
.***.
*****
*****
*.*.*
5 7
..*.*..
.*****.
*******
.*****.
..*.*..
output
5
3
23
34
题意
算出符合要求的数的个数
分析
如果有个点是 * ,那么以它为顶点的树的个数就是分别以它的下面三个子点为顶点的树的个数的最小值 + 1 ,从下往上推上来就能算出答案。
代码
#include<bits/stdc++.h>
using namespace std;
int n,m;
char a[507][507];
int sum[507][507];
void solve()
{
long long ans = 0;
scanf("%d%d",&n,&m);
for(int i=0;i<=n+1;i++)
for(int j=0;j<=m+1;j++)
{
sum[i][j] = 0;
}
for(int i=1;i<=n;i++) scanf("%s",a[i] + 1);
for(int i=n;i>=1;i--)
{
for(int j=1;j<=m;j++)
{
if(a[i][j] == '*')
{
ans++;
sum[i][j] = 1;
if(i + 1 > n || j - 1 < 1 || j + 1 > m) continue;
int minn = 1e8;
for(int k=j-1;k<=j+1;k++)
{
minn = min(minn, sum[i + 1][k]);
}
sum[i][j] += minn;
ans += minn;
}
}
}
printf("%lld\n",ans);
}
int main()
{
int T = 1;
scanf("%d",&T);
while(T--)
{
solve();
}
return 0;
}