太强啦~
hash好神奇
将一片幸运的任意两点间的距离作为hash,这样可能会冲突,但是概率极低。
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
using P = pair<int, int>;
#define x first
#define y second
const int n = 110;
const double eps = 1e-6;
// 8联通的方向
int dx[] = {
0, 1, 0, -1, 1, -1, 1, -1};
int dy[] = {
1, 0, -1, 0, 1, -1, -1, 1};
int N, M;
// 图
string s[n];
vector<P> v;
// 两点间的距离
double get_dist(P a, P b)
{
double dx = a.x - b.x;
double dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
// 哈希值为:任意两点间的距离之和
double get_hash()
{
double sum = 0;
for (int i = 0; i < v.size(); i++)
for (int j = i + 1; j < v.size(); j++)
sum += get_dist(v[i], v[j]);
return sum;
}
// 哈希函数
char get_id(double key)
{
static int index = 0;
static double hash[30];
// 若有当前哈希值
for (int i = 0; i < index; i++)
if (fabs(key - hash[i]) < eps)
return i + 'a';
// 一个新的哈希值
hash[index++] = key;
return index - 1 + 'a';
}
void dfs(int a, int b)
{
s[a][b] = '0';
// 记录每个为1的点
v.push_back({
a, b});
for (int i = 0; i < 8; i++)
{
int nx = dx[i] + a;
int ny = dy[i] + b;
if (nx >= 0 && nx < N && ny >= 0 && ny < M && s[nx][ny] == '1')
dfs(nx, ny);
}
}
int main()
{
cin >> M >> N;
for (int i = 0; i < N; i++)
cin >> s[i];
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
if (s[i][j] == '1')
{
// 存一片星空
v.clear();
dfs(i, j);
// 获取哈希
char c = get_id(get_hash());
// 赋值
for (auto &e : v)
{
s[e.x][e.y] = c;
}
}
for (int i = 0; i < N; i++)
cout << s[i] << endl;
return 0;
}