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. wrk中的lua脚本(转)

    转载地址:http://www.tuicool.com/articles/IFjIJjU wrk是一款现代化的http压测工具,提供lua脚本的功能可以满足每个请求或部分请求的差异化. wrk中执行h ...

  2. Debian 入门安装与配置1

    Debian 入门安装与配置1 最近安装了多个发行版本的Linux,包括Ubuntu.Fedora.Centos和Debian,发现只有Debian在界面和稳定性等综合特性上表现最优,自己也最喜欢,所 ...

  3. log4j 分类输出

    一个log4j的问题也是折磨了我两天了. 终于算是实现了个符合需求的小demo.然而,我必须吧log4j搞定,这个乐塞. 需求描述: 用xml配置文件,将debug.info.warn.error分类 ...

  4. 几个有用的SAP安全配置的用户参数配置列表

    转自http://blog.sina.com.cn/s/blog_4f913cf80100mksj.html Parameter Brief Description login/min_passwor ...

  5. codevs 2216 线段树 两种更新方式的冲突

    题目描述 Description “神州“载人飞船的发射成功让小可可非常激动,他立志长大后要成为一名宇航员假期一始,他就报名参加了“小小宇航员夏令营”,在这里小可可不仅学到了丰富的宇航知识,还参与解决 ...

  6. this指针基础介绍

    =================this指针的由来==================== 一个学生可以有多本书一样,而这些书都是属于这个同学的:同理,如果有很多个同学在一起,那么为了确定他们的书不 ...

  7. MATLAB符号运算

    1.符号运算 使用MATLAB可以进行多项式乘除运算,也可以进行因式分解. 例1. 多项式乘除运算(x+3)3 >> syms x;>> expand((x+3)^3) ans ...

  8. JavaScript学习记录总结(五)——servlet将json数据写出去

    定义teacher和student实体 json.do   List<Student> stus=new ArrayList<Student>();        stus.a ...

  9. 求10000以内n的阶乘

    总时间限制:  5000ms 内存限制:  655360kB 描述 求10000以内n的阶乘. 输入 只有一行输入,整数n(0<=n<=10000). 输出 一行,即n!的值. 样例输入 ...

  10. 增量更新项目时的备份MyBak

    在增量更新项目时,做好备份十分重要,这里提供一个方法备份java Web所更新的文件. 把更新包放在指定目录,配好如下webappFolder.updateFolder以及bakeupFolder的路 ...