[NC14550]旅行
一、题目
二、思路
这题固定了三个点,起点、中转点、终点,很容易想到用dijkstra来写,但是直接一遍dijkstra并不能马上找到两条最长的路径,所以我们可以通过枚举每个点作为中转点时的情况,与这个点距离最远的两个点就是起点和终点,每次和当前的最长路径取最大值即可
时间复杂度: mlogn * n
三、代码
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int N = 2020;
int h[N], e[N], ne[N], w[N], idx;
int dist[N];
bool st[N];
int n, m;
int max1, max2;
void add(int x, int y, int z){
w[idx] = z; e[idx] = y; ne[idx] = h[x]; h[x] = idx ++;
}
void dijkstra(int u){
memset(dist, 0x3f, sizeof dist);
memset(st, false, sizeof st);
dist[u] = 0;
priority_queue<PII, vector<PII>, greater<PII> > heap;
heap.push({0, u});
while(heap.size()){
PII k = heap.top();
heap.pop();
int ver = k.second, distance = k.first;
if(st[ver]) continue;
st[ver] = true;
for(int i = h[ver]; i != -1; i = ne[i]){
int j = e[i];
if(dist[j] > distance + w[i]){
dist[j] = distance + w[i];
heap.push({dist[j], j});
//cout << j << endl;
}
}
}
for(int k = 1; k <= n; k ++){ //判断哪两个点才是最大的两条路
if(max1 < dist[k] && dist[k] != 0x3f3f3f3f){
max2 = max1;
max1 = dist[k];
//cout << k << endl;
}
else if(max2 < dist[k] && dist[k] != 0x3f3f3f3f) max2 = dist[k];
}
//cout << endl;
}
int main(){
int t;
int a, b, c;
int maxn = 0;
cin >> t;
while(t --){
idx = 0;
cin >> n >> m;
for(int i = 0; i <= n + 5; i ++){
h[i] = -1;
e[i] = 0;
ne[i] = 0;
w[i] = 0;
}
for(int i = 1; i <= m; i ++){
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
add(b, a, c);
}
maxn = 0;
for(int i = 1; i <= n; i ++){ //枚举每个中转点作为dijkstra的起点
max1 = 0, max2 = 0;
dijkstra(i);
//cout << max1 << " " << max2 << endl;
if(max1 != 0 && max2 != 0){
maxn = max(maxn, max1 + max2);
}
}
if(maxn == 0) cout << "-1" << endl;
else cout << maxn << endl;
}
return 0;
}


浙公网安备 33010602011771号