题目大意就是找到第一个结点到其他结点最短距离的最大值,所以首先使用Dijkstra算法找到第一个结点到其他结点的最短距离,之后再找到最大值即可:
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int N = 1000 + 10;
const int INF = 999999;
struct Edge{
int to, length;
Edge(int t, int l): to(t), length(l){
}
};
struct Point{
int number;
int distance;
Point(int n, int d): number(n), distance(d){
}
bool operator<(const Point &p) const{
return distance > p.distance;
}
};
vector<Edge> graph[N];
int dis[N];
void Dijkstra(int s){
priority_queue<Point> pq;
dis[s] = 0;
pq.push(Point(s, dis[s]));
while(!pq.empty()){
int u = pq.top().number;
pq.pop();
for(int i = 0; i < graph[u].size(); i ++ ){
int v = graph[u][i].to;
int l = graph[u][i].length;
if(dis[v] > dis[u] + l){
dis[v] = dis[u] + l;
pq.push(Point(v, dis[v]));
}
}
}
}
int Toint(string s){
int n = 0;
for(int i = 0; i < s.size(); i ++ ){
n = n * 10 + s[i] - '0';
}
return n;
}
int main(){
int n;
while(cin >> n){
string ch;
for(int i = 2; i <= n; i ++ ){
for(int j = 1; j < i; j ++ ){
cin >> ch;
if(ch != "x"){
graph[i].push_back(Edge(j, Toint(ch)));
graph[j].push_back(Edge(i, Toint(ch)));
}
}
}
memset(dis, INF, sizeof(dis));
Dijkstra(1);
int maximum = -1;
for(int i = 2; i <= n; i ++ ) maximum = max(maximum, dis[i]);
cout << maximum << endl;
}
return 0;
}
文章评论