poj2653 - Pick-up sticks

                                    想看更多的解题报告: http://blog.csdn.net/wangjian8006/article/details/7870410
                                     转载请注明出处:
http://blog.csdn.net/wangjian8006

题目大意:有n根木条,一根一根的往一个坐标系上丢(给出木条两点的坐标),问最后不被覆盖的木条有哪些,即丢的木条如果和前面丢的木条交叉的话,就会覆盖前面那根木条
解题思路:用到线段交叉的判断,我用队列模拟是否被覆盖,没被覆盖的入队,并且将当前火柴和前面没被覆盖的木条比较如果交叉则前面那根出队,这样的暴力做法在时间上不知道怎么优化了,不过比较了下,我的内存还是很低的

 

/*
Memory 196K
Time  563MS
*/
#include <iostream>
#include <queue>
using namespace std;
#define min(a,b) (a>b?b:a)
#define max(a,b) (a<b?b:a)

typedef struct{
	int cnt;
	double x1,y1,x2,y2;
}Line;

int n;

double direction(double x,double y,double x1,double y1,double x2,double y2){	//叉积
	double a1=x1-x;
	double b1=y1-y;
	double a2=x2-x;
	double b2=y2-y;
	return a1*b2-a2*b1;
}

int on_segment(double x1,double y1,double x2,double y2,double x,double y){		//判断共线
	if((min(x1,x2)<=x && x<=max(x1,x2)) && (min(y1,y2)<=y && y<=max(y1,y2)))
		return 1;
	return 0;
}

int cross(Line v,Line t){		//是否交叉,根据算法导论写的
	double d1,d2,d3,d4;
	d1=direction(t.x1,t.y1,t.x2,t.y2,v.x1,v.y1);	//算叉积
	d2=direction(t.x1,t.y1,t.x2,t.y2,v.x2,v.y2);
	d3=direction(v.x1,v.y1,v.x2,v.y2,t.x1,t.y1);
	d4=direction(v.x1,v.y1,v.x2,v.y2,t.x2,t.y2);
	if(d1*d2<0 && d3*d4<0) return 1;		//直接和0比较的话时间是625MS
	if(!d1 && on_segment(t.x1,t.y1,t.x2,t.y2,v.x1,v.y1)) return 1;
	if(!d2 && on_segment(t.x1,t.y1,t.x2,t.y2,v.x2,v.y2)) return 1;
	if(!d3 && on_segment(v.x1,v.y1,v.x2,v.y2,t.x1,t.y1)) return 1;
	if(!d4 && on_segment(v.x1,v.y1,v.x2,v.y2,t.x2,t.y2)) return 1;
	return 0;
}

void input(){
	queue <Line>q;
	Line v,t;
	int i;
	scanf("%lf%lf%lf%lf",&v.x1,&v.y1,&v.x2,&v.y2);
	v.cnt=1;
	q.push(v);

	for(i=2;i<=n;i++){
		scanf("%lf%lf%lf%lf",&t.x1,&t.y1,&t.x2,&t.y2);
		t.cnt=i;
		q.push(t);		//用当前的作为队尾
		while(!q.empty()){
			v=q.front();q.pop();		//一个一个出队,直到队尾
			if(t.cnt==v.cnt) {
				q.push(t);
				break;
			}
			if(!cross(v,t)) q.push(v);		//如果不交叉继续入队
		}
	}

	v=q.front();q.pop();
	printf("Top sticks: %d",v.cnt);
	while(!q.empty()){
		v=q.front();q.pop();
		printf(", %d",v.cnt);
	}
	printf(".\n");
}

int main(){
	while(scanf("%d",&n) && n){
		input();
	}
	return 0;
}


 

 

你可能感兴趣的:(算法,优化,struct,input)