pku2002 Squares (折半查找)

枚举正方形的一条边,查找满足条件的另外两个顶点是否存在,使用折半查找

 

#include <iostream> #include <algorithm> using namespace std; struct POINT { int x; int y; } ps[1001]; int n; bool comp(POINT p1, POINT p2) { if (p1.x != p2.x) return p1.x < p2.x; return p1.y < p2.y; } bool search(POINT p) { int low = 0, high = n, mid; while (low <= high) { mid = (low + high) / 2; if (ps[mid].x<p.x) low = mid + 1; else if (ps[mid].x>p.x) high = mid - 1; else { if (ps[mid].y<p.y) low = mid + 1; else if (ps[mid].y>p.y) high = mid -1; else return true; } } return false; } int main() { int i, j, count; POINT p, p2; while (cin>>n && n) { for (i=0; i<n; i++) cin >> ps[i].x >> ps[i].y; count = 0; sort(ps, ps+n, comp); for (i=0; i<n; i++) for (j=i+1; j<n; j++) { p.x = ps[j].y - ps[i].y + ps[j].x; p.y = ps[i].x - ps[j].x + ps[j].y; p2.x = ps[j].y - ps[i].y + ps[i].x; p2.y = ps[i].x - ps[j].x + ps[i].y; if (!search(p)) continue; if (!search(p2))continue; count++; } cout << count/2 << endl; } return 0; }

你可能感兴趣的:(search)