zoj 1721 && poj 1556 The Doors

题意:在一个布置了障碍墙的房间里寻找一条最短路径。房间的边界为x=0,x=10,y=0,y=10.路径的起始位置为(0,5),目标位置(10,5)。在房间布置了一些竖直的墙,墙的范围是0~18,每个墙有两个门。


思路:此题是求最短路径,但关键是如何把这个图构造出来。以(0,5)为第0个顶点,以(10,5)为最后一个顶点,墙中的端点对应图中的顶点,整个图的定点数为4n+2。

接下来我们只需判断两个端点之间是否可以相连即可,对于a,b两端点,我们只需判断他们之间是否有一堵墙阻挡了a,b。


代码:

#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

const int inf = 2147483647;
const int maxn = 100;

struct point{
	double x,y;
};

struct wall{
	double x;
	double y[4];
};

int n;
point Point[4*maxn];
int cnt;				//记录点的数量 
wall Wall[maxn];
double edge[4*maxn][4*maxn];
double dist[maxn];


double Dis(point &a, point &b){
	return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}

bool Input(){
	double x,y;
	cin>>n;
	if(n == -1) return false;
	cnt = 1;
	for(int i = 1; i <= n; i++){
		cin>>x;
		Wall[i].x = x;
		for(int j = 0; j < 4; j++){
			cin>>y;
			Wall[i].y[j] = y;
			Point[cnt].x = x;
			Point[cnt].y = y;
			cnt++;
		}
	}
	Point[cnt].x = 10.0;
	Point[cnt].y = 5.0;
	cnt++;
	Wall[n+1].x = 10.0;
	return true;
}

double Cross(point &a, point &b, double x, double y){//判断点是在由a、b构成的直线上方还是下方 
	return (y-b.y)*(a.x-b.x) - (x-b.x)*(a.y-b.y);
}

bool Check(point &a, point &b){
	int posa,posb;
	for(posa = 0; posa <= n+1; posa++)	//找到a点所处的墙 
		if(Wall[posa].x >= a.x) break;
	for(posb = 0; posb <= n+1; posb++)	//找到b点所处的墙 
		if(Wall[posb].x >= b.x) break;
	if(posa == posb) return false;	//两点在一堵墙上 
	for(int i = posa+1; i < posb; i++){
		if(Cross(a,b,Wall[i].x,0.0)*Cross(a,b,Wall[i].x,Wall[i].y[0]) < 0)	
			return false;
		if(Cross(a,b,Wall[i].x,Wall[i].y[1])*Cross(a,b,Wall[i].x,Wall[i].y[2]) < 0)	
			return false;
		if(Cross(a,b,Wall[i].x,Wall[i].y[3])*Cross(a,b,Wall[i].x,10.0) < 0)	
			return false;
	}	
	return true;
}

void Create(){//建图
	for(int i = 0; i < cnt; i++) {
		for(int j = 0; j < cnt; j++){
			if(i == j) edge[i][j] = 0;
			else edge[i][j] = inf;
		}
	}
	for(int i = 0;  i < cnt-1; i++){
		for(int j = i+1; j < cnt; j++){
			if(Check(Point[i],Point[j])){
				edge[i][j] = Dis(Point[i],Point[j]);
			}
		}
	}
}

double Bellman(){
	for(int i = 0; i < cnt; i++){
		dist[i] = edge[0][i];
	}	
	for(int i = 0; i < cnt-2; i++){
		for(int v = 0; v < cnt; v++){
			for(int u = 0; u < cnt; u++){
				if(dist[u] + edge[u][v] < dist[v])
					dist[v] = dist[u] + edge[u][v];
			}
		}
	}
	return dist[cnt-1];
}

int main(){
	Point[0].x = 0.0;
	Point[0].y = 5.0;
	Wall[0].x = 0.0;
	while(Input()){
		Create();
		printf("%.2lf\n",Bellman());
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值