Cod sursa(job #2053475)

Utilizator Alex18maiAlex Enache Alex18mai Data 31 octombrie 2017 19:58:10
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream cin ("royfloyd.in");
ofstream cout ("royfloyd.out");

class cmp{
public:
    bool operator() (pair <int , int> a , pair<int ,int> b){
        return a.second > b.second;
    }
};

int n;
int mat[105][105];
vector < vector < pair <int , int> > > gr(105);

priority_queue < pair <int , int> , vector < pair <int , int> > , cmp> Q;
int dp[105];
const int inf = 2e9;

void put_inf(){
    for (int i=1; i<=n; i++){
        dp[i] = inf;
    }
}

void dijkstra(int root){

    put_inf();

    dp[root] = 0;
    Q.push({root , 0});

    while (!Q.empty()){
        pair<int ,int> now = Q.top();
        Q.pop();
        if (dp[now.first ]!= now.second){
            continue;
        }
        for (auto &x : gr[now.first]){
            if (dp[x.first] > now.second + x.second){
                dp[x.first] = now.second + x.second;
                Q.push({x.first , dp[x.first]});
            }
        }
    }

    gr[root].clear();

    for (int i=1; i<=n; i++){
        if (dp[i] != inf && i != root){
            mat[root][i] = dp[i];
            gr[root].push_back({i , dp[i]});
        }
    }

}

int main() {

    ios::sync_with_stdio(false);
    cin.tie(NULL);

    cin>>n;

    for (int i=1; i<=n; i++){
        for (int j=1; j<=n; j++){
            cin>>mat[i][j];
            if (mat[i][j] != 0){
                gr[i].push_back({j , mat[i][j]});
            }
        }
    }

    for (int i=1; i<=n; i++){
        dijkstra(i);
    }

    for (int i=1; i<=n; i++){
        for (int j=1; j<=n; j++){
            cout<<mat[i][j]<<" ";
        }
        cout<<'\n';
    }

    return 0;
}