Algorithm, Data structure/Solved Algorithmic Problem

USACO 2.1 - The Castle

JaykayChoi 2016. 7. 3. 18:41

In a stroke of luck almost beyond imagination, Farmer John was sent a ticket to the Irish Sweepstakes (really a lottery) for his birthday. This ticket turned out to have only the winning number for the lottery! Farmer John won a fabulous castle in the Irish countryside.

Bragging rights being what they are in Wisconsin, Farmer John wished to tell his cows all about the castle. He wanted to know how many rooms it has and how big the largest room was. In fact, he wants to take out a single wall to make an even bigger room.

Your task is to help Farmer John know the exact room count and sizes.

The castle floorplan is divided into M (wide) by N (1 <=M,N<=50) square modules. Each such module can have between zero and four walls. Castles always have walls on their "outer edges" to keep out the wind and rain.

Consider this annotated floorplan of a castle:

     1   2   3   4   5   6   7
   #############################
 1 #   |   #   |   #   |   |   #
   #####---#####---#---#####---#   
 2 #   #   |   #   #   #   #   #
   #---#####---#####---#####---#
 3 #   |   |   #   #   #   #   #   
   #---#########---#####---#---#
 4 # ->#   |   |   |   |   #   #   
   ############################# 

#  = Wall     -,|  = No wall
-> = Points to the wall to remove to
     make the largest possible new room

By way of example, this castle sits on a 7 x 4 base. A "room" includes any set of connected "squares" in the floor plan. This floorplan contains five rooms (whose sizes are 9, 7, 3, 1, and 8 in no particular order).

Removing the wall marked by the arrow merges a pair of rooms to make the largest possible room that can be made by removing a single wall.

The castle always has at least two rooms and always has a wall that can be removed.

PROGRAM NAME: castle

INPUT FORMAT

The map is stored in the form of numbers, one number for each module, M numbers on each of N lines to describe the floorplan. The input order corresponds to the numbering in the example diagram above.

Each module number tells how many of the four walls exist and is the sum of up to four integers:

  • 1: wall to the west
  • 2: wall to the north
  • 4: wall to the east
  • 8: wall to the south

Inner walls are defined twice; a wall to the south in module 1,1 is also indicated as a wall to the north in module 2,1.

Line 1:Two space-separated integers: M and N
Line 2..:M x N integers, several per line.

SAMPLE INPUT (file castle.in)

7 4
11 6 11 6 3 10 6
7 9 6 13 5 15 5
1 10 12 7 13 7 5
13 11 10 8 10 12 13

OUTPUT FORMAT

The output contains several lines:

Line 1:The number of rooms the castle has.
Line 2:The size of the largest room
Line 3:The size of the largest room creatable by removing one wall
Line 4:The single wall to remove to make the largest room possible

Choose the optimal wall to remove from the set of optimal walls by choosing the module farthest to the west (and then, if still tied, farthest to the south). If still tied, choose 'N' before 'E'. Name that wall by naming the module that borders it on either the west or south, along with a direction of N or E giving the location of the wall with respect to the module.

SAMPLE OUTPUT (file castle.out)

5
9
16
4 1 E


출처: http://train.usaco.org/



MxN 크기의 평면도가 주어질 경우 방의 개수와 최대 방의 크기 그리고 벽을 하나 허물어서 가장 큰 방을 하나 만들려고 할 때 허물어야 되는 벽과 얻어지는 그 가장 큰 방의 크기를 구하시오.


input

line 1 : M, N (1 <= M, N <= 50)

line2~ : 방의 평면도가 공백으로 구분되어 주어진다.

1: 서쪽에 벽이 있음

2: 북쪽에 벽이 있음

4: 동쪽에 벽이 있음

8: 남쪽에 벼이 있음


output

1: 방의 개수

2: 가장 큰 방의 크기

3: 벽 하나를 허물 경우 얻어지는 가장 큰 방의 크기

4: 어떤 벽을 허물지 좌표와 방향

방향은 북쪽 N 과 동쪽 E 로 출력하며 답이 한 개가 아닐 경우 가장 서쪽에 있는, 이 경우에도 중복이 있다면 가장 북쪽에 있는 벽을 출력한다.



우선 벽의 정보는 2진수로 주어지기 때문에 bit mask로 값을 쉽게 얻을 수 있도록 isWall 함수를 만들고, 각 좌표를 전체 크기가 50으로 주어졌기에 50 * Y + X 로 표현했습니다.

방의 크기는 재귀함수를 이용한 깊이 우선 탐색으로 찾았고, 벽을 허무는 부분을 풀기위해 각 좌표를 key로 하여 방의 번호를 담아두었고, 방의 번호를 key로 하여 각 방의 크기를 담아두었습니다. 이 부분은 struct 를 사용하여 더 보기좋게 정리할 수 있을 것 같네요.

마지막으로 이 문제의 concept 을 주어진 Flood Fill Algorithms 을 공부해봐야 될 것 같네요.




my solving

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <string>
#include <map>
using namespace std;
 
ofstream fout("castle.out");
int width, height;
int floorplan[50][50];
set<int> totalVisitedRooms;
vector<int> sizes;
map<intint> roomNumber;
map<intint> roomSize;
 
//direction 0: west, 1: north, 2: east, 3: south
bool isWall(int curPosition, int direction)
{
    int curY = curPosition / 50;
    int curX = curPosition % 50;
 
    int cur = floorplan[curY][curX];
 
    if (cur & << direction)
        return true;
    else
        return false;
}
 
int movingResult(int curPosition, int direction)
{
    int curY = curPosition / 50;
    int curX = curPosition % 50;
 
    switch (direction)
    {
    case 0:
        curX--;
        break;
    case 1:
        curY--;
        break;
    case 2:
        curX++;
        break;
    case 3:
        curY++;
        break;
    default:
        break;
    }
 
    if (curX < || curY < || curY >= height || curX >= width)
        return -1;
 
    return curY * 50 + curX;
}
 
bool isCheckmate(int prePosition, int curPosition)
{
    for (int i = 0; i < 4; i++)
    {
        if (isWall(curPosition, i) == false && prePosition != movingResult(curPosition, i))
            return false;
    }
    
    return true;
}
 
int searchRooms(vector<int>& path, set<int>& visited)
{
    int prePosition = path.size() > ? path[path.size() - 2] : -51;
    int curPosition = path.back();
 
    if (isCheckmate(prePosition, curPosition))
        return visited.size();
 
    for (int i = 0; i < 4; i++)
    {
        if (isWall(path.back(), i))
            continue;
        
        int movingPosition = movingResult(path.back(), i);
        if (prePosition > && (movingPosition == prePosition || movingPosition < 0))
            continue;
 
        set<int>::iterator it = visited.find(movingPosition);
        if (it != visited.end())
            continue;
 
        path.push_back(movingPosition);
        visited.insert(movingPosition);
        totalVisitedRooms.insert(movingPosition);
        searchRooms(path, visited);
        path.pop_back();
    }
 
    return visited.size();
}
 
void solveWithRemoving()
{
    sort(sizes.begin(), sizes.end());
    int maxRoomSize = sizes[sizes.size() - 1+ sizes[sizes.size() - 2];
    int largesRoom = 0;
    int retY, retX;
    string direction;
    for (int x = 0; x < width; x++)
    {
        for (int i = 1; i <= 2; i++)
        {
            for (int y = height - 1; y >= 0; y--)
            {
                if (isWall(y * 50 + x, i) == false)
                    continue;
                int movingPosition = movingResult(y * 50 + x, i);
                if (movingPosition == -1)
                    continue;
                map<intint>::iterator it1 = roomNumber.find(y * 50 + x);
                map<intint>::iterator it2 = roomNumber.find(movingPosition);
                int curRoomNumber = it1->second;
                int movingRoomNumber = it2->second;
                if (curRoomNumber == movingRoomNumber)
                    continue;
                totalVisitedRooms.clear();
    
                it1 = roomSize.find(curRoomNumber);
                it2 = roomSize.find(movingRoomNumber);
                int rooms = it1->second + it2->second;
                if (rooms > largesRoom)
                {
                    largesRoom = rooms;
                    retY = y;
                    retX = x;
                    direction = i == "N" : "E";
                }
 
                if (maxRoomSize == largesRoom)
                    break;
            }
            if (maxRoomSize == largesRoom)
                break;
        }
        if (maxRoomSize == largesRoom)
            break;
    }
 
    fout << largesRoom << endl;
    fout << retY + << " " << retX + << " " << direction << endl;
}
 
void solve()
{
    int largesRoom = 0;
    int rooms = 0;
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            set<int>::iterator it = totalVisitedRooms.find(y * 50 + x);
            if (it != totalVisitedRooms.end())
                continue;
            vector<int> path;
            path.push_back(y * 50 + x);
            set<int> visited;
            visited.insert(y * 50 + x);
            int num = searchRooms(path, visited);
            rooms++;
            sizes.push_back(num);
            for (set<int>::iterator it = visited.begin(); it != visited.end(); it++)
                roomNumber.insert(make_pair(*it, rooms));
            roomSize.insert(make_pair(rooms, num));
            largesRoom = max(largesRoom, num);
 
        }
    }
 
    fout << rooms << endl;
    fout << largesRoom << endl;
}
 
int main()
{
    ifstream fin("castle.in");
 
    fin >> width >> height;
 
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            int num;
            fin >> num;
            floorplan[y][x] = num;
        }
    }
 
    solve();
    solveWithRemoving();
 
    fin.close();
    fout.close();
    return 0;
}
cs