hdu 3685 Rotational Painting

来源:互联网 发布:赤月传说2麻痹升级数据 编辑:程序博客网 时间:2024/06/08 03:43

题目:有一副玻璃画,要立在桌子上,可以在垂直于桌面的平面旋转,问有几种稳定的摆放状态。

分析:计算几何、凸包、重心。摆放条件:首先、能够稳定摆放一定是用凸包的边与桌面接触;其次、如果稳定,那么重心必须落在对应的凸包的边内(边上不行)。

            1.重心计算:将多边形分割成三角形(分割形式任意),然后每个三角形用自己的重心代替,看成质点,质量为三角形面积(利用叉乘计算),最后求出所有质点的平均值即可;此算法和面积计算一样与凸凹无关。

            2.稳定状态:对于给已求得的重心枚举凸包的边即可;对于稳定的判断,可以得到一些判断条件:

               (1).两底角为锐角,会出现精度问题。

               (2).利用叉乘计算,稍稍有点麻烦。

               (3).利用解析几何的可行域求解,即对于给定直线方程带入两点结果符号相反。

               这里利用方案3,计算方便,也不会出现精度问题。已知重心c,凸包底边ab,则(b.x-a.x)*(x-c.x)+(b.y-a.y)*(y-c.y)=0即为目标方程。

注意:精度问题、过多的浮点运算会出现精度问题。

#include <algorithm> #include <iostream>#include <cstdlib>#include <cstdio>#include <cmath>using namespace std;typedef struct pnode{double x,y,d;}point; point P[ 50005 ];point S[ 50005 ];point MP;double crossproduct( point a, point b, point c )//ab到ac {return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);}double dist( point a, point b ){return sqrt((b.x-a.x)*(b.x-a.x)+(b.y-a.y)*(b.y-a.y));}point center( int N ){double sum = 0.0,s;point  p; p.x = p.y = 0.0;if ( N == 0 ) return p;if ( N == 1 ) return P[0];if ( N == 2 ) {p.x = (P[0].x+P[1].x)/2;p.y = (P[0].y+P[1].y)/2;return p;}for ( int i = 2 ; i < N ; ++ i ) {s = crossproduct( P[0], P[i-1], P[i] );p.x += (P[0].x+P[i-1].x+P[i].x)*s;p.y += (P[0].y+P[i-1].y+P[i].y)*s;sum += s;}p.x /= 3*sum; p.y /= 3*sum;return p;}bool cmp1( point a, point b ){if ( a.x == b.x ) return a.y < b.y;else return a.x < b.x;}bool cmp2( point a, point b ){return crossproduct( P[0], a, b ) > 0;}bool cmp3( point a, point b ){double cp = crossproduct( P[0], a, b );if ( cp == 0.0 ) {if ( !crossproduct( P[0], a, MP ) )return a.d < b.d;else return a.d > b.d;}else return cp > 0;}int Graham( int N ){point c = center( N );sort( P+0, P+N, cmp1 );sort( P+1, P+N, cmp2 );//处理共线,去掉共线的点 for ( int i = 1 ; i < N ; ++ i )P[i].d = dist( P[0], P[i] );MP = P[N-1];sort( P+1, P+N, cmp3 );int top = -1;if ( N > 0 ) S[++ top] = P[0];if ( N > 1 ) S[++ top] = P[1];if ( N > 2 ) {S[++ top] = P[2];for ( int i = 3 ; i < N ; ++ i ) {while ( crossproduct( S[top-1], S[top], P[i] ) < 0 ) -- top;S[++ top] = P[i];}}S[++ top] = P[0];int    count = 0;double A,B;for ( int i = 0 ; i < top ; ++ i ) {A = S[i+1].x-S[i].x;B = S[i+1].y-S[i].y;if ( (A*(S[i].x-c.x)+B*(S[i].y-c.y))*(A*(S[i+1].x-c.x)+B*(S[i+1].y-c.y)) < 0 )count ++;}return count;}int main(){int  N,T; while ( scanf("%d",&T) != EOF ) while ( T -- ) {scanf("%d",&N);for ( int i = 0 ; i < N ; ++ i ) scanf("%lf%lf",&P[i].x,&P[i].y);printf("%d\n",Graham( N ));}return 0;}

原创粉丝点击