UVALive - 3263 That Nice Euler Circuit (几何 蓝书)

#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
const double ep=1e-10;
const int maxn=3e2+10;

struct Point {
	double x, y;
	Point(){}
	Point(double x, double y): x(x), y(y){}
	bool operator < (const Point A) const{ return x<A.x || (x==A.x&&y<A.y);}
	
};
typedef Point Vector;

int dcmp(double x){
	if(fabs(x) < ep) return 0; else return x<0? -1 : 1;
}

Point operator + (Point A, Vector B) { return Point(A.x+B.x, A.y+B.y); }
Point operator - (Point A, Point B) { return Vector(A.x-B.x, A.y-B.y); }
Vector operator * (Vector A, double p) { return Vector(A.x*p, A.y*p); }
Vector operator / (Vector A, double p) {return Vector(A.x/p, A.y/p); }
bool operator == (const Point &A, const Point &B) { return (dcmp(A.x-B.x)==0 && dcmp(A.y-B.y)==0); }
double Dot(Vector A, Vector B){ return A.x*B.x+A.y*B.y; }
double Cross(Vector A, Vector B){ return A.x*B.y-A.y*B.x; }

bool SegmentProperIntersection(Point a1, Point a2, Point b1, Point b2){
	double c1=Cross(a2-a1, b1-a1), c2=Cross(a2-a1, b2-a1);
	double c3=Cross(b2-b1, a1-b1), c4=Cross(b2-b1, a2-b1);
	return dcmp(c1)*dcmp(c2)<0 && dcmp(c3)*dcmp(c4)<0;
}

Point GetLineIntersection(Point a1, Vector v1, Point a2, Vector v2){
	Vector v=a1-a2;
	double t=Cross(v2, v)/Cross(v1, v2);
	return a1+v1*t;
}

bool OnSegment(Point p, Point a, Point b){
	return dcmp(Cross(a-p, b-p))==0 && dcmp(Dot(a-p, b-p))<0;
}

int main() {
	int n, cas=0;
	Point  p[maxn], v[maxn*maxn];
	while(~scanf("%d", &n) && n) {
		for(int i=0; i<n; i++)
		{
			scanf("%lf%lf", &p[i].x, &p[i].y);
			v[i]=p[i];
		}
		n--;	
		int c=n, e=n;
		
		for(int i=0; i<n; i++)
			for(int j=i+1; j<n; j++)
				if(SegmentProperIntersection(p[i], p[i+1], p[j], p[j+1]))
					v[c++]=GetLineIntersection(p[i], p[i+1]-p[i], p[j], p[j+1]-p[j]);
		
		sort(v, v+c);
		c=unique(v, v+c)-v;//一定要加上原先的点再去重,因为原先的的端点可能落在原先的线段上,当再有边穿过时,并没有产生新边。
		for(int i=0; i<c; i++)
			for(int j=0; j<n; j++)
				if(OnSegment(v[i], p[j], p[j+1])) e++;
		
		printf("Case %d: There are %d pieces.\n", ++cas, 2+e-c);
	}
	return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页