Cod sursa(job #607724)

Utilizator SpiderManSimoiu Robert SpiderMan Data 13 august 2011 12:41:55
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <queue>
# include <vector>
using namespace std;

# define verf ++poz == hg ? fread ( ch, 1, hg, stdin ), poz = 0 : 0

const char *FIN = "bellmanford.in", *FOU = "bellmanford.out";
const int MAX = 50005, hg = 1 << 13, oo = 0x3f3f3f3f;

vector < pair <int, int> > G[MAX];
int N, M, poz, dp[MAX], cnt[MAX];
char ch[hg];
bool viz[MAX];

inline void cit ( int &x ) {
    int semn = 1;
    if ( ch[0] == '\0' ) fread ( ch, 1, hg, stdin ) ;
    else for ( ; (ch[poz] < '0' || ch[poz] > '9') && ch[poz] != '-' ; verf ) ;
    for ( x = 0 ; ch[poz] >= '0' && ch[poz] <= '9' || ch[poz] == '-' ; (ch[poz] == '-' ? semn = -1 : x = x * 10 + ch[poz] - '0'), verf ) ;
    x *= semn;
}

struct comp {
    bool operator () (const int &A, const int &B) {
        return dp[A] > dp[B];
    }
};

priority_queue < int, vector <int>, comp > Q ;

void solve (void) {
    memset (dp, oo, sizeof (dp));
    for (dp[1] = 0, Q.push (viz[1] = 1); ! Q.empty (); ) {
        int act = Q.top (); viz[act] = 0; Q.pop ();
        for (vector < pair <int, int> > :: iterator it = G[act].begin (); it != G[act].end (); ++it)
            if (dp[act] + it -> second < dp[it -> first]) {
                dp[it -> first] = dp[act] + it -> second;
                if (viz[it -> first] == 0) {
                    if (cnt[it -> first] > N) {
                        printf ("Ciclu negativ!");
                        exit (0);
                    } else {
                        Q.push (it -> first);
                        viz[it -> first] = 1, ++cnt[it -> first];
                    }
                }
            }
    }
}

int main (void) {
    freopen (FIN, "r", stdin);
    freopen (FOU, "w", stdout);

    cit (N), cit (M);
    for (int i = 1, x, y, z; i <= M; ++i) {
        cit (x), cit (y), cit (z);
        G[x].push_back (make_pair (y, z));
    }
    solve ();
    for (int i = 2; i <= N; ++i)
        printf ("%d ", dp[i] < oo ? dp[i] : 0);
}