POJ2284:线段相交 + 欧拉定理

POJ2284

题解

  • 欧拉定理:顶点数V,边数E,面数F满足V + F - E = 2,所以F = E + 2 - V
  • 点数包括原有的点和新的相交的点。所以每两条线段求交点。但是去掉交点重复的点。求得V
  • 在原先边的基础上,如果某个点在某条表上,则边数加1。求得E。
  • 注意要用unique,结构体要重载 == 运算符。

代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
using namespace std;
int const N = 300 + 10;
double const eps = 1e-8;
int n,e,c;
int dcmp(double x){    //判断符号
	if(fabs(x) < eps)	return 0;
	else return x < 0 ? -1 : 1;
}
typedef struct Point{   //点和向量
	double x,y;
	Point(){};
	Point(double x,double y):x(x),y(y){};
	Point operator - (const Point& e)const{   //减
		return Point(x - e.x,y - e.y);
	}
	Point operator + (const Point& e)const{   //减
		return Point(x + e.x,y + e.y);
	}
	double operator ^ (const Point& e)const{  //叉乘
		return x * e.y - y * e.x;
	}
	double operator * (const Point& e)const{  //点积
		return x * e.x + y * e.y;
	}
	bool operator < (const Point& e)const{   //sort操作
		return x < e.x || (x == e.x && y < e.y);
	}
	bool operator == (const Point& e)const{  //unique操作
		return dcmp(x - e.x) == 0 && dcmp(y - e.y) == 0;
	}
}Vector;
struct Line{    //直线的定义
	Point a,b;
	Line(){};
	Line(Point a,Point b):a(a),b(b){}
};
vector<Point>v;
Point p[N];
bool onsegment(Point p,Point a1,Point a2){ //点p是否在线段a1a2上,端点不重合。如果否则取等号,则端点可以重合。
	return dcmp((a1 - p) ^ (a2 - p)) == 0 && dcmp((a1 - p) * (a2 - p)) < 0;  
}
bool segment_intersection(Line line1,Line line2){  //判断线段是否相交,相交返回true
	double c1 = (line1.b - line1.a) ^ (line2.a - line1.a);
	double c2 = (line1.b - line1.a) ^ (line2.b - line1.a);
	double c3 = (line2.b - line2.a) ^ (line1.a - line2.a);
	double c4 = (line2.b - line2.a) ^ (line1.b - line2.a);
	if(dcmp(c1) * dcmp(c2) < 0 && dcmp(c3) * dcmp(c4) < 0)	return true;
	return false;
} 
Point intersection(Point p,Vector v,Point q,Vector w){   //两直线(p+tv)和(q+tw)求交点
	Vector u = p - q;
	double t = (w ^ u) / (v ^ w);
	return p + Point(v.x * t,v.y * t);
}
int main(){
	int caser = 0;
	while(~scanf("%d",&n) && n){
		v.clear();
		for(int i=0;i<n;i++){
			scanf("%lf%lf",&p[i].x,&p[i].y);
			v.push_back(p[i]);
		}
		e = --n;
		for(int i=0;i<n;i++){  //(i,i+1)与(j,j+1)的交点
			for(int j=i+1;j<n;j++)
				if(segment_intersection(Line(p[i],p[i+1]),Line(p[j],p[j+1])))
					v.push_back(intersection(p[i],p[i+1]-p[i],p[j],p[j+1]-p[j]));
		}
		sort(v.begin(),v.end());
		v.erase(unique(v.begin(),v.end()),v.end());
		for(int i=0;i<v.size();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",++caser,e + 2 - v.size());
	}
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值