B. Spotlights
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Theater stage is a rectangular field of size n × m. The director gave you the stage’s plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight’s position is a cell it is placed to and a direction it shines.
A position is good if two conditions hold:
there is no actor in the cell the spotlight is placed to;
there is at least one actor in the direction the spotlight projects.
Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the plan.
The next n lines contain m integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.
Output
Print one integer — the number of good positions for placing the spotlight.
Examples
input
2 4
0 1 0 0
1 0 1 0
output
9
input
4 4
0 0 0 0
1 0 0 1
0 1 1 0
0 1 0 0
output
20
Note
In the first example the following positions are good:
the (1, 1) cell and right direction;
the (1, 1) cell and down direction;
the (1, 3) cell and left direction;
the (1, 3) cell and down direction;
the (1, 4) cell and left direction;
the (2, 2) cell and left direction;
the (2, 2) cell and up direction;
the (2, 2) and right direction;
the (2, 4) cell and left direction.
Therefore, there are 9 good positions in this example.
题意:
找出所有0的有1的方向数的和。
解题思路:
类似于前缀和求解。这里要注意,cin的时间很长,会超时,慎用。
AC代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e3+5;
bool mp[maxn][maxn];
int sum_r[maxn][maxn];
int sum_c[maxn][maxn];
int main()
{
int n,m;
cin>>n>>m;
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= m;j++) scanf("%d",&mp[i][j]),sum_r[i][j] = sum_r[i][j-1]+mp[i][j],sum_c[i][j] = sum_c[i-1][j]+mp[i][j];
}
int res = 0;
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= m;j++)
{
if(!mp[i][j])
{
if(sum_r[i][j]) res++;
if(sum_r[i][m]-sum_r[i][j]) res++;
if(sum_c[i][j]) res++;
if(sum_c[n][j]-sum_c[i][j]) res++;
}
}
}
printf("%d",res);
return 0;
}