POJ-1502-MPI Maelstrom [最短路][Dijkstra]


题目传送门


题意:给出一个无向图表示第i行为第i+1个主机与前i个主机之间的通信时间,’x’为不通,求从1号主机向所有主机发消息全部接受到的最短时间。

思路:Dijkstra模板题,最后遍历一遍求最大值。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

int mp[120][120];
const int inf = 0x3f3f3f3f;
int N;
void init()
{
    for (int i = 0; i < 120; i++)
        for (int j = 0; j < 120; j++)
            mp[i][j] = inf;
    return ;
}
void Dij(int x)
{
    int book[120], dis[120];
    memset(book,0,sizeof(book));
    for (int i = 1; i <= N; i++)
        dis[i] = mp[x][i];
    book[x] = 1;
    for (int i = 1; i < N; i++)
    {
        int mi = inf, f = -1;
        for (int j = 1; j <= N; j++)
        {
            if (dis[j]if (f==-1)
            break;
        book[f] = 1;
        for (int j = 1; j <= N; j++)
        {
            if (!book[j] && mp[f][j]+dis[f] < dis[j])
                dis[j] = mp[f][j]+dis[f];
        }
    }
    int ans = 0;
    for (int i = 1; i <= N; i++)
    {
        if (dis[i]!=inf)
            ans = max(dis[i],ans);
    }
    printf("%d\n", ans);
    return;
}
int main(void)
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);

    while (~scanf("%d", &N))
    {
        init();
        for (int i = 1; i < N; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                int x = 0;
                char ch[10];
                scanf(" %s", ch);
                if (ch[0]=='x')
                    continue;
                int len = strlen(ch);
                for (int k = 0; k < len; k++)
                    x = x*10 + (ch[k]-'0');
                if (mp[i+1][j]>x)
                    mp[i+1][j] = mp[j][i+1] = x; 
            }
        }
        Dij(1);
    }
    return 0;
}

你可能感兴趣的:(最短路,一条ACM咸鱼的自我修养)