Coding a Dijkstra is not hard. %70 of my time spent on tackling TLE, as my last post.

Dijkstra works in BFS manner, but at each step, it picks the shortest child greedily and then relax all other neighbors.

Data Structure: since there could be up to 10000 cities, storing distance for all pairs of cities are not allowed - 300+M space exceeds SPOJ's 256M limit. So I simply used std::map (my another version used GNU's hash_map but not tried its performance) as the adjacent linked list to store graph; and map<string, int> to store city name - index mapping. Again, hash_map could be better.

Anyway, here's my AC code, 11.34s:

//

#include <vector>
#include <cstdio>
#include <iostream>
#include <queue>
#include <map>
using namespace std; /*
//////////////////////////////////
// Components for GNU's hash_map
#include <backward/hash_map>
using namespace __gnu_cxx;
namespace __gnu_cxx
{
template<>
struct hash<std::string>
{
hash<char*> h;
size_t operator()(const std::string &s) const
{
return h(s.c_str());
};
};
}
*/
////////////////////////////////// const int MaxCity = ;
const int MaxDist = 0xFFFFFFF;
map<string, int> hmap;
typedef map<int, map<int, int> > DHash;
DHash distMap; bool visited[MaxCity] = {false};
int dist[MaxCity] = {MaxDist}; /////////////////////////////////////
void add_dist(int srcInx, int toInx, int cost)
{
distMap[srcInx][toInx] = cost;
}
int get_dist(int srcInx, int toInx)
{
DHash::iterator iter = distMap.find(srcInx);
if(iter != distMap.end())
{
map<int, int>::iterator iter2 = iter->second.find(toInx);
if(iter2 != iter->second.end())
{
return iter2->second;
}
}
return MaxDist;
}
/////////////////////////////////////
struct nComp
{
int operator() (const pair<int,int>& p1, const pair<int,int> &p2)
{
return p1.second > p2.second;
}
};
///////////////////////////////////////
void clearGraph()
{
hmap.clear();
distMap.clear();
} void clearRuntime(int citycnt)
{
for(int i = ; i < citycnt; i ++)
{
visited[i] = false;
dist[i] = MaxDist;
}
}
///////////////////////////////////////////
int find_shortest_path(int cinx1, int cinx2)
{
int vcnt = hmap.size(); priority_queue<pair<int, int>, vector<pair<int, int> >, nComp> q;
// Init
for(int i = ; i < vcnt; i ++)
{
dist[i] = MaxDist;
visited[i] = false;
}
dist[cinx1 - ] = ;
q.push(make_pair(cinx1-, )); // Go
while(!q.empty())
{
pair<int,int> n = q.top(); q.pop(); // Greedy, find the unvisited min-cost node
int minInx = n.first;
int minCost = n.second;
if(minCost == MaxDist) break;
visited[minInx] = true;
if(minInx == cinx2 - ) return dist[cinx2 - ]; // Relax neighbors
DHash::iterator iter = distMap.find(minInx);
map<int,int> &child = iter->second;
for(map<int,int>::iterator iMap = child.begin(); iMap != child.end(); iMap ++)
{
int i = iMap->first;
int gDist = iMap->second;
int alt = dist[minInx] + gDist;
if(alt < dist[i])
{
dist[i] = alt;
//cout << "\t\trelaxed to " << alt << " " << minInx << " to" << i <<endl;
q.push(make_pair(i, dist[i]));
}
}
} return MaxDist;
}
/////////////////////////
#define gc getchar
int read_int()
{
char c = gc();
while(c<'' || c>'') c = gc();
int ret = ;
while(c>='' && c<='') {
ret = * ret + c - ;
c = gc();
}
return ret;
}
/////////////////////////
int main()
{
int runcnt = read_int();
//cout << "Run " << runcnt << endl;
while(runcnt --)
{
clearGraph();
int ccnt = read_int();
for(int ic = ; ic <= ccnt; ic ++)
{
// cityName -> cityInx
string city_name; cin >> city_name;
int nnbr = read_int();
hmap.insert(map<string, int>::value_type(city_name, ic));
//cout << city_name << "->" << ic << endl; // Fill out adjacency matrix
while(nnbr--)
{
int cinx = read_int();
int cost = read_int();
add_dist(ic-, cinx-, cost);
//cout << ic << " <-> " << cinx << " = " << cost << endl;
}
} int qcnt = read_int();
while(qcnt --)
{
string c1, c2;
cin >> c1 >> c2;
int cinx1 = hmap[c1];
int cinx2 = hmap[c2];
// cout << c1 << "-" << c2 << " = " << cinx1 << " - " << cinx2 << endl;
clearRuntime(ccnt);
cout << find_shortest_path(cinx1, cinx2) << endl;
}
getchar();
getchar(); // should return 0xA (enter)
} return ;
}

SPOJ #440. The Turtle´s Shortest Path的更多相关文章

  1. hdu-----(2807)The Shortest Path(矩阵+Floyd)

    The Shortest Path Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others ...

  2. zoj 2760 How Many Shortest Path 最大流

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1760 Given a weighted directed graph ...

  3. The Shortest Path in Nya Graph

    Problem Description This is a very easy problem, your task is just calculate el camino mas corto en ...

  4. hdu 3631 Shortest Path(Floyd)

    题目链接:pid=3631" style="font-size:18px">http://acm.hdu.edu.cn/showproblem.php?pid=36 ...

  5. Shortest Path(思维,dfs)

    Shortest Path  Accepts: 40  Submissions: 610  Time Limit: 4000/2000 MS (Java/Others)  Memory Limit: ...

  6. Shortest Path

    Shortest Path Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)T ...

  7. (中等) HDU 4725 The Shortest Path in Nya Graph,Dijkstra+加点。

    Description This is a very easy problem, your task is just calculate el camino mas corto en un grafi ...

  8. 【ZOJ2760】How Many Shortest Path

    How Many Shortest Path 标签: 网络流 描述 Given a weighted directed graph, we define the shortest path as th ...

  9. [Swift]LeetCode847. 访问所有节点的最短路径 | Shortest Path Visiting All Nodes

    An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1) is given as graph. graph.lengt ...

随机推荐

  1. java项目上各种小问题

    md,出现好几次这种问题,还得上百度? 以此为证,再出现这种问题我就不信想不起来怎么解决!!!----清除不存在jar包 ok,第二个问题: 每个类上有无数个红叉,然而代码并没有问题 解决方案:run ...

  2. 支持 Firefox、Chrome 等主流浏览器的全站变灰 CSS 代码

    <style> html{ -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); -ms-filter: grays ...

  3. Protobuf C/C++实战笔记(1)

    前言: Protobuf作为数据交换格式, 被很多人喜欢. 数据压缩比高, 向后兼容性强, 性能优异, 而且对平台中性, 支持多语言(C/C++, JAVA, Python). 优点太多, 实在不胜枚 ...

  4. centos6.4搭建knowlededgeroot-1.0.4知识库平台

    知识库平台选择 http://www.oschina.net/project/tag/320/pkm 最近接到一个任务,要求搭建一个用于部门内部业务知识规范管理和共享的平台,目的是把部门内的FAQ知识 ...

  5. POJ 2253 Frogger

    题目链接:http://poj.org/problem?id=2253 Frogger Time Limit: 1000MS   Memory Limit: 65536K Total Submissi ...

  6. CSS控制a标签链接的四种状态

    /*CSS链接的四种状态 *a:link 普通的.未被访问的链接样式 *a:visited 用户已访问的链接样式 *a:hover 鼠标指针位于链接上方样式 *a:active 链接被点击的时刻样式 ...

  7. 单页web应用(SPA)的简单介绍

    单页 Web 应用 (single-page application 简称为 SPA) 是一种特殊的 Web 应用.它将所有的活动局限于一个Web页面中,仅在该Web页面初始化时加载相应的HTML.J ...

  8. 关于HTML的Element

    今天搞HTML的时候,发现了一些操作element的方法.先引用一篇. 1.document.getElementById(id);  2.document.getElementByTagName(t ...

  9. hdu1158 dp经典题

    题意:已知雇佣员工花费(h).解雇员工花费(f).员工每月薪水(s),员工未被解雇的话即使未工作也要付薪水,现知道每个月需要几名员工,求最低花费. 很显然,刷 DP 专题的我早早地就意识到这是一道 D ...

  10. Kali linux渗透测试的艺术 思维导图

    Kali Linux是一个全面的渗透测试平台,其自带的高级工具可以用来识别.检测和利用目标网络中未被发现的漏洞.借助于Kali Linux,你可以根据已定义的业务目标和预定的测试计划,应用合适的测试方 ...