南阳-街区最短路径

注意这个最短路径只能是从红点沿着黑线走到蓝点!不可以穿越白色区域!

解题思路:求出x,y的中位点,然后把每个点到该点距离算出来,求和。

#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
#define MAX 20
int x[MAX],y[MAX];
int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		int m_x,m_y;
		int sum=0;
		int m,i;
		cin>>m;
		for(i=0;i<m;i++)
			cin>>x[i]>>y[i];
		sort(x,x+m);
		sort(y,y+m);
		//for(i=0;i<m;i++)
	//	{
	//		sum+=abs(x[i]-x[m/2])+abs(y[i]-y[m/2]);//一般想法,把各个点到中位点的距离加起来。
	//	}
		for(i=0;i<m/2;i++)   //(更优程序)注意不要包括中间点!,因为最后某一个点到前面对应一点的话,就会经过中间点!
		{
			sum+=x[m-1-i]-x[i]+y[m-1-i]-y[i];//思想:与其求各个点到中点距离,不如减少一半计算量,后一点减相应前一点!
		}
		cout<<sum<<endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以给你一个基于 Dijkstra 算法的追踪游戏实现。这个游戏的规则是,有一个警察和一个小偷,在一个城市里行动。警察要尽快地抓住小偷,小偷要尽可能地逃脱。每个街区都有一个固定的警察和小偷的位置。 这个游戏的实现可以分为以下几个步骤: 1.定义一个地图,包括街区的位置和道路的连接情况。 2.定义警察和小偷的初始位置。 3.使用 Dijkstra 算法计算从警察到小偷的最短路径。 4.警察按照最短路径移动,小偷则根据一定的策略移动。 5.重复步骤 3 和 4,直到小偷被捕或者逃脱成功。 下面是这个游戏的 Python 实现代码: ```python import heapq class Graph: def __init__(self): self.vertices = {} def add_vertex(self, name, edges): self.vertices[name] = edges def shortest_path(self, start, end): heap = [(0, start)] visited = set() while heap: (cost, current) = heapq.heappop(heap) if current in visited: continue visited.add(current) if current == end: return cost for (neighbor, next_cost) in self.vertices[current].items(): heapq.heappush(heap, (cost + next_cost, neighbor)) return -1 class Police: def __init__(self, graph, start): self.graph = graph self.location = start def move(self, target): path = self.graph.shortest_path(self.location, target) if path != -1: self.location = target class Thief: def __init__(self, graph, start): self.graph = graph self.location = start def move(self, police): min_distance = float('inf') best_location = self.location for neighbor in self.graph.vertices[self.location]: distance = self.graph.shortest_path(neighbor, police.location) if distance < min_distance: min_distance = distance best_location = neighbor self.location = best_location if __name__ == '__main__': g = Graph() g.add_vertex('A', {'B': 5, 'C': 2}) g.add_vertex('B', {'D': 4}) g.add_vertex('C', {'D': 2, 'E': 3}) g.add_vertex('D', {'F': 1}) g.add_vertex('E', {'F': 7}) g.add_vertex('F', {}) police = Police(g, 'A') thief = Thief(g, 'F') while True: police.move(thief.location) thief.move(police) print(f'Police: {police.location}, Thief: {thief.location}') if police.location == thief.location: print('Thief is caught!') break ``` 这个实现中,我们首先定义了一个 `Graph` 类,用于表示地图和计算最短路径。然后,我们定义了一个 `Police` 类和一个 `Thief` 类,分别表示警察和小偷。在每个回合中,警察会按照最短路径移动,小偷则会选择离警察最远的位置移动。如果警察和小偷在同一个位置,游戏结束。 上面的代码只是一个简单的示例,你可以根据自己的需求更改地图和初始位置,以及警察和小偷的移动策略。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值