Cod sursa(job #1378729)

Utilizator vlady1997Vlad Bucur vlady1997 Data 6 martie 2015 13:55:41
Problema Floyd-Warshall/Roy-Floyd Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#define INF 10000000
using namespace std;
struct bellman
{
    vector <int> nod, cost;
};
bellman g[101];
queue <int> q;
int a[101][101], Cost[101], n;
bool used[101];
void bellman_ford (int x)
{
    int i, nod;
    while (!q.empty()) q.pop();
    memset(used,0,sizeof(used));
    for (i=1; i<=n; i++) Cost[i]=INF;
    q.push(x); Cost[x]=0; used[x]=true;
    while (!q.empty())
    {
        nod=q.front();
        q.pop();
        used[nod]=false;
        for (i=0; i<g[nod].nod.size(); i++)
        {
            if (Cost[nod]+g[nod].cost[i]<Cost[g[nod].nod[i]])
            {
                Cost[g[nod].nod[i]]=Cost[nod]+g[nod].cost[i];
                if (!used[g[nod].nod[i]])
                {
                    used[g[nod].nod[i]]=true;
                    q.push(g[nod].nod[i]);
                }
            }
        }
    }
}
int main()
{
    int i, j;
    freopen("royfloyd.in","r",stdin);
    freopen("royfloyd.out","w",stdout);
    scanf("%d",&n);
    for (i=1; i<=n; i++)
        for (j=1; j<=n; j++) scanf("%d",&a[i][j]);
    for (i=1; i<=n; i++)
    {
        for (j=1; j<=n; j++)
        {
            if (a[i][j]!=0)
            {
                g[i].nod.push_back(j);
                g[i].cost.push_back(a[i][j]);
            }
        }
    }
    for (i=1; i<=n; i++)
    {
        bellman_ford(i);
        for (j=1; j<=n; j++)
        {
            if (Cost[j]==-1) Cost[j]=0;
            printf("%d ",Cost[j]);
        }
        printf("\n");
    }
    return 0;
}