zoukankan      html  css  js  c++  java
  • HackerRank

    Typical Floyd-Walshall Algorithm.

    #include <cmath>
    #include <cstdio>
    #include <vector>
    #include <string>
    #include <iostream>
    #include <algorithm>
    #include <queue>
    #include <unordered_map>
    #include <unordered_set>
    using namespace std;
    
    const long DIST_MAX = std::numeric_limits<long>::max();
    
    int main() 
    {
            const int INF = std::numeric_limits<int>::max();
            
            //    Get input
            int n, m; cin >> n >> m;
            vector<vector<int>> dist(n, vector<int>(n, INF));
            int mm = m;
            while (mm--){
                int x, y, r;
                cin >> x >> y >> r;
                dist[x - 1][y - 1] = r;
            }
            for (int i = 0; i < n; i++)
                dist[i][i] = 0;
    
            //    Floyd-Walshall
            for (int v = 0; v < n; v ++)
            for (int f = 0; f < n; f++)
            for (int t = 0; t < n; t++)
            {
                if (f == t) continue;
    
                int fv = dist[f][v];
                int vt = dist[v][t];            
                if (fv != INF && vt != INF)
                {
                    if (dist[f][t] > (fv + vt))
                        dist[f][t] = fv + vt;
                }
            }
    
            //    Queries
            int q; cin >> q;
            while (q--)
            {
                int a, b; cin >> a >> b;
                int ret = dist[a - 1][b - 1];
                cout << (ret == INF ? -1 : ret) << endl;
            }
        
        return 0;
    }
    View Code
  • 相关阅读:
    python day1
    Vue与react的择决
    CommonJS规范
    js面向对象的程序设计
    正则匹配所有的a标签
    js-静态、原型、实例属性
    js中参数不对应问题
    sublime常用快捷键
    JSON.parse()和JSON.stringify()
    setAttribute()
  • 原文地址:https://www.cnblogs.com/tonix/p/4697213.html
Copyright © 2011-2022 走看看