Cod sursa(job #3151312)

Utilizator Paul281881818818181991919191881818Draghici Paul Paul281881818818181991919191881818 Data 20 septembrie 2023 16:48:45
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include <fstream>
#include <vector>
#include <queue>
#define INF (1 << 30)
std::ifstream fin("royfloyd.in");
std::ofstream fout("royfloyd.out");
std::vector<std::vector<std::pair<int, int>>> V;
std::vector<int> dist, viz, d;

int main(){
    int n, m, x;
    fin >> n ;
    V = std::vector<std::vector<std::pair<int, int>>> (n + 1);
    viz = d = dist = std::vector<int> (n + 1);
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= n; j++){
            fin >> x;
            if(x)
                V[i].push_back({j, x});
        }
    }
    for(int i = 1; i <= n; i++){
        V[0].push_back({i, 0});
    }
    std::queue<int> Q;
    std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> Q1;
    Q.push(0);
    int ok = 1;
    while(!Q.empty()){
        int node = Q.front();
        Q.pop();
        if(ok == 0) break;
        for(std::pair<int, int> it : V[node]){
            if(dist[node] + it.second < dist[it.first]){
                dist[it.first] = dist[node] + it.second;
                viz[it.first] ++;
                if(viz[it.first] >= n){
                    ok = 0; 
                }
            }
        }
    }
    if(ok == 1){
        for(int i = 1; i <= n; i++){
            for(std::pair<int, int> it : V[i]){
                it.second = it.second + dist[i] - dist[it.first];
            }
        }
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= n; j++){
                d[j] = INF;
            }
            d[i] = 0;
            Q1.push({0, i});
            while(!Q1.empty()){
                int node = Q1.top().second;
                Q1.pop();
                for(std::pair<int, int> it : V[node]){
                    if(d[node] + it.second < d[it.first]){
                        d[it.first] = d[node] + it.second;
                        Q1.push({d[it.first], it.first});
                    }
                }
            }
            for(int j = 1; j <= n; j++){
                if(d[j] == INF){
                    fout << 0 << " ";
                }
                else fout << d[j] + dist[j] - dist[i] << " ";
            }
            fout << "\n";
        }
    }
    else fout << "ciclu neg";
}