題意
這道題比較簡單,就是一個消除遊戲,求最終能得到的最高分數,並輸出每一次消除的分數,顏色,個數,和消除區域最左、最下邊的座標。
分析
因爲在出現空列的時候,需要將右邊部分合併到左邊,所以考慮按列處理,而不是按行。
我們把每一列看作一個字符串,那麼所有球構成一個初始長度爲10的15個字符串。這裏利用了一個string的特性,string在中間某一字符被刪除的時候會自動收縮。比如,str = “abcd”,在刪除字符‘b’之後,str自動變爲”acd”,這樣避免了手動去移動字符。
在搜索最大區域的時候,假定最後需要N次來消除,那麼我們在搜索的時候把每個字符均加上當前次數n[1, N]在每次消除的時候,所有字符均變爲 c(原值) + n(1..N)。因爲每次搜索的起點[x,y]有記錄,最後刪除的時候直接從座標[x,y]開始去刪除鄰近的值等於matrix[x,y]的小球就行。
搜索和刪除最大區域均用了一個函數int search(int pos, int col, char key, bool erase),pos爲當前搜索列的下標(從下到上),也就是字符串的下標。col爲當前所有列的數目,也就是字符串數目。key爲搜索或刪除目標,通過erase確定是刪除還是搜索。
因爲是深度搜索,所以刪除的時候,先標記要刪除的字符,最後遍歷一次刪除即可。
PS:注意輸出格式。
代碼如下:
Memory: 220K Time: 500MS Length: 93LINES
#include <iostream>
#include <string>
using namespace std;
const unsigned int max_rows = 10;
const unsigned int max_cols = 15;
unsigned int cols;
string matrix[max_cols];
int search(int pos, int col, char key, bool erase)
{
int left, right;
for (left = pos; left >= 0; --left)
{
if (matrix[col][left] == key) matrix[col][left] = erase ? '0' : matrix[col][left] + 1;
else break;
}
++left;
for (right = pos + 1; right < matrix[col].length(); ++right)
{
if (matrix[col][right] == key) matrix[col][right] = erase ? '0' : matrix[col][right] + 1;
else break;
}
int sum = right - left;
for (int i = left; i < right; ++i)
{
if (col < cols - 1 && matrix[col + 1].length() > i && matrix[col + 1][i] == key)
sum += search(i, col + 1, key, erase);
if (col > 0 && matrix[col - 1].length() > i && matrix[col - 1][i] == key)
sum += search(i, col - 1, key, erase);
}
return sum;
}
bool check(char c) { return (c == 'R' || c == 'G' || c == 'B'); }
int main()
{
int count = 0;
cin >> count;
for (int i = 0; i < count; ++i)
{
char c;
short remaind = max_rows * max_cols;
int final_score = 0;
for (int j = 0; j < max_cols; ++j) matrix[j].clear();
for (int j = 0; j < max_rows; ++j)
for (int k = 0; k < max_cols && cin >> c && check(c); matrix[k] = c + matrix[k], ++k);
cout << "Game " << i + 1 << ":" << endl << endl;
cols = max_cols;
for (int step = 1, maxsum = 2; maxsum > 1; ++step, remaind -= maxsum)
{
maxsum = 0;
int j, k;
int x = -1, y = -1;
int zone = 0;
for (j = 0; j < cols; ++j)
for (k = 0; k < matrix[j].length(); ++k)
{
if (check(matrix[j][k] - step + 1))
{
int res = search(k, j, matrix[j][k], false);
if (res > maxsum)
{
maxsum = res;
x = j;
y = k;
}
}
}
if (maxsum < 2) break;
int score = (maxsum - 2)*(maxsum - 2);
final_score += score;
cout << "Move " << step << " at (" << y + 1 << "," << x + 1 << "): removed " << maxsum;
cout << " balls of color " << char(matrix[x][y] - step) << ", got " << score << " points." << endl;
search(y, x, matrix[x][y], true);
for (j = 0; j < cols; ++j)
{
for (string::size_type pos; (pos = matrix[j].find('0')) != string::npos; matrix[j].erase(pos, 1));
if (matrix[j].length() == 0)
{
for (int k = j; k < cols - 1; ++k) matrix[k] = matrix[k + 1];
--j;
--cols;
}
}
}
cout << "Final score: " << final_score + (remaind == 0 ? 1000 : 0) << ", with " << remaind << " balls remaining." << endl << endl;
}
return 0;
}