Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

A trickier Dijkstra.

#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <queue>
#include <unordered_map>
#include <unordered_set>
using namespace std;

const int INF = std::numeric_limits<int>::max();

typedef pair<int, int> Node; // index-dist
struct Comp
{
    int operator() (const Node &v1, const Node &v2)
    {
        return v1.second > v2.second;
    }
};

int main() 
{
    int t; cin >> t;
    while (t--)
    {
        //    Setup Graph
        unordered_map<int, unordered_set<int>> g;
        for (int i = 1; i < 100; i++)
            for (int d = 1; d <= 6; d++)
                if ((i + d) <= 100)    g[i].insert(i + d);

        int n; cin >> n; // ladder
        while (n--)
        {
            int a, b; cin >> a >> b;
            g[a].clear();
            g[a].insert(b);
        }
        int m; cin >> m; // snake
        while (m--)
        {            
            int a, b; cin >> a >> b;
            g[a].clear();
            g[a].insert(b);
        }

        //    Dijstra
        vector<int> dist(101, INF);
        vector<int> god(101, 0);
        dist[1] = 0;
        priority_queue<Node, vector<Node>, Comp> hp;
        hp.push(Node(1, 0));
        while (!hp.empty())
        {
            Node i = hp.top(); hp.pop();
            for (auto &c : g[i.first])
            {
                if (dist[c] == INF || (dist[i.first] + 1) < dist[c])
                {
                    dist[c] = dist[i.first] + 1;
                    god[c] = god[i.first];
                    if ((c > i.first && (c - i.first) > 6) || (c < i.first))
                    {
                        god[c] += 1;
                    }
                    if(c == 100)
                    {
                        while(!hp.empty()) hp.pop();                              
                        break;
                    }
                    hp.push(Node(c, dist[c]));
                }
            }
        }

        int ret = dist[100];
        cout << (ret == INF ? -1 : ret - god[100]) << endl;
    }

    return 0;
}
View Code
posted on 2015-08-03 07:41  Tonix  阅读(391)  评论(0编辑  收藏  举报