Cod sursa(job #878031)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 13 februarie 2013 19:44:42
Problema Castel Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.68 kb
#include <fstream>
//#define DEBUG
#include<limits.h>
using namespace std;

ifstream cin("castel.in");
ofstream cout("castel.out");

int m, n,u, p, a[160][160], l[160][160], c, q[4][22555], f[1000], nr, i_st, j_st, i, j, maxi=INT_MIN;

void afisare()
{
    #ifdef DEBUG
    for(i=1;i<=m;i++)
        {
            for(j=1;j<=n;j++)
                cout<<l[i][j]<<" ";
            cout<<"\n";

        }
    for(i=1;i<=16;i++)
        cout<<f[i]<<" ";
    #endif
    cout<<c+2<<"\n";
}
void intr(int c, int d)
{
    u=u+1;
    q[1][u]=c;
    q[2][u]=d;
}
void extr(int &c, int &d)
{
    p=p+1;
    c=q[1][p];
    d=q[2][p];
}
void lee()
{
    int x, y;
    p=0;
    u=1;
    while(p!=u)
    {
        //nr camera=(i-1)*n+j;
        extr(x, y);
        if(x>1)
            if(f[a[x-1][y]])
               {
                   if(l[x-1][y]>l[x][y]+1 || l[x-1][y]==-1)
                    {
                        c++;
                        f[(x-1-1)*n+y]++;
                        l[x-1][y]=l[x][y]+1;
                        intr(x-1, y);
                    }
               }
        if(x<m)
            if(f[a[x+1][y]])
               {
                   if(l[x+1][y]>l[x][y]+1 || l[x+1][y]==-1)
                    {
                        c++;
                        f[(x+1-1)*n+y]++;
                        l[x+1][y]=l[x][y]+1;
                        intr(x+1, y);
                    }
               }
        if(y>1)
            if(f[a[x][y-1]])
               {
                   if(l[x][y-1]>l[x][y]+1 || l[x][y-1]==-1)
                    {
                        c++;
                        f[(x-1)*n+(y-1)]++;
                        l[x][y-1]=l[x][y]+1;
                        intr(x, y-1);
                    }
               }
        if(y<n)
            if(f[a[x][y+1]])
               {
                   if(l[x][y+1]>l[x][y+1]+1 || l[x][y+1]==-1)
                    {
                        c++;
                        f[(x-1)*n+(y+1)]++;
                        l[x][y+1]=l[x][y]+1;
                        intr(x, y+1);
                    }
               }

    }
}
int main()
{
    cin>>m>>n>>nr;
    if(nr%n==0)
        {
            i_st=(nr/n);
            j_st=n;
        }
    else {
            i_st=(nr/n)+1;
            j_st=nr-(i_st-1)*n;
         }
    #ifdef DEBUG
    cout<<i_st<<" "<<j_st<<"\n";
    #endif
    for(i=1;i<=m;++i)
        for(j=1;j<=n;++j)
            {
                cin>>a[i][j];
                l[i][j]=-1;
            }
    l[i_st][j_st]=0;
    q[1][1]=i_st;
    q[2][1]=j_st;
    f[a[i_st][j_st]]++;
    lee();
    afisare();
    return 0;
}