題意:按指令畫多邊形,求出裏面有多少個正方形。
思路:求出面積。注意:需判斷多邊形的走向,利用叉積的正負個數。
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
int dir[][4]={{0,1},{0,-1},{-1,0},{1,0}};
int f(char ch )
{
if(ch=='U') return 0;
else if(ch=='D') return 1;
else if(ch=='L') return 2;
return 3;
}
class node
{
public:
int x,y;
};
node st[150],ld,py[150];
using namespace std;
int n,ind;
bool judge()
{
int an1=0,an2=0;
for(int i=2;i<n;i++)
{
node p0= py[i-1],p1=py[i],p2=py[(i+1)%n];
int x0= p2.x -p1.x ,y0=p2.y -p1.y ;
int x1= p1.x -p0.x ,y1=p1.y -p0.y ;
int k=(x0*y1-x1*y0);
if(k>0) an1++;
if(k<0) an2++;
}
if(an1>an2) return true;
return false;
}
void work()
{
if(judge())
{
int k=n;
for(int i=1;i<=k/2;i++)
{
node temp =py[i];py[i]=py[k-i];py[k-i]=temp;
}
}
int s=0;
s=py[0].y *(py[n-1].x -py[1].x );
for(int i=1;i<n;i++)
s+=py[i].y *(py[i-1].x -py[(i+1)%n].x );
printf("%d\n",s/2);
}
int main()
{
int t;
int i=0;
int ca=0;
scanf("%d",&t);
while(t--)
{
char s[120];
scanf("%s",s);
int len=strlen(s);
st[0].x =0;st[0].y =0;
ld=st[0];ind =0;
for(i=0;i<len;i++)
{
int k=f(s[i]);
st[i+1].x =st[i].x +dir[k][0];
st[i+1].y =st[i].y +dir[k][1];
if(st[i+1].x <ld.x ) ld=st[i+1],ind=i+1;
if(st[i+1].x ==ld.x &&st[i+1].y <ld.y ) ld=st[i+1],ind=i+1;
}
n=i;
int j=1;
i=ind;
while(j<=n)
{
py[j-1]=st[i%n];
j++,i++;
}
printf("case %d: ",++ca);
work();
}
return 0;
}