灾后重建 Floyd

Code:

#include<cstdio>
#include<algorithm>
using namespace std;
const int N=205;
const int INF=10000000+233;
int d[N][N],times[N];
int main()
{
	//freopen("in.txt","r",stdin);
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=0;i<n;++i)
		for(int j=0;j<n;++j)
			if(i!=j)d[i][j]=d[j][i]=INF;
	for(int i=0;i<n;++i)scanf("%d",&times[i]);
	times[n]=INF;
	for(int i=1;i<=m;++i)
	{
		int a,b,c;
		scanf("%d%d%d",&a,&b,&c);
		d[a][b]=d[b][a]=c;
	}
	int q,ed=0,k=0;
	scanf("%d",&q);
	while(q--)
	{
		int a,b,c;
		scanf("%d%d%d",&a,&b,&c);
		while(times[ed+1]<=c)++ed;
		for(;k<=ed;++k)
			for(int i=0;i<n;++i)
				for(int j=0;j<n;++j)
					if(d[i][k]+d[k][j]<d[i][j])d[i][j]=d[j][i]=(d[i][k]+d[k][j]);
		if(d[a][b]==INF||a>ed||b>ed)printf("-1\n");
		else printf("%d\n",d[a][b]);
	}
	return 0;
}
### 蓝桥杯竞赛中的重建题目及其解题思路 #### 1. 重建类问题的特点 蓝桥杯竞赛中涉及重建的题目通常会围绕图论展开,尤其是最短路径算法的应用。这类问题可能涉及到城之间道路修复、资源分配或者交通网络优化等问题[^1]。 #### 2. 技术要求与常用算法 对于此类问题的技术要求主要包括但不限于以下几个方面: - **数据结构**:熟练掌握邻接矩阵和邻接表表示方法。 - **算法基础**:熟悉Dijkstra算法、Floyd-Warshall算法以及SPFA(Shortest Path Faster Algorithm)。其中,SPFA虽然可以处理带有负权边的情况,但在某些情况下可能会因为性能问题而超时(TLE)[^2]。 #### 3. 示例代码实现 下面是一个基于Python语言的简单SPFA算法实现: ```python from collections import deque, defaultdict def spfa(graph, start_node): dist = {node: float('inf') for node in graph} dist[start_node] = 0 queue = deque([start_node]) in_queue = set() in_queue.add(start_node) while queue: current = queue.popleft() in_queue.remove(current) for neighbor, weight in graph[current]: if dist[neighbor] > dist[current] + weight: dist[neighbor] = dist[current] + weight if neighbor not in in_queue: queue.append(neighbor) in_queue.add(neighbor) return dist # Example usage of SPFA algorithm with a sample graph represented as adjacency list. graph_example = { 'A': [('B', 1), ('C', 4)], 'B': [('C', 1), ('D', 2)], 'C': [('D', 1)], 'D': [] } distances = spfa(graph_example, 'A') print(distances) ``` 此代码片段展示了如何通过队列来更新节点间的距离,并检测是否有更优路径可用。 #### 4. 结合实际场景分析 假设某年蓝桥杯的一道典型重建问题是关于恢复区通信线路的问题,则可以通过构建加权无向图模型解决该问题,在这个过程中需要考虑每线路的成本以及其他约束件。 #### 5. 总结建议 当面对类似题目时,除了运用上述提到的各种算法外,还应注重审题细节,比如输入规模大小是否允许复杂度较高的解决方案;另外也要善于利用平台上的优质解答作为学习参考资料。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值