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. 说说Audition消除歌曲中的人声

    今天再说说消除人声,音乐中人声的消除有多种方法,但都很难完全消除,而且效果越好越难消除,一首音效极佳的立体声歌曲是无法完全消除人声的.本人常用的是以下三种方法.第1种如下图,此方法简单,但是完成后变成 ...

  2. Xcode编译异常和警告汇总(持续更新中)

    1.Method definition for 'xxx' not found xxx的方法没有实现 出现原因.h声明了xxx方法但是.m没有实现xxx方法 解决方法:在类的.m文件实现xxx方法   ...

  3. 硬盘缓存的最佳方案,DiskLruCache完全解析

    收藏自:http://blog.csdn.net/guolin_blog/article/details/28863651

  4. union与union的区别

    把2个具有相同列及数据类型的 结果 放到一起显示,并且不去重.select a,b,c from table1union allselect ca,cb,cc from table2 而union会对 ...

  5. SQL server 2008 数据库企业版安装教程图解

    SQL Server 2008是一个重大的产品版本,它推出了许多新的特性和关键的改进,使得它成为至今为止的最强大和最全面的SQL Server版本.  在现今数据的世界里,公司要获得成功和不断发展,他 ...

  6. 使用isInEditMode解决可视化编辑器无法识别自定义控件的问题

    如果在自定义控件的构造函数或者其他绘制相关地方使用系统依赖的代码, 会导致可视化编辑器无法报错并提示:Use View.isInEditMode() in your custom views to s ...

  7. 故障模块名称: mso.dll

    本人今天早上打开word文档的时候打不开了,反复试了n次也不成,一想八成儿要重新装了,结果我点开详细信息看了一下,看到了“故障模块名称: mso.dll”这个提示,结果我就放到了百度上找了一下,都是只 ...

  8. 【P1373】奶牛的卧室

    看山神的题解写出来的,sro_dydxh_orz 原题:奶牛们有一个习惯,那就是根据自己的编号选择床号.如果一头奶牛编号是a,并且有0..k-1一共k张床,那么她就会选择a  mod  k号床作为她睡 ...

  9. java的nio之:java的nio系列教程之DatagramChannel

    Java NIO中的DatagramChannel是一个能收发UDP包的通道.因为UDP是无连接的网络协议,所以不能像其它通道那样读取和写入.它发送和接收的是数据包. 打开 DatagramChann ...

  10. phpstorm用正则删除PHP代码空行小技巧

    有很多小伙伴会遇到代码空行特别多,但是一行一行删除肯定很烦躁,这时候就需要用到批量删除空行. 怎么批量删除空行呢? 我的办法是用正则把所有空行找到,然后一键全部替换. 首先把Match Case和Re ...