星空之夜
技術標籤:Acwing
夜空深處,閃亮的星星以星群的形式出現在人們眼中,形態萬千。
一個星群是指一組非空的在水平,垂直或對角線方向相鄰的星星的集合。
一個星群不能是一個更大星群的一部分。
星群可能是相似的。
如果兩個星群的形狀、包含星星的數目相同,那麼無論它們的朝向如何,都認為它們是相似的。
通常星群可能有
8
8
8 種朝向,如下圖所示:
現在,我們用一個二維
01
01
01 矩陣來表示夜空,如果一個位置上的數字是
1
1
1,那麼說明這個位置上有一個星星,否則這個位置上的數字應該是
0
0
0。
給定一個夜空二維矩陣,請你將其中的所有星群用小寫字母進行標記,標記時相似星群用同一字母,不相似星群用不同字母。
標註星群就是指將星群中所有的 1 1 1 替換為小寫字母。
輸入格式
第一行包含一個整數
W
W
W,表示矩陣寬度。
第二行包含一個整數 H H H,表示矩陣高度。
接下來 H H H 行,每行包含一個長度為 W W W 的 01 01 01 序列,用來描述整個夜空矩陣。
輸出格式
輸出標記完所有星群后的二維矩陣。
用小寫字母標記星群的方法很多,我們將整個輸出讀取為一個字串,能夠使得這個字串字典序最小的標記方式,就是我們想要的標記方式。
輸出這個標記方式標出的最終二維矩陣。
資料範圍
0
≤
W
,
H
≤
100
,
0
≤
星
群
數
量
≤
500
,
0
≤
不
相
似
星
群
數
量
≤
26
,
1
≤
星
群
中
星
星
的
數
量
≤
160
0≤W,H≤100,\\ 0≤ 星群數量 ≤500,\\ 0≤ 不相似星群數量 ≤26,\\ 1≤ 星群中星星的數量 ≤160
輸入樣例:
23
15
10001000000000010000000
01111100011111000101101
01000000010001000111111
00000000010101000101111
00000111010001000000000
00001001011111000000000
10000001000000000000000
00101000000111110010000
00001000000100010011111
00000001110101010100010
00000100110100010000000
00010001110111110000000
00100001110000000100000
00001000100001000100101
00000001110001000111000
輸出樣例:
a000a0000000000b0000000
0aaaaa000ccccc000d0dd0d
0a0000000c000c000dddddd
000000000c0b0c000d0dddd
00000eee0c000c000000000
0000e00e0ccccc000000000
b000000e000000000000000
00b0f000000ccccc00a0000
0000f000000c000c00aaaaa
0000000ddd0c0b0c0a000a0
00000b00dd0c000c0000000
000g000ddd0ccccc0000000
00g0000ddd0000000e00000
0000b000d0000f000e00e0b
0000000ddd000f000eee000
樣例解釋
樣例對應的星空圖如下:
答案對應的標記後星空圖如下:
#include <bits/stdc++.h>
using namespace std;
const double eps=1e-6;
const int maxn = 110;
const int dx[] = {0, 0, 1, -1, 1, -1, 1, -1};
const int dy[] = {1, -1, 0, 0, -1, 1, 1, -1};
typedef pair<int, int> pii;
vector<pii> v;
int n, m;
char s[maxn][maxn];
map<double,char>ma;
void dfs(int x,int y) {
s[x][y] = '0';
for (int i = 0; i < 8; i++) {
int nx = x + dx[i], ny = y + dy[i];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && s[nx][ny] == '1') {
v.push_back({nx,ny});
dfs(nx, ny);
}
}
}
double dis(int i,int j) {
int dx = v[i].first - v[j].first;
int dy = v[i].second - v[j].second;
return sqrt(dx * dx + dy * dy);
}
double Hash(vector<pii>v) {
int n = v.size();
double res = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
res += dis(i, j);
}
}
return res;
}
char getch(double x) {
for (map<double, char>::iterator it = ma.begin(); it != ma.end(); it++) {
if (fabs(it->first - x) < eps) return it->second;
}
ma[x] = ma.size() + 'a';
return ma[x];
}
void fill(vector<pii>v,char ch) {
for (auto &it:v) {
s[it.first][it.second] = ch;
}
}
int main() {
scanf("%d%d", &m, &n);
for (int i = 1; i <= n; i++) {
scanf("%s", s[i] + 1);
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s[i][j] == '1') {
v.push_back({i, j});
dfs(i, j);
double hash = Hash(v);
fill(v, getch(hash));
v.clear();
}
}
}
for (int i = 1; i <= n; i++) {
printf("%s\n", s[i]+1);
}
return 0;
}