这道题在我刚学c++的时候写过一遍,然而因为代码太长了又写得很烂所以没敢交。
那时候或者是不久以前我觉得oj能ac都是一件不可思议的事情,这次也是参考了一些大神的想法,还有搜索了polyomino的问题大家在stackoverflow上的看法,然后写出来的。
其实我觉得因为我用了好多vector结构会导致变慢,但实际上ac居然0ms,不知道数据到底是怎么弄的。
主要还是哈希,每一个block对应一个key。
如何使形状和数值上的key联系起来是最关键的。
网上有两种说法,一种是每两个点之间距离的平方(亲测可以ac),另一种是任意两点之间的加和,没有去试因为觉得有点不靠谱。
另外还有一种是degree,貌似是在一个block中,每个点在四个方向上的维度(元素的多少),有空可以去试一下。
重点其实是hash的观念,最近上课也在学,但是估计不会讲得很深,所以最好自己去看一下书。
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
int width,height,n;
int table[101][101];
struct Point{
int x;
int y;
Point(int X, int Y){
x=X;
y=Y;
}
};
vector<Point> points_total;
vector<int> hash_keys;
int MARK = 2;
class Block{
public:
void add_point(Point p){
points.push_back(p);
}
double getHashKey(){
double key=0;
long size = points.size();
for(long i=0;i<size-1;i++){
for(long j=i+1;j<size;j++){
double x1 = points[i].x;
double y1 = points[i].y;
double x2 = points[j].x;
double y2 = points[j].y;
double distance2 = pow(x1-x2,2) + pow(y1 - y2, 2);
key+=distance2;
}
}
return key;
}
vector<Point> points;
};
void add_to_block(Point p, Block& b){
if(table[p.x][p.y]==1){
b.add_point(p);
table[p.x][p.y]=MARK;
}
else
return;
if(p.x-1>=0){
Point up(p.x-1,p.y);
add_to_block(up, b);
}
if(p.x+1<width){
Point down(p.x+1,p.y);
add_to_block(down, b);
}
if(p.y-1>=0){
Point left(p.x,p.y-1);
add_to_block(left, b);
}
if(p.y+1<height){
Point right(p.x,p.y+1);
add_to_block(right, b);
}
}
void find_blocks(){
for(int i=0;i<points_total.size();i++){
Point p = points_total[i];
if(table[p.x][p.y]==1){
Block b;
add_to_block(p, b);
hash_keys.push_back(b.getHashKey());
}
}
}
int main(int argc, const char * argv[]) {
// insert code here...
int Case_no;
cin>>Case_no;
while(Case_no--){
cin>>width>>height>>n;
for(int i=0;i<width;i++){
for(int j=0;j<height;j++){
table[i][j]=0;
}
}
for(int i=0;i<n;i++){
int x,y;
cin>>x>>y;
table[x][y]=1;
Point p(x,y);
points_total.push_back(p);
}
find_blocks();
vector<int> keys1 = hash_keys;
sort(keys1.begin(),keys1.end());
hash_keys.clear();
points_total.clear();
for(int i=0;i<width;i++){
for(int j=0;j<height;j++){
table[i][j]=0;
}
}
for(int i=0;i<n;i++){
int x,y;
cin>>x>>y;
table[x][y]=1;
Point p(x,y);
points_total.push_back(p);
}
find_blocks();
vector<int> keys2 = hash_keys;
sort(keys2.begin(),keys2.end());
if(keys1==keys2)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
hash_keys.clear();
points_total.clear();
}
return 0;
}