HackerRank - "Snakes and Ladders: The Quickest Way Up"

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值