题目链接
输入样例
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
分析:
开始做这道题的时候感觉无从下手,特别是如何判断这个星系之前出现过。看题解,是用hash方法来判断星系是否相同(感觉hash真nb),具体就是以星系中每两个点之间的距离和作为hash值,算每个距离时一定要开方(否则不同星系hash值相同的可能性会很大),当然还有别的hash方法来判断相似。
之后的过程,就是dfs遍历+标记数组。
代码如下:
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cmath>
#define x first
#define y second
using namespace std;
typedef pair<int,int>PII;
const int N=110;
const double esp=1e-6;
int w,h;
char s[N][N];
int top;
PII p[N*N];
double hs[30];
int id=0;
void dfs(int x,int y)
{
p[top].x=x;
p[top++].y=y;
s[x][y]='0';
for(int i=x-1;i<=x+1;i++)
for(int j=y-1;j<=y+1;j++)
if(i>=0&&i<h&&j>=0&&j<w&&s[i][j]=='1')
dfs(i,j);
}
double get_dist(PII a,PII b)
{
double res=a.x-b.x;
double ans=a.y-b.y;
return sqrt(res*res+ans*ans);
}
double get_hs()
{
double res=0;
for(int i=0;i<top;i++)
for(int j=i+1;j<top;j++)
res+=get_dist(p[i],p[j]);
return res;
}
char get_char(double res)
{
for(int i=0;i<id;i++)
if(fabs(hs[i]-res)<esp) return i+'a';
hs[id++]=res;
return id-1+'a';
}
int main()
{
scanf("%d%d",&w,&h);
for(int i=0;i<h;i++) cin>>s[i];
for(int i=0;i<h;i++)
for(int j=0;j<w;j++)
if(s[i][j]=='1')
{
top=0;
dfs(i,j);
char c=get_char(get_hs());
for(int i=0;i<top;i++) s[p[i].x][p[i].y]=c;
}
for(int i=0;i<h;i++) cout<<s[i]<<endl;
return 0;
}