-
D -- 计算特殊多边形面积
- Description
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
he 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.
- Sample Input
4 5 825 6725 6244865
- Sample Output
0 0 0.5 2
- 题目理解
其实计算几何的题目模板真的很重要,尤其是很多基础模板,很多题都需要转换成基础的东西重复去做,总结归纳很重要。这一题就是把多顶点的不规则多边形变成许多的三角形去计算,通过建立直角坐标系直接通过向量的叉积进行运算。详情参考白书。
#include<cstdio>
typedef long long ll;
struct point{
ll x,y;
//point(double x=0, double y=0):x(x),y(y){}
};
using namespace std;
ll cal(point& a,point& b){//后面记得除以2
return a.x*b.y-a.y*b.x;
}
const int maxn=1e6+5;
char str[maxn];
ll op[2][10]={{0,-1,0,1,-1,0,1,-1,0,1},{0,-1,-1,-1,0,0,0,1,1,1}};
int main()
{
point p1,p2;
int t;
scanf("%d",&t);
while(t--){
scanf("%s",str+1);
//printf("%s\n",str+1);
p1.x=0,p1.y=0;
p2.x=0,p2.y=0;
ll sum=0;
int cur=1;
while(str[cur]!='5'){
int opr=str[cur]-'0';
//printf("!!!!%d\n",opr);
p2.x=p2.x+op[0][opr],p2.y=p2.y+op[1][opr];
//printf("!!!%d %d %d %d\n",p1.x,p1.y,p2.x,p2.y);
sum+=cal(p1,p2);
//printf("!!%d %d %d\n",cur,tt,sum);
p1.x=p2.x,p1.y=p2.y;
cur++;
}
//printf("%d\n",sum);
if(sum<0) sum=(-sum);
if(sum&1)
printf("%lld.5\n",sum/2);
else
printf("%lld\n",sum/2);
}
return 0;
}