One important factor to identify acute stroke (急性脑卒中) is the volume of the stroke core. Given the results of image analysis in which the core regions are identified in each MRI slice, your job is to calculate the volume of the stroke core.
Input Specification:
Each input file contains one test case. For each case, the first line contains 4 positive integers: M, N, L and T, where M and N are the sizes of each slice (i.e. pixels of a slice are in an M by N matrix, and the maximum resolution is 1286 by 128); L (<=60) is the number of slices of a brain; and T is the integer threshold (i.e. if the volume of a connected core is less than T, then that core must not be counted).
Then L slices are given. Each slice is represented by an M by N matrix of 0’s and 1’s, where 1 represents a pixel of stroke, and 0 means normal. Since the thickness of a slice is a constant, we only have to count the number of 1’s to obtain the volume. However, there might be several separated core regions in a brain, and only those with their volumes no less than T are counted. Two pixels are “connected” and hence belong to the same region if they share a common side, as shown by Figure 1 where all the 6 red pixels are connected to the blue one.
Figure 1
Output Specification:
For each case, output in a line the total volume of the stroke core.
Sample Input:
3 4 5 2
1 1 1 1
1 1 1 1
1 1 1 1
0 0 1 1
0 0 1 1
0 0 1 1
1 0 1 1
0 1 0 0
0 0 0 0
1 0 1 1
0 0 0 0
0 0 0 0
0 0 0 1
0 0 0 1
1 0 0 0
Sample Output:
26
本题必须使用广度遍历,如果使用深度遍历,栈会爆掉。
PS:由此应该知道,出现段错误时,可能的错误原因有什么。
#include<iostream>
#include<vector>
#include<string.h>
#include<queue>
using namespace std;
int N,M,L,T,ans=0;
bool visited[1290][130][61]={false};
int slice[1290][130][61]={0};
int nextw[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};
struct node{
int i,j,l;
node(int ni,int nj,int nl){i=ni,j=nj,l=nl;}
};
int bfs(int i,int j,int l){
int cnt=0;
queue<node> q;
q.push(node(i,j,l));
visited[i][j][l]=true;
while(!q.empty()){
node t=q.front();
q.pop();
cnt++;
for(int k=0;k<6;k++){
int ni=t.i+nextw[k][0];
int nj=t.j+nextw[k][1];
int nl=t.l+nextw[k][2];
if(ni>=0&&ni<N&&nj>=0&&nj<M&&nl>=0&&nl<L){
if(!visited[ni][nj][nl]&&slice[ni][nj][nl]==1){
q.push(node(ni,nj,nl));
visited[ni][nj][nl]=true;
}
}
}
}
if(cnt>=T)
return cnt;
else return 0;
}
int main(){
freopen("in.txt","r",stdin);
scanf("%d%d%d%d",&N,&M,&L,&T);
for(int l=0;l<L;l++){
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
scanf("%d",&slice[i][j][l]);
}
}
}
for(int l=0;l<L;l++){
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(!visited[i][j][l]&&slice[i][j][l]){
ans+=bfs(i,j,l);
}
}
}
}
printf("%d\n",ans);
return 0;
}