Cod sursa(job #2451907)

Utilizator alexoloieriAlexandru Oloieri alexoloieri Data 28 august 2019 18:23:34
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <bits/stdc++.h>

using namespace std;

class floydWarshall
{
#define inf 999999999
#define uint unsigned int
    std::vector<std::vector<uint>>dist;
    uint n;
    bool computeDists(std::vector<std::vector<uint>> &ret, uint n)
    {
        if (n == 0) return false;
        for (uint i=1; i<=n; ++i)
            for (uint j=1; j<=n; ++j)
                if (i != j && !ret[i][j])
                    ret[i][j] = inf;
        for (uint k=1; k<=n; ++k)
            for (uint i=1; i<=n; ++i)
                for (uint j=1; j<=n; ++j)
                    if (ret[i][k] + ret[k][j] < ret[i][j])
                        ret[i][j] = ret[i][k] + ret[k][j];
        for (uint i=1; i<=n; ++i)
            for (uint j=1; j<=n; ++j)
                if (ret[i][j] == inf)
                    ret[i][j] = 0;
        return true;
    }
public:
    bool setNumberOfNodes(uint n)
    {
        if (n == 0) return false;
        dist.resize(n+1);
        for (uint i=1; i<=n; ++i)
            dist[i].resize(n+1, 0);
        this->n = n;
        return true;
    }
    bool addEdge(uint x, uint y, uint d)
    {
        if (x > n || y > n) return false;
        dist[x][y] = d;
        return true;
    }
    std::vector<std::vector<uint>> getDistMatrix()
    {
        std::vector<std::vector<uint>> ret = dist;
        computeDists(ret, n);
        return ret;
    }
    bool computeDistMatrix(std::vector<std::vector<uint>> &ans)
    {
        uint n = ans.size() - 1;
        return computeDists(ans, n);
    }
};

int main()
{
    freopen("royfloyd.in","r",stdin);
    freopen("royfloyd.out","w",stdout);
    int n, x;
    floydWarshall fw;
    cin>>n;
    fw.setNumberOfNodes(n);
    for (int i=1;i<=n;++i)
        for (int j=1;j<=n;++j)
    {
        cin>>x;
        fw.addEdge(i, j, x);
    }
    auto ans = fw.getDistMatrix();
    for (auto row:ans)
    {
        if (row.size() == 0) continue;
        for (int i=1;i<=n;++i)
            cout<<row[i]<<' ';
        cout<<'\n';
    }
    return 0;
}