Cod sursa(job #409931)
#include <cstdio>
#include <vector>
using namespace std;
#define lmax 22555
int n, m, k, v[lmax], ua[lmax], uc[lmax], c[lmax], h;
vector <int> d[lmax];
void add(int x)
{
if (!ua[x] && !uc[x])
{
if (uc[v[x]])
{
h++;
c[h]=x;
uc[x]=1;
} else
{
d[v[x]].push_back(x);
ua[x]=1;
}
}
}
int main()
{
freopen("castel.in","r",stdin);
freopen("castel.out","w",stdout);
scanf("%d %d %d",&n,&m,&k);
int i, j, x, f;
for (i=1; i<=n*m; i++) scanf("%d",&v[i]);
h=1;
c[1]=k;
uc[k]=1;
uc[v[k]]=1;
for (i=1; i<=h; i++)
{
x=c[i];
for (j=0; j<d[x].size(); j++)
{
f=d[x][j];
h++;
c[h]=f;
uc[f]=1;
ua[f]=0;
}
d[x].erase(d[x].begin(), d[x].end());
x=c[i]-1;
if (c[i]%m!=1) add(x);
x=c[i]+1;
if (c[i]%m) add(x);
x=c[i]-m;
if (x>0) add(x);
x=c[i]+m;
if (x<=n*m) add(x);
}
printf("%d",h);
}