標籤:
Squares
非常好的一道二分,其實本來我是沒有思路的,看了基神的題解之後才似乎明白了點。
題意:給出最多有1000個點,問這些點可以組成多少個正方形
分析:先想想怎麼判斷正方形吧,假如我現在有四個點A,B,C,D,因為邊不一定是平行於x軸的,可能是傾斜的,如何判斷四個點組成的四邊形是正方形呢?以A點為中心,AB為軸,繞A點順時針或者逆時針轉動90度,就可以得到一個點D‘ , 同樣的方法,以B
點為中心,BA為軸,繞B點順時針或者逆時針轉動90度,就可以得到一個點C‘ , 如果D‘ 的座標與D的座標相同,如果C‘ 的座標與C的座標相同 , 那麼就可以確定這個四邊形是正方形了。
旋轉可以用這個公式:
任意點(x,y),繞一個座標點(rx0,ry0)逆時針旋轉a角度後的新的座標設為(x0, y0),有公式:
x0= (x - rx0)*cos(a) - (y - ry0)*sin(a) + rx0 ;
y0= (x - rx0)*sin(a) + (y - ry0)*cos(a) + ry0 ;
既然知道如何判斷正方形了,那麼接下來,我只需要在給定的點裡面每次取出兩個點,A,B,【這裡O(N^2)的複雜度】,求出對應的C‘,D‘【由於旋轉方向不同,會有兩個這樣的解】,然後判斷在這些給定的點裡面有沒有點與C‘,D‘重合即可,如果我再暴力的去遍曆,最終複雜度會變成O(N^3),TLE無疑,這個時候,二分來作用了,我剛開始就把點給排序,然後只需要對點進行二分尋找就OK了,那麼這個時候我的複雜度是O(N^2*log(N))。當然,要注意不要重複判斷了,也就是我取A,B的時候,還有二分的時候注意一下範圍就可以了。
#include <cmath>#include <queue>#include <cstdio>#include <string>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn = 1000+5;int N,ans;struct SPoint { double x,y; SPoint() {} SPoint(int xx,int yy) : x(xx), y(yy) {} bool operator < (const SPoint& p) const { if(x == p.x) return y < p.y; return x < p.x; } bool operator == (const SPoint& p) const { return x==p.x&&y==p.y; }}pnt[maxn];//任意點(x,y),繞一個座標點(rx0,ry0)逆時針旋轉a角度後的新的座標設為(x0, y0),有公式://x0= (x - rx0)*cos(a) - (y - ry0)*sin(a) + rx0 ;//y0= (x - rx0)*sin(a) + (y - ry0)*cos(a) + ry0 ;void transXY(SPoint A, SPoint B, SPoint &C, int f) { int tx = B.x - A.x, ty = B.y - A.y; C.x = A.x - ty * f; C.y = A.y + tx * f;}int main() { //freopen("input.in","r",stdin); while(~scanf("%d",&N)&&N) { ans = 0; for(int i = 0;i < N;i++) scanf("%lf %lf",&pnt[i].x,&pnt[i].y); sort(pnt,pnt+N); for(int i = 0;i < N-3;i++) //① { for(int j = i+1;j < N-2;j++) //② { SPoint C,D; transXY(pnt[i],pnt[j],C,1); transXY(pnt[j],pnt[i],D,-1); if(binary_search(pnt+j,pnt+N,C)&&binary_search(pnt+j,pnt+N,D)) ans++; //③ transXY(pnt[i],pnt[j],C,-1); transXY(pnt[j],pnt[i],D,1); if(binary_search(pnt+j,pnt+N,C)&&binary_search(pnt+j,pnt+N,D)) ans++; //④ 注意這四個地方,避免重複判斷 } } printf("%d\n",ans); } return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
POJ 2002 Squares