Cod sursa(job #3323463)

Utilizator _irina__irina tanase _irina__ Data 18 noiembrie 2025 13:06:16
Problema Floyd-Warshall/Roy-Floyd Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
#include <bits/stdc++.h>
#include <queue>
#include <fstream>
using namespace std;

int inf = 1e9;

void royfloyd()
{
    ifstream fin("royfloyd.in");
    ofstream fout("royfloyd.out");

    int n;
    fin >> n;

    int dist[n + 1][n + 1];

    for(int i = 1; i <= n; i ++)
        for(int j = 1; j <= n; j ++)
        {
            int ct;
            fin >> ct;
            dist[i][j] = ct;
        }

    for(int k = 1; k <= n; k ++)
    {
        for(int i = 1; i <= n; i ++)
        {
            for(int j = 1; j <= n; j ++)
            {
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
            }
        }
    }

    for(int i = 1; i <= n; i ++)
    {
        for(int j = 1; j <= n; j ++)
        {
            if(dist[i][j] == 1e9) dist[i][j] = 0;

            fout << dist[i][j] << ' ';
        }
        fout << endl;
    }
}

void dijkstra()
{
    ifstream fin("dijkstra.in");
    ofstream fout("dijkstra.out");

    int n, m;

    fin >> n >> m;

    priority_queue<pair<int, int>> pq;

    vector<long long> dist(n + 1, inf);
    vector<pair<int, int>> L[n + 1];
    vector<int> vis(n + 1, 0);

    for(int i = 1; i <= m; i ++)
    {
        int x, y, ct;

        fin >> x >> y >> ct;

        L[x].push_back({y, ct});
        //L[y].push_back({x, -ct});
    }

    dist[1] = 0;

    pq.push({-dist[1], 1});

    while(!pq.empty())
    {
        int node = pq.top().second;
        pq.pop();
        
        if(vis[node] != 1)
        {
            vis[node] = 1;
            for(auto elem: L[node])
            {
                int vecin = elem.first;
                int cost = elem.second;

                if(dist[vecin] > dist[node] + cost)
                {
                    dist[vecin] = dist[node] + cost;
                    pq.push({-dist[vecin], vecin});
                }
            }
        }
    }

    for(int d = 2; d <= n; d++)
    {
        if(vis[d] == 0) dist[d] = 0;

        fout << dist[d] << ' ';
    }
}

int main()
{
    royfloyd();
    return 0;
}