11 • 3个月前
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;
const int INF = numeric_limits<int>::max();
struct Edge {
int to;
int time;
};
struct Compare {
bool operator()(const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second;
}
};
int calculateMinTime(int n, const vector<vector<Edge>>& graph) {
vector<int> dist(n + 1, INF);
priority_queue<pair<int, int>, vector<pair<int, int>>, Compare> pq;
dist[1] = 0;
pq.push({1, 0});
while (!pq.empty()) {
int current = pq.top().first;
int currentDist = pq.top().second;
pq.pop();
if (currentDist > dist[current]) continue;
for (const Edge& edge : graph[current]) {
int next = edge.to;
int time = edge.time;
if (dist[next] > dist[current] + time) {
dist[next] = dist[current] + time;
pq.push({next, dist[next]});
}
}
}
int maxTime = 0;
for (int i = 1; i <= n; ++i) {
if (dist[i] == INF) return -1;
maxTime = max(maxTime, dist[i]);
}
return maxTime;
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<Edge>> graph(n + 1);
for (int i = 0; i < m; ++i) {
int u, v, k;
cin >> u >> v >> k;
graph[u].push_back({v, k});
graph[v].push_back({u, k});
}
int result = calculateMinTime(n, graph);
cout << result << endl;
return 0;
}
评论:
请先登录,才能进行评论