SPOJ #440. The Turtle´s Shortest Path

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:

//    440

#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 = 10000;
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 = 0; 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 = 0; i < vcnt; i ++)
    {
        dist[i] = MaxDist;
        visited[i] = false;
    }
    dist[cinx1 - 1] = 0;
    q.push(make_pair(cinx1-1, 0));

    //    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 - 1) return dist[cinx2 - 1];

        //    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<'0' || c>'9') c = gc();
  int ret = 0;
  while(c>='0' && c<='9') {
    ret = 10 * ret + c - 48;
    c = gc();
  }
  return ret;
}
/
int main()
{
    int runcnt = read_int();
    //cout << "Run " << runcnt << endl;
    while(runcnt --)
    {
        clearGraph();
        int ccnt = read_int();
        for(int ic = 1; 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-1, cinx-1, 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 0;
}
View Code

 

转载于:https://www.cnblogs.com/tonix/p/3548072.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
洛谷的SPOJ需要注册一个SPOJ账号并进行绑定才能进行交题。您可以按照以下步骤进行注册: 1. 打开洛谷网站(https://www.luogu.com.cn/)并登录您的洛谷账号。 2. 在网站顶部导航栏中找到“题库”选项,将鼠标悬停在上面,然后选择“SPOJ”。 3. 在SPOJ页面上,您会看到一个提示,要求您注册SPOJ账号并进行绑定。点击提示中的链接,将会跳转到SPOJ注册页面。 4. 在SPOJ注册页面上,按照要求填写您的用户名、密码和邮箱等信息,并完成注册。 5. 注册完成后,返回洛谷网站,再次进入SPOJ页面。您会看到一个输入框,要求您输入刚刚注册的SPOJ用户名。输入用户名后,点击“绑定”按钮即可完成绑定。 现在您已经成功注册并绑定了SPOJ账号,可以开始在洛谷的SPOJ题库上刷题了。祝您顺利完成编程练习!\[1\]\[2\] #### 引用[.reference_title] - *1* *3* [(洛谷入门系列,适合洛谷新用户)洛谷功能全解](https://blog.csdn.net/rrc12345/article/details/122500057)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [luogu p7492 序列](https://blog.csdn.net/zhu_yin233/article/details/122051384)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值