Problem Link : http://lightoj.com/volume_showproblem.php?problem=1337
Solution :
#include<bits/stdc++.h>
#define pii pair<int,int>
using namespace std;
int cell[502][502];
int dell[502][502];
int visited[502][502];
int fx[]= {1,-1,0,0};
int fy[]= {0,0,1,-1};
int r,c,ok=1;
map<int,int>mp;
int bfs(pii s)
{
visited[s.first][s.second]=1;
queue<pii>q;
pii u,a;
int x,y,cnt=0;
if(cell[s.first][s.second]==3) cnt++;
dell[s.first][s.second]=ok;
q.push(s);
while(!q.empty())
{
u=q.front();
q.pop();
for(int i=0; i<4; i++)
{
x=fx[i]+u.first;
y=fy[i]+u.second;
if(x>=1 and x<=r and y>=1 and y<=c and cell[x][y]!=2 and visited[x][y]==0)
{
visited[x][y]=1;
dell[x][y]=ok;
if(cell[x][y]==3) cnt++;
a.first=x;
a.second=y;
q.push(a);
}
}
}
mp[ok]=cnt;
return cnt;
}
int main()
{
int t,ans,q,a,b;
char ch;
pii s,s1,s2,d;
scanf("%d",&t);
for(int ca=1; ca<=t; ca++)
{
scanf("%d%d%d",&r,&c,&q);
getchar();
memset(dell,-1,sizeof(dell));
memset(visited,0,sizeof(visited));
ok=1;
for(int i=1; i<=r; i++)
{
for(int j=1; j<=c; j++)
{
scanf("%c",&ch);
if(ch=='.') cell[i][j]=1;
else if(ch=='#') cell[i][j]=2;
else if(ch=='C')
{
cell[i][j]=3;
}
}
getchar();
}
printf("Case %d:\n",ca);
for(int i=0; i<q; i++)
{
scanf("%d%d",&a,&b);
s.first=a;
s.second=b;
if(visited[a][b]!=0) printf("%d\n",mp[dell[a][b]]);
else
{
ans= bfs(s);
printf("%d\n",ans);
}
ok++;
}
mp.clear();
}
}
Solution :
#include<bits/stdc++.h>
#define pii pair<int,int>
using namespace std;
int cell[502][502];
int dell[502][502];
int visited[502][502];
int fx[]= {1,-1,0,0};
int fy[]= {0,0,1,-1};
int r,c,ok=1;
map<int,int>mp;
int bfs(pii s)
{
visited[s.first][s.second]=1;
queue<pii>q;
pii u,a;
int x,y,cnt=0;
if(cell[s.first][s.second]==3) cnt++;
dell[s.first][s.second]=ok;
q.push(s);
while(!q.empty())
{
u=q.front();
q.pop();
for(int i=0; i<4; i++)
{
x=fx[i]+u.first;
y=fy[i]+u.second;
if(x>=1 and x<=r and y>=1 and y<=c and cell[x][y]!=2 and visited[x][y]==0)
{
visited[x][y]=1;
dell[x][y]=ok;
if(cell[x][y]==3) cnt++;
a.first=x;
a.second=y;
q.push(a);
}
}
}
mp[ok]=cnt;
return cnt;
}
int main()
{
int t,ans,q,a,b;
char ch;
pii s,s1,s2,d;
scanf("%d",&t);
for(int ca=1; ca<=t; ca++)
{
scanf("%d%d%d",&r,&c,&q);
getchar();
memset(dell,-1,sizeof(dell));
memset(visited,0,sizeof(visited));
ok=1;
for(int i=1; i<=r; i++)
{
for(int j=1; j<=c; j++)
{
scanf("%c",&ch);
if(ch=='.') cell[i][j]=1;
else if(ch=='#') cell[i][j]=2;
else if(ch=='C')
{
cell[i][j]=3;
}
}
getchar();
}
printf("Case %d:\n",ca);
for(int i=0; i<q; i++)
{
scanf("%d%d",&a,&b);
s.first=a;
s.second=b;
if(visited[a][b]!=0) printf("%d\n",mp[dell[a][b]]);
else
{
ans= bfs(s);
printf("%d\n",ans);
}
ok++;
}
mp.clear();
}
}
No comments:
Post a Comment