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. Asp.net 执行回调操作后 无法更新ViewState的问题

    源码 待续...

  2. ZOJ 1105 FatMouse’s Tour

    原题链接 题目大意:FM要去逛街,他可以走任何街道,在任何路口转弯.他走一条陌生街道的速度是20公里每小时,走一条熟悉街道的速度是50公里每小时.输入是街道信息,输出消耗时间. 解法:本质就是浮点运算 ...

  3. eBay_Relist(退换刊登费)

    如果物品首次刊登结束时没有人中标,或是买家并没有付款完成交易,那么卖家以通过重新刊登的方法来再次销售.如果该物品在第二次刊登时成功售出,且满足eBay的重新刊登退费条件,那么eBay便会退还重新刊登的 ...

  4. leetcode 120 Triangle ----- java

    Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent n ...

  5. LAMT基于mod_proxy方式的负载均衡集群

    一.apache服务器 # httpd -D DUMP_MODULES | grep  proxy查看是否有 proxy_balancer_module (shared)模块 二.编辑配置文件 1.编 ...

  6. 【BZOJ1008】【HNOI2008】越狱

    以前水过的水题 原题: 监狱有连续编号为1...N的N个房间,每个房间关押一个犯人,有M种宗教,每个犯人可能信仰其中一种.如果相邻房间的犯人的宗教相同,就可能发生越狱,求有多少种状态可能发生越狱 1& ...

  7. C++@语句块

    #include <iostream> using namespace std; int main() { { int x=1; cout << x << endl ...

  8. 嵌入式Linux开发——内容介绍与开发环境的搭建

    嵌入式Linux开发步骤 设计自己的硬件系统 编写Bootloader 裁剪自己的Linux内核 开发移植设备驱动 构建根文件系统 开发应用程序 嵌入式Linux学习要点 熟练使用开发工具和相关指令集 ...

  9. [poj 3261]Milk Patterns

    后缀数组搞一下就可以了喵~ 其实这道题的第一个想法是 SAM ,建完后缀自动机后拓扑排序跑一遍统计下每个子串的出现次数就 O(N) 就妥妥过掉了 后缀树也是 O(N) 的,统计一下每个节点对应的子树中 ...

  10. java编程之:org.apache.commons.lang3.text.StrTokenizer

    第一个api测试:按特殊符号进行分词,并遍历每一个分词部分 public static void main(String[] args) { String aString="AB-CD-EF ...