公约
题目
火炬传递
题目描述
伦敦奥运会就要来了,此次伦敦奥运的火炬将不再进行全球传递,也就是只在本国英国传递。伦敦奥组委计划将火炬传遍英国的各个角落,这下可苦了某些城市的市长,由于欧债危机,他们实在无钱支付火炬传递需要的开销。于是设计一条花费最小的火炬传递路线势在必行。 市的格局很神奇,这个市是一个类似威尼斯的水城,共有 个岛,并且有 条桥连接着它们,这些桥在火炬传递期间只能单向行进,通过每座桥都有一定的费用(包括环境布置等)。火炬传递的路线必须是一个环,也就是说,你可以任意选择一个岛出发,最后必须回到这个岛。现在请你找出花费最小的一条火炬传递路线。
输入格式
输入第一行包含两个整数 ,,表示岛屿个数和桥的个数。
接下来行,第 行两个整数,,, ,表示可以从岛 经过第 座桥到达岛 ,花费为 。
输出格式
输出一行,最小花费。
样例 #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提示
对于 的数据
对于的数据
思路
由暴力到正解
我们撕开一个环,发现:一个环就是一条边加上一条更长的边。
所以我们思考:
对于每一条边 ,其实形成边权和最小的环便是 的最短路径加上 的结果。
求答案: 。
那怎么快速全源最短路呢?
以每个点为源点分别跑一次 Dijkstra 。
总时间复杂度:。
下面是 和 ()时间!
#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;
}