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. 参数化SQL sql语句

    在日常的数据插入时,需要避免数据脚本注入攻击,所以进行参数化SQL很有必要. --说明参数 ) --参数赋值 ' --数据插入 ,'A')

  2. [转载]NoSQL by Martin Flower

    ============================================================== URL1 nosql ========================== ...

  3. php二分式查找

    要求数组是有序数组 1 <?php 2 #二分查找 3 function binarySearch(Array $arr, $target) { 4 $low = 0; 5 $high = co ...

  4. Spring MVC 属性文件读取注入到静态字段

    目录(?)[-] servlet-contextxml configproperties 示例属性 ConfigInfo 对应的配置bean 使用   在项目中,有些参数需要配置到属性文件xxx.pr ...

  5. HTML DOM部分---document对象;

    <style type="text/css"> #d3{ color:red} </style> </head> <body> &l ...

  6. HDU 1003 Max Sum --- 经典DP

    HDU 1003    相关链接   HDU 1231题解 题目大意:给定序列个数n及n个数,求该序列的最大连续子序列的和,要求输出最大连续子序列的和以及子序列的首位位置 解题思路:经典DP,可以定义 ...

  7. UVA-11235 Frequent values (RMQ)

    题目大意:在一个长度为n的不降序列中,有m次询问,每次询问(i,j)表示在区间(i,j)中找出出现次数最多的元素的出现次数. 题目分析:因为序列有序,可以将序列分段,并且记录每段的元素个数.每一个元素 ...

  8. tomcat的配置详解:[1]tomcat绑定域名

    转自:http://jingyan.baidu.com/article/7e440953dc096e2fc0e2ef1a.html tomcat的配置详解:[1]tomcat绑定域名分步阅读 在jav ...

  9. Android平台下的JNI开发

    JNI是Java Native Interface的缩写,通过JNI可以方便我们在Android平台上进行C/C++编程.要用JNI首先必须安装Android的NDK,配置好NDK环境之后就可以在Ec ...

  10. android基础知识13:AndroidManifest.xml文件解析

    注:本文转载于:http://blog.csdn.net/xianming01/article/details/7526987 AndroidManifest.xml文件解析. 1.重要性 Andro ...