[wikioi]回家
2013-10-27 17:54
330 查看
http://wikioi.com/problem/1079/
单源最短路径,可以用dijkstra来做。这里采用了heap优化,复杂度是(V+E)logV。这里用了STL的优先队列(堆),重复加入pair没有问题,因为dist小的会先出来。为了避免重复扩展,用了visit判重,这个也不是必须的。
注意的是:
1.pair使用的时候,把距离放在first的位置,那么在priority queue里,距离小的会先出来。
2.priority_queue<pp, vector<pp>, greater<pp> > que;这样定义,小的先出来。
3.使用graph[from][to] ?来判断是否用from=>to这条路。
单源最短路径,可以用dijkstra来做。这里采用了heap优化,复杂度是(V+E)logV。这里用了STL的优先队列(堆),重复加入pair没有问题,因为dist小的会先出来。为了避免重复扩展,用了visit判重,这个也不是必须的。
注意的是:
1.pair使用的时候,把距离放在first的位置,那么在priority queue里,距离小的会先出来。
2.priority_queue<pp, vector<pp>, greater<pp> > que;这样定义,小的先出来。
3.使用graph[from][to] ?来判断是否用from=>to这条路。
#include <iostream> #include <queue> #include <vector> #include <map> #include <set> #include <utility> #include <climits> #include <functional> using namespace std; #define pp pair<int, char> int main() { int n; cin >> n; map<char, map<char, int> > graph; // 'A'-'Z', 'a'-'z' map<char, int> dist; set<char> visit; for (int i = 0; i < n; i++) { char from, to; int weight; cin >> from >> to >> weight; graph[from][to] = min(weight, graph[from][to] ? graph[from][to]: INT_MAX); graph[to][from] = min(weight, graph[to][from] ? graph[to][from]: INT_MAX); } int ans = INT_MAX; char ansc; priority_queue<pp, vector<pp>, greater<pp> > que; dist['Z'] = 0; que.push(pp(0, 'Z')); while (!que.empty()) { pp edge = que.top(); que.pop(); int weight = edge.first; char node = edge.second; if (visit.count(node) != 0) continue; visit.insert(node); for (map<char,int>::iterator it = graph[node].begin(); it != graph[node].end(); it++) { if (!dist.count(it->first) || it->second + dist[node] < dist[it->first]) { // add to que dist[it->first] = it->second + dist[node]; que.push(pp(dist[it->first], it->first)); if (ans > dist[it->first] && it->first >= 'A' && it->first < 'Z') { ans = dist[it->first]; ansc = it->first; } } } } cout << ansc << " " << ans << endl; return 0; }
相关文章推荐
- wikioi 回家c
- 有这样一群青年在别人放假的时候她们不回家?为什么?
- 【程序员归家计划】放假回家之前拜服务器?不存在的,这才是保证程序员过好年的正确打开方式
- EOJ 华东师范大学2月月赛 F-回家咯
- [alg] 熊回家
- 我回家了!
- 今天没有学到什么东西,晚上回家一定要补上
- “突袭”回家(虽然这不是我的故事但真的很感动)
- 明天回家
- 快回家了,感觉什么事情都不想做,除了吃饭睡觉
- 回家过年了,暂时不来上网了.放到20号.爽啊
- [导入]第二个年头没回家过年了。
- 回家团聚咯
- 回家了
- 国庆回家纪事-之二
- 〔转贴〕春节还是“春劫”?请给我一张回家的票
- 今年过年不回家
- 今天下午回家:提前给大家拜个年!
- 回家
- 回家了,两个月后上线。