1. 程式人生 > >POJ - 1654 Area (初入幾何)

POJ - 1654 Area (初入幾何)

You are going to compute the area of a special kind of polygon. One vertex of the polygon is the origin of the orthogonal coordinate system. From this vertex, you may go step by step to the following vertexes of the polygon until back to the initial vertex. For each step you may go North, West, South or East with step length of 1 unit, or go Northwest, Northeast, Southwest or Southeast with step length of square root of 2. 

For example, this is a legal polygon to be computed and its area is 2.5: 

Input

The first line of input is an integer t (1 <= t <= 20), the number of the test polygons. Each of the following lines contains a string composed of digits 1-9 describing how the polygon is formed by walking from the origin. Here 8, 2, 6 and 4 represent North, South, East and West, while 9, 7, 3 and 1 denote Northeast, Northwest, Southeast and Southwest respectively. Number 5 only appears at the end of the sequence indicating the stop of walking. You may assume that the input polygon is valid which means that the endpoint is always the start point and the sides of the polygon are not cross to each other.Each line may contain up to 1000000 digits.

Output

For each polygon, print its area on a single line.

題意:初始點在原點,現在給出8種走的方式,數字1~9每個數字表示一種走的方式。5表示回到原點。當走完所有點是會形成一個圖形,最後問你這個圖形的面積

這個圖形必然可以分割有限個以原點為頂點的三角形,我們只要算出所有三角形的面積就可以得到答案。前幾天複習了下凸包,剛好叉積就可以解決這個問題,叉積的性質大家自行百度,叉積的計算方式是行列式。

a=(x1,y1.0),b=(x2,y2,0).

a×b=i       j      k

        x1    y1   0

        x2    y2   0

=(0*y1-0*y2)*i+(0*x1-0*x2)*j+(x1*y2-x2*y1)*k

=(x1*y2-x2*y1)*k

而三角形的一個點是原點,那麼另外兩個點的向量就是(x1-0)(y1-0),(x2-0)(y2-0)。所以一個三角形的面積就可以是(x1*y2-x2*y1)

這題坑點還挺多的,寫的時候要注意

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
#define ll long long
char s[1000005];
int dx[10]={0,1,1,1,0,0,0,-1,-1,-1};
int dy[10]={0,-1,0,1,-1,0,1,-1,0,1};
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s",s);
        int len=strlen(s);
        if(len<3&&s[0]=='5')
            printf("0\n");
        else
        {
            ll x=0,y=0,nx,ny,aa=0;
            for(int i=0; i<len; i++)
            {
                nx=x+dx[s[i]-'0'];
                ny=y+dy[s[i]-'0'];
                aa+=x*ny-y*nx;
                x=nx;
                y=ny;
            }
            if(aa<0)
                aa=-aa;
            if(aa%2==0)
            printf("%lld\n",aa/2);
            else
            printf("%lld.5\n",aa/2);
        }
    }
}