P1907 设计道路 题解

题目传送门

解法

思路

求“最小不满值”,还给了一些点和边,明显是求最短路。

算法流程

记走 Dirt Road 和 Rome Road 一个单位长度时的不满值为 D D D R R R

前置知识:欧几里得距离Dijkstra

  • 按照输入的建 Rome Road。边权为 R × ( x 1 − x 2 ) 2 + ( y 1 − y 2 ) 2 R\times\sqrt{(x_1-x_2)^2+(y_1-y_2)^2} R×(x1x2)2+(y1y2)2 x 1 , y 1 , x 2 , y 2 x_1,y_1,x_2,y_2 x1,y1,x2,y2 分别为两点坐标。
  • 输入起点(码头)和终点(家)。可以将它们记为 0 0 0 号和 n + 1 n+1 n+1 号点。
  • 遍历任意两点建 Dirt Road。边权为 D × ( x 1 − x 2 ) 2 + ( y 1 − y 2 ) 2 D\times\sqrt{(x_1-x_2)^2+(y_1-y_2)^2} D×(x1x2)2+(y1y2)2
  • 进行 Dijkstra。
代码
#include <iostream>
#include <queue>
#include <vector>
#include <cmath>
using namespace std;

struct node//节点
{
	double x,y;
};
struct ndfp//给堆优化用的
{
	int id;
	double d;
	friend bool operator < (ndfp a,ndfp b)
	{
		return a.d<b.d;
	}
};

//计算两点间欧几里得距离
inline double dist(double x1,double y1,double x2,double y2)
{
	return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}

int main()
{
	double D,R;//不满值
	int n;
	scanf("%lf %lf\n%d",&D,&R,&n);
	node p[n+2];
	double e[n+2][n+2];//邻接矩阵
	fill(*e,*e+(n+2)*(n+2),0x3f3f3f3f);
	for(int i=1;i<=n;i++)
	{
		scanf("%lf %lf",&p[i].x,&p[i].y);
	}
	int a,b;
	while(true)
	{
		scanf("%d %d",&a,&b);
		if(!(a||b))
			break;
		e[a][b]=R*dist(p[a].x,p[a].y,p[b].x,p[b].y);//建 Rome Road
		e[b][a]=R*dist(p[a].x,p[a].y,p[b].x,p[b].y);
	}
	double bx,by,ex,ey;
	scanf("%lf %lf %lf %lf",&bx,&by,&ex,&ey);
	p[0].x=bx;
	p[0].y=by;
	p[n+1].x=ex;
	p[n+1].y=ey;
	for(int i=0;i<=n+1;i++)
	{
		for(int j=0;j<=n+1;j++)
		{
			if(i!=j)//建 Dirt Road
				e[i][j]=min(e[i][j],D*dist(p[i].x,p[i].y,p[j].x,p[j].y));
		}
	}
	priority_queue<ndfp> q;//堆
	q.push({0,0});
	ndfp t;
	double dis[n+2];
	fill(dis,dis+(n+2),0x3f3f3f3f);
	dis[0]=0;
	while(!q.empty())//Dijkstra(我写堆优化因为好写)
	{
		t=q.top();
		q.pop();
		if(t.d!=dis[t.id])
		{
			continue;
		}
		for(int i=0;i<=n+1;i++)
		{
			if(dis[i]>dis[t.id]+e[t.id][i])
			{
				dis[i]=dis[t.id]+e[t.id][i];
				q.push({i,dis[i]});
			}
		}
	}
	printf("%.4lf",dis[n+1]);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值