1. 程式人生 > 其它 >acwing 1402. 星空之夜 雜湊+連通塊

acwing 1402. 星空之夜 雜湊+連通塊

技術標籤:acwing

題目連結
對於結構特別的連通塊可以將它的每個點到其他點的距離之和作為hash值
並且在判斷浮點數是否出現過時,應該比較fabs的差值

#include<bits/stdc++.h>
#define lowbit(x) x&(-x)
#define x first
#define y second
using namespace std;
typedef pair<int,int>PII;
const int N=110;
const double eps=1e-6;
int n,m;
char g[N][N];
PII q[N*N];
int top; double get_dist(PII a,PII 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<top;i++) for(int j=i+1;j<top;j++) sum+=get_dist(q[i],q[j]); return sum; } char get_id(double
key){ static double hash[30]; static int id=0; for(int i=0;i<id;i++) if(fabs(hash[i]-key)<eps)//判斷有無出現過 return i+'a'; hash[id++]=key; return id-1+'a'; } void dfs(int a,int b){ q[top++]={a,b}; g[a][b]='0'; for(int x=a-1;x<=a+1;x++) for(int
y=b-1;y<=b+1;y++){ if(x==a&&y==b) continue; if(x>=0&&x<n&&y>=0&&y<m&&g[x][y]=='1') dfs(x,y); } } int main(){ cin>>m>>n; for(int i=0;i<n;i++) cin>>g[i]; for(int i=0;i<n;i++) for(int j=0;j<m;j++){ if(g[i][j]=='1'){ top=0; dfs(i,j); char c=get_id(get_hash()); for(int k=0;k<top;k++) g[q[k].x][q[k].y]=c; } } for(int i=0;i<n;i++) cout<<g[i]<<endl; return 0; }