At the beginning, only 2 computers were infected:
1 0 0 0
0 0 0 2
0 0 0 0
In day 1:
1 0 0 0
0 0 0 2
0 0 2 2
In day 2:
1 0 1 0
1 1 1 2
0 1 2 2
In day 3:
1 1 1 1
1 1 1 2
1 1 2 2
So at last, all the computers in the networks were infected by virus.
Your task is to calculate after all the computers are infected, how many computers are infected with some specific virus variations.
Input
The input contains multiple test cases!
On the first line of each test case are two integers M and N (1 <= M, N <= 500), followed by a M * N matrix. A positive integer T in the matrix indicates that the corresponding computer had already been infected by the virus variations of type T at the beginning while a negative integer -L indicates that the computer has a defense level L. Then there is an integer Q indicating the number of queries. Each of the following Q lines has an integer which is the virus variation type we care.
Output
For each query of the input, output an integer in a single line which indicates the number of computers attacked by this type of virus variation.
Sample Input
3 4
1 -3 -2 -3
-2 -1 -2 2
-3 -2 -1 -1
2
1
2
Sample Output
9
3
Author: XUE, Zaiyue
题目大意:熊猫烧香病毒入侵电脑,病毒入侵的能力每天增长一,每天都可以入侵不大于自己入侵能力,且与感染病毒电脑相连的电脑,没种电脑只能被感染一次
t次询问,问感染某种病毒的电脑数量是多少。
思路:
BFS 优先队列搜索,先取入侵能力小的代表入侵的时间是靠前的,如果入侵能力相同,取病毒类型数小的先入侵
每次入侵时,如果病毒的入侵能力大于当前电脑的防御能力,则对其进行感染,如果不够入侵,则先取该病毒所在位置周边电脑防御能力最小的入队列,循环操作,直至队列为空
#include <iostream>
#include <algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int x,y;
int c[][2]= {{0,1},{0,-1},{1,0},{-1,0}};
int maps[520][520];
int v[520][520];
int cou[250000];
int n,m;
struct Node
{
int x,y;
int type;
int level;
friend bool operator < (Node a,Node b)
{
if(a.level==b.level)
return a.type>b.type;
return a.level>b.level;
}
} node;
priority_queue<Node> q;
void bfs()
{
while(!q.empty())
{
int flag=0;
Node tp=q.top(),temp;
q.pop();
for(int i=0; i<4; i++)
{
temp.x=tp.x+c[i][0];
temp.y=tp.y+c[i][1];
if(temp.x>=n||temp.y>=m||temp.x<0||temp.y<0||maps[temp.x][temp.y]>0) continue;
if(tp.level>=maps[temp.x][temp.y]*(-1))
{
temp.type=tp.type;
temp.level=tp.level;
q.push(temp);
maps[temp.x][temp.y]=temp.type;
cou[temp.type]++;
}
else
{
if(!flag) flag=maps[temp.x][temp.y];
else
flag=max(flag,maps[temp.x][temp.y]);//因为输入的防御能力是负数,所以我们取得是最大值(eg,-2>-3,我们取-2能力最弱)
}
}
if(flag){//如果还有,没有入侵的电脑,将其入队列;
tp.level=-flag;
q.push(tp);
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
while(!q.empty()) q.pop();
memset(cou,0,sizeof(cou));
Node a;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
{
scanf("%d",&maps[i][j]);
if(maps[i][j]>0)
{
a.x=i;
a.y=j;
a.type=maps[i][j];
a.level=1;
cou[a.type]++;
q.push(a);
}
}
bfs();
int k,t;
scanf("%d",&k);
while(k--)
{
scanf("%d",&t);
printf("%d\n",cou[t]);
}
}
return 0;
}