跳到正文

个人记录

火炬传递 题解

banned_gutongxing约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年1月12日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

公约

  1. E.u,E.v,E.wE.u,E.v,E.w

题目

BSOJ\color{#7F1083}\text{BSOJ} 和 Luogu\color{#3498DB} \text{Luogu}

火炬传递

题目描述

20122012 伦敦奥运会就要来了,此次伦敦奥运的火炬将不再进行全球传递,也就是只在本国英国传递。伦敦奥组委计划将火炬传遍英国的各个角落,这下可苦了某些城市的市长,由于欧债危机,他们实在无钱支付火炬传递需要的开销。于是设计一条花费最小的火炬传递路线势在必行。XX 市的格局很神奇,这个市是一个类似威尼斯的水城,共有 nn 个岛,并且有 mm条桥连接着它们,这些桥在火炬传递期间只能单向行进,通过每座桥都有一定的费用(包括环境布置等)。火炬传递的路线必须是一个环,也就是说,你可以任意选择一个岛出发,最后必须回到这个岛。现在请你找出花费最小的一条火炬传递路线。

输入格式

输入第一行包含两个整数 nn,mm,表示岛屿个数和桥的个数。

接下来mm行,第 ii 行两个整数,xx,yy, cc,表示可以从岛 xx 经过第 ii 座桥到达岛 yy,花费为 cc。

输出格式

输出一行,最小花费。

样例 #1

样例输入 #1

代码
10 15
8 9 1
6 2 10
2 4 5
3 1 5
1 4 3
6 7 10
2 9 9
1 5 8
10 6 5
3 10 4
8 6 8
6 5 4
6 4 8
3 2 9
7 8 5

样例输出 #1

代码
13

提示

对于 50%50\% 的数据 n≤200,m≤2000n\le200, m\le2000 对于100%100\%的数据 n≤1000,m≤10000n\le1000, m\le10000

思路

由暴力到正解

我们撕开一个环,发现:一个环就是一条边加上一条更长的边。

所以我们思考:

对于每一条边 EE ,其实形成边权和最小的环便是E.u<−E.vE.u <- E.v 的最短路径加上 E.wE.w 的结果。

求答案:O(m)O(m) 。

那怎么快速全源最短路呢?

以每个点为源点分别跑一次 Dijkstra 。

总时间复杂度:O(n2log⁡n)O(n^2\log n)。

下面是 Coding\mathbf{Coding} 和 Typing\mathbf{Typing} (copying\mathbf{copying})时间!

C++
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e3+10;
const int MAXM = 1e4+10;
const int INF = 0x3f3f3f3f;
//Grath
int n,m,x,y,z,ans = INF;
struct edge{
	int to,w;
};
vector<edge> v[MAXN];
//Dijkstra
int dis[MAXN][MAXN];
bool vis[MAXN][MAXN];
bool operator < (const edge &b,const edge &a){
	return a.w<b.w;
}
priority_queue<edge> pq;
void dijkstra(int s){
	dis[s][s] = 0;
	pq.push({s,0});
	while(!pq.empty()){
		auto x = pq.top();
		pq.pop();
		if(vis[s][x.to]) continue;
		vis[s][x.to] = true;
		for(auto i:v[x.to]){
			if(dis[s][i.to]>dis[s][x.to]+i.w){
				dis[s][i.to] = dis[s][x.to]+i.w;
				pq.push({i.to,dis[s][i.to]});
			}
		}
	}
}
signed main(){
	memset(dis,0x3f,sizeof(dis));
	scanf("%d%d",&n,&m);
	for(int i = 1;i<=m;i++){
		scanf("%d%d%d",&x,&y,&z);
		v[x].push_back({y,z});
	}
	for(int i = 1;i<=n;i++) dijkstra(i);
	for(int i = 1;i<=n;i++){
		for(auto j:v[i]){
			ans = min(ans,j.w+dis[j.to][i]);
		}
	}
	printf("%d",ans);
	return 0;
}
原文