zoukankan      html  css  js  c++  java
  • HackerRank

    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
  • 相关阅读:
    js设计模式——代理模式
    js设计模式——策略模式
    js设计模式——单例模式
    Krpano vtourskin.xml 默认皮肤详解
    通过JS动态切换大场景xml
    krpano 户型地图雷达
    微信小程序开发
    CSS3的calc()使用
    Yslow
    微信分享
  • 原文地址:https://www.cnblogs.com/tonix/p/4697314.html
Copyright © 2011-2022 走看看