백준 아기 상어 [c++]

16236 아기 상어 골드 3

문제 링크

문제

N×N 크기의 공간에 물고기 M마리와 아기 상어 1마리가 있다. 공간은 1×1 크기의 정사각형 칸으로 나누어져 있다. 한 칸에는 물고기가 최대 1마리 존재한다.

아기 상어와 물고기는 모두 크기를 가지고 있고, 이 크기는 자연수이다. 가장 처음에 아기 상어의 크기는 2이고, 아기 상어는 1초에 상하좌우로 인접한 한 칸씩 이동한다.

아기 상어는 자신의 크기보다 큰 물고기가 있는 칸은 지나갈 수 없고, 나머지 칸은 모두 지나갈 수 있다. 아기 상어는 자신의 크기보다 작은 물고기만 먹을 수 있다. 따라서, 크기가 같은 물고기는 먹을 수 없지만, 그 물고기가 있는 칸은 지나갈 수 있다.

아기 상어가 어디로 이동할지 결정하는 방법은 아래와 같다.

더 이상 먹을 수 있는 물고기가 공간에 없다면 아기 상어는 엄마 상어에게 도움을 요청한다. 먹을 수 있는 물고기가 1마리라면, 그 물고기를 먹으러 간다. 먹을 수 있는 물고기가 1마리보다 많다면, 거리가 가장 가까운 물고기를 먹으러 간다. 거리는 아기 상어가 있는 칸에서 물고기가 있는 칸으로 이동할 때, 지나야하는 칸의 개수의 최솟값이다. 거리가 가까운 물고기가 많다면, 가장 위에 있는 물고기, 그러한 물고기가 여러마리라면, 가장 왼쪽에 있는 물고기를 먹는다. 아기 상어의 이동은 1초 걸리고, 물고기를 먹는데 걸리는 시간은 없다고 가정한다. 즉, 아기 상어가 먹을 수 있는 물고기가 있는 칸으로 이동했다면, 이동과 동시에 물고기를 먹는다. 물고기를 먹으면, 그 칸은 빈 칸이 된다.

아기 상어는 자신의 크기와 같은 수의 물고기를 먹을 때 마다 크기가 1 증가한다. 예를 들어, 크기가 2인 아기 상어는 물고기를 2마리 먹으면 크기가 3이 된다.

공간의 상태가 주어졌을 때, 아기 상어가 몇 초 동안 엄마 상어에게 도움을 요청하지 않고 물고기를 잡아먹을 수 있는지 구하는 프로그램을 작성하시오.

입력

첫째 줄에 공간의 크기 N(2 ≤ N ≤ 20)이 주어진다.

둘째 줄부터 N개의 줄에 공간의 상태가 주어진다. 공간의 상태는 0, 1, 2, 3, 4, 5, 6, 9로 이루어져 있고, 아래와 같은 의미를 가진다.

0: 빈 칸 1, 2, 3, 4, 5, 6: 칸에 있는 물고기의 크기 9: 아기 상어의 위치 아기 상어는 공간에 한 마리 있다.

출력

첫째 줄에 아기 상어가 엄마 상어에게 도움을 요청하지 않고 물고기를 잡아먹을 수 있는 시간을 출력한다.

풀이

처음에 문제를 보고 생각한 아이디어는

  1. 크기가 i인 물고기가 몇마리 있는지 정보를 저장하는 fish[6] 배열을 선언한다.
    • 이 배열은 먹이를 먹고 난 후 다음 bfs를 진행할지 결정하는데 이용된다.
    • 만약 자신의 크기보다 작은 물고기가 없다면 bfs를 종료.
  2. 처음 시작 위치에서 bfs를 수행해 조건에 맞는 먹이를 찾아 먹은 후 bfs를 종료하면서 먹은 위치를 return한다.
  3. 그리고 return된 위치에서 종료 조건에 만족하지 않는다면 다시 bfs를 수행한다.

그리고 코드를 작성하고 테스트케이스를 확인하니 몇가지 경우에서 예외가 발생했다. 문제는 아기 상어가 먹이를 먹는데, 같은 거리에 있으면 위쪽, 같은 높이라면 가장 왼쪽 먹이를 먹어야 한다.

이 문제를 해결하기 위해 priority_queue를 사용해 먹이의 우선순위를 정해 해결하려고 했다.

테스트케이스는 맞았으나 시간초과가 났다.

이후, 다른 블로그( 참고 링크 )를 살펴보니 fish배열을 쓰지 않고 visited에 distance를 저장하는 방식으로 풀이하는 코드가 많았다. 이를 참고해 코드를 수정해, 문제를 해결했다.

코드1 (오답)

#include <iostream>
#include <vector>
#include <queue>
#include <functional>
#include <algorithm>
#include <utility>
#include <math.h>
using namespace std;

int fish[7];
int n, m;
int sea[21][21];

int dir[2][4] = {{-1,0,0,+1}, {0,-1,+1,0}};

int visited[21][21];
int sharkSize = 2;
int growCredit = 2;
int dis = 0;

struct Compare {
    using value_type = pair<pair<int, int>, int>;

    bool operator()(const value_type& lhs, const value_type& rhs) const {
        //second우선, second가 같으면 first.first가 작은 것이 우선 first.first도 같다면 first.second가 작은 것이 우선
        if(lhs.second == rhs.second){
            if(lhs.first.first == rhs.first.first){
                return lhs.first.second > rhs.first.second;
            } else{
                return lhs.first.first > rhs.first.first;
            }
        } else{
            return lhs.second > rhs.second;
        }
    }

    typedef value_type& reference;
    typedef const value_type& const_reference;
    typedef size_t size_type;
};

void init()
{
    for(int i = 0; i < 7; i++)
    {
        fish[i] = 0;
    }
    for(int i = 0; i < 21; i++)
    {
        for(int j = 0; j < 21; j++)
        {
            sea[i][j] = 0;
        }
    }
}

void init_visited()
{
    for(int i = 0; i < 21; i++)
    {
        for(int j = 0; j < 21; j++)
        {
            visited[i][j] = 0;
        }
    }
}

void print_fish()
{
    cout << "fish : ";
    for(int i = 1; i < 7; i++)
    {
        cout << fish[i] << " ";
    }
}

void print_sea(int n)
{
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cout << sea[i][j] << " ";
        }
        cout << "\n";
    }

}

int distance(int sx, int sy, int ex, int ey)
{
    return abs(ex - sx) + abs(ey - sy);
}

pair<pair<int, int>, int> bfs(int x, int y)
{
    // priority_queue<pair<pair<int, int>, int> > q;
    priority_queue<pair<pair<int, int>, int>, vector<pair<pair<int, int>, int> > , Compare > q;
    q.push(make_pair(make_pair(x, y), 0));

    while(!q.empty())
    {
        int nowX = q.top().first.first;
        int nowY = q.top().first.second;
        int move = q.top().second;
        visited[nowX][nowY] = 1;
        q.pop();

        if(sea[nowX][nowY] >= 1 && sea[nowX][nowY] <= 6)
        {
            if(sea[nowX][nowY] < sharkSize)
            {
                fish[sea[nowX][nowY]]--;
                sea[nowX][nowY] = 0;
                // cout << "eat : " << nowX << " " << nowY << " sharkSize : " << sharkSize << endl;
                // print_sea(n);
                if(growCredit > 1)
                {
                    growCredit--;
                } else{
                    sharkSize++;
                    growCredit = sharkSize;
                }
                return make_pair(make_pair(nowX, nowY), move);
            } else if(sea[nowX][nowY] > sharkSize){
                continue;
            }
        }

        for(int i = 0; i < 4; i++)
        {
            int nX = nowX + dir[0][i];
            int nY = nowY + dir[1][i];
            if(nX >= 0 && nX < n && nY >= 0 && nY < n && visited[nX][nY] == 0 && sea[nX][nY] <= sharkSize)
            {
                q.push(make_pair(make_pair(nX, nY), move + 1));
            }
        }
    }
    return make_pair(make_pair(-1,-1), -1);
}

int main()
{
    cin >> n;
    init();
    int startX, startY;

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cin >> sea[i][j];
            if(sea[i][j] >= 1 && sea[i][j] <= 6)
            {
                fish[sea[i][j]]++;
            }
            if(sea[i][j] == 9){
                startX = i;
                startY = j;
                sea[i][j] = 0;
            }
        }
    }

    int uCan = 1;
    // cout << "where\n";
    while(uCan)
    {
        init_visited();
        bool can = false;
        int maxFish = sharkSize;
        if(maxFish > 7){
            maxFish = 7;
        }
        for(int i = 1; i < maxFish; i++)
        {
            if(fish[i] > 0){
                can = true;
            }
        }
        // cout << "can : " << can << endl;
        if(can == false){
            uCan = 0;
        } else{
            pair< pair<int, int>, int> next;
            next = bfs(startX, startY);
            // dis += distance(startX, startY, next.first, next.second);
            dis += next.second;
            // cout << "dis : " << dis << endl;
            // cout << endl;
            startX = next.first.first;
            startY = next.first.second;
        }
        // cout << "sharkSize : " << sharkSize << endl;
        // print_fish();
    }

    cout << dis << endl;

    return 0;
}

코드2 (정답)

#include <iostream>
#include <vector>
#include <queue>
#include <functional>
#include <algorithm>
#include <utility>
#include <math.h>
using namespace std;

int fish[7];
int n, m;
int sea[21][21];

int dir[2][4] = {{-1,0,0,+1}, {0,-1,+1,0}};

int visited[21][21];
int sharkSize = 2;
int growCredit = 2;
int sec = 0;
int x, y;
int ate = 0;

void init()
{
    for(int i = 0; i < 7; i++)
    {
        fish[i] = 0;
    }
    for(int i = 0; i < 21; i++)
    {
        for(int j = 0; j < 21; j++)
        {
            sea[i][j] = 0;
        }
    }
}

void init_visited()
{
    for(int i = 0; i < 21; i++)
    {
        for(int j = 0; j < 21; j++)
        {
            visited[i][j] = 0;
        }
    }
}

void print_sea(int n)
{
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cout << sea[i][j] << " ";
        }
        cout << "\n";
    }

}

int bfs()
{
    // priority_queue<pair<pair<int, int>, int> > q;
    init_visited();
    int dis = 0;
    queue<pair<int, int> > q;
    priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
    q.push(make_pair(x, y));
    visited[x][y] = 1;

    while(!q.empty())
    {
        int nowX = q.front().first;
        int nowY = q.front().second;
        q.pop();

        if(visited[nowX][nowY] == dis){
            break;
        }
        
        for(int i = 0; i < 4; i++)
        {
            int nX = nowX + dir[0][i];
            int nY = nowY + dir[1][i];

            if (nY < 0 || nY >= n || nX < 0 || nX >= n){
                continue;
            }
            if (visited[nX][nY]){
                continue;
            }
            if(!sea[nX][nY] || sea[nX][nY] == sharkSize)
            {
                q.push(make_pair(nX, nY));
                visited[nX][nY] = visited[nowX][nowY] + 1;
            }
            else if(sea[nX][nY] < sharkSize) {
                if(!dis) {
                    ate++;
                }
                visited[nX][nY] = visited[nowX][nowY] + 1;
                dis = visited[nX][nY];
                pq.push(make_pair(nX, nY));
            }
        }

    }
    if(pq.empty())
    {
        return 0;
    }
    x = pq.top().first;
    y = pq.top().second;
    sea[x][y] = 0;
    if(ate == sharkSize) {
        sharkSize++;
        ate = 0;
    }
    return visited[x][y] -1;
}

int main()
{
    cin >> n;
    init();
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cin >> sea[i][j];
            if(sea[i][j] == 9){
                x = i;
                y = j;
                sea[i][j] = 0;
            }
        }
    }

    while(1) {
        int temp = bfs();
        sec += temp;
        if(!temp) {
            break;
        }
    }

    cout << sec << endl;

    return 0;
}