Stockbroker Grapevine(AC) Dijkstra算法

#include <iostream>
#include <memory.h>
using namespace std;
int weight[101][101], dis[101], pi[101];
int visit[101] = {0};
int minTime = 10000, vertexNum = 0;
void input()
{
    int p = 0, cost = 0;
    for (int j=1; j<=vertexNum; j++)
    {
        cin >> weight[j][0];
        for (int i=1; i<=weight[j][0]; i++)
        {
            cin >> p >> cost;
            weight[j][p] = cost;
        }
    }
}
void Relax(int u, int v)
{
    if (dis[v] > dis[u] + weight[u][v])
    {
        dis[v] = dis[u] + weight[u][v];
        pi[v] = u;
    }
}
void Dijkstra(int s)
{
    for (int i=0; i<=100; i++)
    {
        dis[i] = 10000;
        pi[i] = -1;
        visit[i] = 0;//千万不要忘了在初始化的时候将保存“访问标记”的数组 visit 也清空;
    }
    dis[s] = 0;
    int minimum = 1000;
    int j;
    for (int k=1; k<=vertexNum; k++)
    {
        minimum = 1000;
        for (int i=1; i<=vertexNum; i++)
            if (dis[i] <= minimum && !visit[i])//不要忘了这里有等号,是 ”<=“,而不是 ”<“,因为可能有两个点到源点的距离相同,只能分先后访问,不能只访其一;
            {
                j = i;
                minimum = dis[i];
            }
        visit[j] = 1;
        for (int i=1; i<=100; i++)
            if (weight[j][i] != 10000)
                Relax(j, i);
    }
}

int main()
{
    int ss = 0;
    int maxTime = 0;
    while (cin >> vertexNum, vertexNum)
    {
        ss = 0;
        minTime = 10000;
        memset(visit , 0, sizeof(visit));
        for (int i=0; i<101; i++)
        {
            for (int j=0; j<101; j++)
            {
                weight[i][j] = 10000;
            }
        }
        input();
        for (int s=1; s<=vertexNum; s++)
        {
            Dijkstra(s);
            maxTime = 0;
            for (int i=1; i<=vertexNum; i++)
            {
                if (dis[i] >= maxTime)
                    maxTime = dis[i];
            }
            if (maxTime < minTime)
            {
                minTime = maxTime;
                ss = s;
            }
        }
        if (minTime != 10000)
            cout << ss << ' ' << minTime << endl;
        else
            cout << "disjoint" << endl;
    }
    return 0;
}

  使用 Dijkstra 算法,效率会比 Bellman Ford 算法高些,但写的算法有问题,直到今天才找到,在代码中作了注释,其他的与前一篇相同。由于没有使用数组来保存边的信息,而是用直接检查邻接矩阵的方法,代码简洁了许多。visit 数组定义为局部数组或许更好,那样的话就不用考虑初始化时清空的问题了。

posted @ 2011-09-03 20:18  SunnyDay2015  阅读(236)  评论(0编辑  收藏  举报