Cod sursa(job #2165352)

Utilizator TheNextGenerationAyy LMAO TheNextGeneration Data 13 martie 2018 11:55:33
Problema Barbar Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.15 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("barbar.in");
ofstream out("barbar.out");

int n,m,dp[1005][1005],cost[1005][1005];
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
const int INF = 1<<30;
bool ok(int i, int j)
{
    return (i>=1 && i<=n && j>=1 && j<=m);
}
char v[1005][1005];

int main()
{
    int x1,y1,x2,y2;
    queue< pair<int,int> > q;
    in >> n >> m;
    for (int i = 1; i<=n; i++)
        for (int j = 1; j<=m; j++)
        {
            in >> v[i][j];
            if (v[i][j] == 'D')
            {
                q.push(make_pair(i,j));
                dp[i][j] = 1;
            }
            else
            {
                if (v[i][j] == 'I')
                {
                    x1 = i;
                    y1 = j;
                }
                else if (v[i][j] == 'O')
                {
                    x2 = i;
                    y2 = j;
                }
            }
        }
    while (!q.empty())
    {
        int i = q.front().first;
        int j = q.front().second;
        for (int z = 0; z<4; z++)
        {
            int i2 = i+dx[z];
            int j2 = j+dy[z];
            if (ok(i2,j2) && !dp[i2][j2])
            {
                dp[i2][j2] = 1+dp[i][j];
                q.push(make_pair(i2,j2));
            }
        }
        q.pop();
    }
    q.push(make_pair(x1,y1));
    cost[x1][y1] = dp[x1][y1];
    while (!q.empty())
    {
        int i = q.front().first;
        int j = q.front().second;
        for (int z = 0; z<4; z++)
        {
            int i2 = i+dx[z];
            int j2 = j+dy[z];
            if (ok(i2,j2) && (v[i2][j2] != '*'))
            {
                if (cost[i2][j2] == -1)
                {
                    cost[i2][j2] = min(dp[i2][j2],cost[i][j]);
                    q.push(make_pair(i2,j2));
                }
                else if (cost[i2][j2]<min(cost[i][j],dp[i2][j2]))
                {
                    cost[i2][j2] = min(cost[i][j],dp[i2][j2]);
                    q.push(make_pair(i2,j2));
                }
            }
        }
        q.pop();
    }
    out << cost[x2][y2]-1;
}