POJ3907 Build Your Home(向量基本運算求多邊形面積)
阿新 • • 發佈:2018-12-15
古伽蘭那
【題目大意】
給你一個多邊形,詢問其面積。
【輸入格式】
輸入包含多組資料,每組資料第一個數為N,表示為N邊形,接下來給出N對(x,y),表示多邊形頂點的座標(x,y為實數,頂點按順時針或逆時針給出)
【輸出格式】
對於每組資料輸出多邊形面積(四捨五入)。
【樣例輸入】
1 123.45 67.890
3 0.001 0 1.999 0 0 2
5 10 10 10 12 11 11 12 12 12.0 10.0
0
【樣例輸出】
0
2
3
【題目分析】
求多邊形面積。。。。。好板啊。。。。。。
對於一個多邊形的面積就視作多個三角形的面積求和(當然是方向面積),如下圖所示:
因為我們計算的是有向面積,根據給出頂點的順序,有可能會出現最後算出的面積為負的情況,所以我們還要取個絕對值。
最後提醒一點:叉積得到的是平行四邊形的面積,所以要除以2!除以2!
【程式碼~】
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; const int MAXN=1e5+10; int n,m; struct point{ double x,y; point(double a=0,double b=0){ x=a,y=b; } friend inline point operator+(const point &a,const point &b){ return point(a.x+b.x,a.y+b.y); } friend inline point operator-(const point &a,const point &b){ return point(a.x-b.x,a.y-b.y); } friend inline double operator*(const point &a,const point &b){ return a.x*b.y-a.y*b.x; } friend inline double dot(const point &a,const point &b){ return a.x*b.x+a.y*b.y; } inline double dist() { return x*x+y*y; } }; struct polygon{ point q[MAXN]; }a; double area() { if(n==1||n==2) return 0; double ret=0; a.q[n+1]=a.q[1]; for(int i=1;i<=n;++i) ret+=a.q[i]*a.q[i+1]; return ret/2; } int main() { while(scanf("%d",&n)&&n) { for(int i=1;i<=n;++i) scanf("%lf%lf",&a.q[i].x,&a.q[i].y); cout<<(int)(fabs(area())+0.5)<<'\n'; } return 0; }