hdu 1874 畅通工程续

Dijkstra单源最短路算法

#include<stdio.h>

#include<string.h>

#include<math.h>

#include<algorithm>

using namespace std;



const int maxn = 205;

int cost[maxn][maxn];

int n, m, u, v, c, su, eu;

int mincost[maxn], s[maxn];



int main()

{

    int i, j, ii;

    while (~scanf("%d%d", &n, &m))

    {

        for (i = 0; i <= n; i++)for (j = 0; j <= n; j++)cost[i][j] = 999999999;

        for (i = 0; i < m; i++)

        {

            scanf("%d%d%d", &u, &v, &c);

            if (c < cost[u][v]) cost[u][v] = c, cost[v][u] = c;

        }

        scanf("%d%d", &su, &eu);

        for (i = 0; i < n; i++) mincost[i] = cost[su][i], s[i] = 0;

        s[su] = 1; int x;

        mincost[su] = 0;

        for (ii = 0; ii < n - 1; ii++)

        {

            int minn = 999999999, flag = 0;

            for (i = 0; i < n; i++)

            if (!s[i] && mincost[i] < minn)

                minn = mincost[i], v = i, flag = 1;

            if (!flag) continue;

            s[v] = 1;

            for (i = 0; i < n; i++)

            if (!s[i] && mincost[v] + cost[v][i] < mincost[i])

                mincost[i] = mincost[v] + cost[v][i];

        }

        if (mincost[eu] != 999999999) printf("%d\n", mincost[eu]);

        else printf("-1\n");

    }

    return 0;

}

 

Bellman-Ford

 

#include<cstdio>

#include<cstring>

#include<cmath>

#include<algorithm>

using namespace std;



const int maxn = 205;

int dist[maxn];

int ee[maxn][maxn];



int main()

{

    int n, m, i, j, k, u, v, c, su, eu;

    while (~scanf("%d%d", &n, &m))

    {

        for (i = 0; i <= n; i++)

        {

            for (j = 0; j < n; j++)

            {

                if (i == j) ee[i][j] = 0;

                else ee[i][j] = 999999999;

            }

        }

        for (i = 0; i < m; i++)

        {

            scanf("%d%d%d", &u, &v, &c);

            if (c < ee[u][v]) ee[u][v] = ee[v][u] = c;

        }

        scanf("%d%d", &su, &eu);

        for (i = 0; i < n; i++) dist[i] = ee[su][i];

        for (k = 1; k <= n - 1; k++)

        for (i = 0; i < n; i++)

        for (j = 0; j < n; j++)

        if (ee[j][i] != 999999999 && dist[j] + ee[j][i] < dist[i])

            dist[i] = dist[j] + ee[j][i];

        if (dist[eu] != 999999999)printf("%d\n", dist[eu]);

        else printf("%d\n", -1);

    }

    return 0;

}

 

你可能感兴趣的:(HDU)