POJ-2187(旋转卡壳)
2015-08-12 23:02
267 查看
题目:http://poj.org/problem?id=2187
今天终于耐下心来学习凸包和旋转卡壳了,以poj的经典例题2187为例,学习主要参考了以下两篇博文:
/article/6985015.html
/article/8132786.html
![](http://img.blog.csdn.net/20150812230140763?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
今天终于耐下心来学习凸包和旋转卡壳了,以poj的经典例题2187为例,学习主要参考了以下两篇博文:
/article/6985015.html
/article/8132786.html
#include <cstdio> #include <cmath> #include <algorithm> using namespace std; #define MAX 50005 int N; struct Point{ int x, y; } points[MAX]; Point ch[MAX]; int top; int cross(const Point& o, const Point& a, const Point& b) { return (a.x-o.x)*(b.y-o.y) - (b.x-o.x)*(a.y-o.y); } int dist2(const Point& a, const Point& b) { return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y); } struct Compare { Point o; bool operator()(const Point& a, const Point& b)const{ //return true if a should be in front b //that is oa smaller polar angle, that is ob is on the anticlockwise order of oa //so that oa x ob > 0 int r = cross(o, a, b); if(r != 0) return r > 0; return dist2(o, a) < dist2(o, b); } }; bool input() { if(scanf("%d", &N) != 1) return false; for(int i = 0; i < N; ++i) scanf("%d%d", &points[i].x, &points[i].y); return true; } int findLeftDown() { int k = 0; for(int i = 1; i < N; ++i){ if(points[i].x < points[k].x || points[i].x == points[k].x && points[i].y < points[k].y){ k = i; } } return k; } void grahamScan() { //step 1: sort up by polar angle int o = findLeftDown(); Compare comparator; comparator.o = points[o]; swap(points[o], points[0]); sort(points+1, points+N, comparator); //step 2: scan every point check if it disobey convex rule ch[0] = points[0]; ch[1] = points[1]; ch[2] = points[2]; top = 2; for(int i = 3; i < N; ++i){ while(top && cross(ch[top-1], ch[top], points[i]) <= 0) --top; ch[++top] = points[i]; } //now ch[0] ~ ch[top] are the points that compose of the convex hull } int rotateCalipers(Point* ch, int n) { int q = 1, ans = 0; ch = ch[0]; for(int p = 0; p < n; ++p){ while(cross(ch[p], ch[p+1], ch[q+1]) > cross(ch[p], ch[p+1], ch[q])) q = (q+1) % n; ans = max(ans, max(dist2(ch[p], ch[q]), dist2(ch[p+1], ch[q+1]))); } return ans; } int main() { while(input()){ grahamScan(); printf("%d\n", rotateCalipers(ch, top+1)); } return 0; }
相关文章推荐
- 快速幂取余
- 优化布局:ViewStub的应用
- 使用HttpWebRequest与HttpWebResponse抓取网页数据
- 【Android性能优化】JAVA内存管理
- maven 项目出现 java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
- POJ 2456 Aggressive cows
- 使用JDK提供的MD5算法对字符串进行加密
- django用户登录和注销
- 二分法使用方法调用的练习--修改
- KVC、 KVO
- ACM--Genetic Code(POJ 2558)
- c++,为什么要引入虚拟继承
- group by的参考地址
- final的含义
- 阻塞 与 非阻塞
- hdu 5375 Gray code(dp)
- 第10章:深入函数
- linux内存管理之malloc
- 【Android性能优化】Android-Lint:查错与代码优化利器
- c#学习之双冒泡运算符