您的位置:首页 > Web前端 > JavaScript

hdoj2112-HDU Today(dijsktra)

2016-11-09 12:32 281 查看
题目链接

思路

首先输入的车站名字为单词,不便于运算,因此我用一个map < string, int >容器储存信息,一个变量num给车站编号,每当车站第一次出现时,给车站编号为num,然后num+1,以便给下一个车站编号;

然后这是求最短路问题,因此我采用dijsktra+堆优化求解;

#include <iostream>
#include <algorithm>
#include <fstream>
#include <cstring>
#include <string>
#include <vector>
#include <functional>
#include <queue>
#include <cstdio>
#include <map>
using namespace std;

const int INF = 0x3f3f3f3f;
const int MAX = 10000+5;
int t, s, d;
int n;  //城市数
int dist[MAX];
bool vis[MAX];
map<string, int> m;

class Node {   //边信息
public:
int to, w;
Node(int _to, int _w) {
to = _to;
w = _w;
}
};

struct cmp {
bool operator()(int a, int b) {
return dist[a] > dist[b];
}
};

vector<vector<Node> > v(MAX);   //用来储存边信息,邻接表

void dijsktra(int st, int e) {
priority_queue<int, vector<int>, cmp> pq;
dist[st] = 0;
pq.push(st);
while(!pq.empty()) {
int t = pq.top();
pq.pop();
if(t == e)
{
cout << dist[e] << endl;
return ;
}
vis[t] = false;
int s = v[t].size();
for(int i = 0; i < s; ++ i) {
int to = v[t][i].to;
int w = v[t][i].w;
if(dist[to] > dist[t] + w) {
dist[to] = dist[t] + w;
if(!vis[to])
pq.push(to);
}
}
}
cout << "-1" << endl;
}

int getNum(string s, int &num)   //根据车站名得到编号
{
if(!m[s])//当车站第一次出现时,给节点编号,存进map容器中
{
m[s] = num ++;
}
return m[s];
}

int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
//ifstream cin("data.in");
int n;
while(cin >> n&& n != -1) {
memset(dist, INF, sizeof(dist));
memset(vis, false, sizeof(vis));
int num = 1, s, e;
//num用来记录车站的编号,从1开始,当车站第一次出现时给车站编号,然后num++;
//s为起始点,t为终点
string str;
cin >> str;
s = getNum(str, num);
cin >> str;
e = getNum(str, num);

for(int i = 0; i < n; i ++) {
int from, to, w;
string f, t;
cin >> f >> t >> w;
from = getNum(f, num);
to = getNum(t, num);
v[from].push_back(Node(to, w));
v[to].push_back(Node(from, w));
}
dijsktra(s, e);
for(int i = 0; i <= n; i ++)    //每次运算完之后注意清空容器
{
v[i].clear();
}
m.clear();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdoj 最短路