目录
问题
HDU 2112 HDU Today - https://acm.hdu.edu.cn/showproblem.php?pid=2112
分析
- 题目描述是“从s到e的时间”,但实际代码是“s与e”间,因此是无向图
代码
- 方法一:邻接矩阵 + 优先队列
#include<bits/stdc++.h>
using namespace std;
#define MXLOC 160
#define MXLEN 35
#define pii pair<int, int>
#define inf 0x7f7f7f7f
int N, s, t, vis[MXLOC], dis[MXLOC], g[MXLOC][MXLOC];
char name[MXLEN];
map<string, int> mp;
struct cmp{
bool operator()(pii x, pii y){
return x.second > y.second;
}
};
priority_queue<pii, vector<pii>, cmp> q;
int read(){
scanf("%s", name);
if(!mp.count(name)) mp[name] = mp.size()+1;
return mp[name];
}
void add(int start){
vis[start] = 1;
for(int i = 1; i < MXLOC; ++i){
if(vis[i] || g[start][i] == inf) continue;
q.push({i, dis[start]+g[start][i]});
}
}
int solve(){
pii tmp;
q.push({s, 0});
while(!q.empty()){
tmp = q.top();
q.pop();
if(vis[tmp.first]) continue;
dis[tmp.first] = tmp.second;
if(tmp.first == t) return dis[t];
add(tmp.first);
}
return -1;
}
int main(){
int a, b, c, ans;
while(scanf("%d", &N), ~N){
memset(vis, 0, sizeof vis);
memset(dis, 0, sizeof dis);
memset(g, inf, sizeof g);
while(!q.empty()) q.pop();
mp.clear();
s = read();
t = read();
while(N--){
a = read(), b = read();
scanf("%d", &c);
if(c < g[a][b]) g[a][b] = g[b][a] = c;
}
ans = solve();
printf("%d\n", ans);
}
return 0;
}