HDU 2112 - HDU Today (优先队列)
Posted jpphy0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 2112 - HDU Today (优先队列)相关的知识,希望对你有一定的参考价值。
问题
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 ext(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];
ext(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;
}
- 方法二:链式前向星+优先队列
#include<bits/stdc++.h>
using namespace std;
#define MXR 20010 // 2倍边数
#define MXLOC 160
#define MXLEN 35
#define pii pair<int, int>
#define inf 0x7f7f7f7f
int N, s, t, vis[MXLOC], dis[MXLOC];
int head[MXLOC], cnt;
struct Edge{
int to, tim, nxt;
}edge[MXR];
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) == 0) mp[name] = mp.size()+1;
return mp[name];
}
void ext(int start){
vis[start] = 1;
for(int i = head[start]; ~i; i = edge[i].nxt){
int to = edge[i].to;
if(vis[to]) continue;
q.push({to, dis[start]+edge[i].tim});
}
}
void add(int u, int v, int w){
edge[cnt].to = v;
edge[cnt].tim = w;
edge[cnt].nxt = head[u];
head[u] = cnt++;
}
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];
ext(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(head, -1, sizeof head), cnt = 1;
while(!q.empty()) q.pop();
mp.clear();
s = read(), t = read();
while(N--){
a = read(), b = read();
scanf("%d", &c);
add(a, b, c);
add(b, a, c);
}
ans = solve();
printf("%d\\n", ans);
}
return 0;
}
以上是关于HDU 2112 - HDU Today (优先队列)的主要内容,如果未能解决你的问题,请参考以下文章
HDU Today HDU杭电2112Dijkstra || SPFA
hdu 2112 HDU Today(map与dijkstra的结合使用)