Cod sursa(job #1498945)

Utilizator redcrocodileIlies Andreea redcrocodile Data 9 octombrie 2015 21:53:57
Problema Barbar Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.74 kb
#include <fstream>
#include <cstring>
#include <queue>
using namespace std;

ifstream f("barbar.in");
ofstream g("barbar.out");

const int dl[5] = {0, -1, 0, 1, 0};
const int dc[5] = {0, 0, 1, 0, -1};
string s;
int a[1002][1002],b[1002][1002],i,j,m,n,li,lf,ci,cf,solutie,nn;

struct pozitie {
  unsigned char l, c;
}p,pn;
queue <pozitie> q;

void citire()
{
    f>>n>>m;
    for (i=1;i<=n;i++)
    {
        getline(f,s);
        for (j=1;j<=n;j++)
          if (s[j-1]=='*') {a[i][j]=-1; b[i][j]=-1;}
            else if (s[j-1]=='I') {li=i; ci=j;}
                  else if(s[j-1]=='D') {p.l=i; p.c=j; q.push(p); b[i][j]=1; a[i][j]=-2;}
                        else if (s[j-1]=='O') {lf=i; cf=j;}
    }
}
void margini()
{
    for(i=0;i<=m;i++)
      a[i][0]=b[i][0]=a[i][n+1]=b[i][n+1]=-1;
    for(j=1;j<=n;j++)
      a[0][j]=b[0][j]=a[m+1][j]=b[m+1][j]-1;
}
void drag()
{
  int d;
  while (!q.empty()) {
    p = q.front();
    q.pop();
    for (d = 1; d <= 4; d++) {
      pn.l = p.l + dl[d]; pn.c = p.c + dc[d];
      if (b[pn.l][pn.c] == 0) {
        b[pn.l][pn.c] = b[p.l][p.c] + 1;
        q.push(pn);
      }
    }
  }
}
int cond(int x)
{
    int d;
    while(!q.empty())
        q.pop();

    for (i=1;i<=m;i++)
        for (j=1;j<=n;j++)
        if(a[i][j]>0)
         a[i][j]=0;

  p.l = li; p.c = ci;
  q.push(p);
  a[li][ci] = 1;
  while (a[lf][cf] == 0 and !q.empty()) {
    p = q.front();
    q.pop();
    for (d = 1; d <= 4; d++) {
      pn.l = p.l + dl[d]; pn.c = p.c + dc[d];
      if (a[pn.l][pn.c] == 0 and b[pn.l][pn.c]>=x) {
        a[pn.l][pn.c] = a[p.l][p.c] + 1;
        q.push(pn);
      }
    }
  }
  if(q.empty()) return 1;
  if(a[lf][cf]>0) return 0;
  }
int cautare()
{
  int step, ans;
	for(step = 1; step <= nn; step *= 2);
	for(ans = 0; step; step /= 2) {
		if(step + ans <= nn && !cond(step + ans)) {
			ans += step;
		}
	}
	return ans;
}
int ver()
{
    int d;
    while(!q.empty())
        q.pop();

    for (i=1;i<=m;i++)
        for (j=1;j<=n;j++)
        if(a[i][j]>0 or a[i][j]==-2)
         a[i][j]=0;


  p.l = li; p.c = ci;
  q.push(p);
  a[li][ci] = 1;
  while (a[lf][cf] == 0 and !q.empty()) {
    p = q.front();
    q.pop();
    for (d = 1; d <= 4; d++) {
      pn.l = p.l + dl[d]; pn.c = p.c + dc[d];
      if (a[pn.l][pn.c] == 0 and b[pn.l][pn.c]>0) {
        a[pn.l][pn.c] = a[p.l][p.c] + 1;
        q.push(pn);
      }
    }
  }

    if (a[lf][cf]>0) return 0; else return -1;
}
int main()
{
    citire();
    margini();
    drag();
    if(b[li][ci]>b[lf][cf]) nn=b[lf][cf]; else nn=b[li][ci]; if(b[li][ci]==2 or b[lf][cf]==2) nn=0;
    solutie=cautare();
    if(solutie>0) g<<solutie-1;
    else
    g<<ver();
    return 0;
}