【floyd的灵活运用】LOJ 1174 Commandos

KIDx的解题报告

 

题目链接:http://lightoj.com/volume_showproblem.php?problem=1174

 

题意:无限支军队从起点出发,最少要多长时间路过所有城市并且到达终点?

 

利用folyd 插点法的思想即可解决

 

找到dist[s][i] + dist[i][t]的最大值即为所求最小值

#include <iostream>
using namespace std;
#define M 105
#define inf 0x3fffffff
 
int dist[M][M], n;
 
void init ()
{
    int i, j;
    for (i = 0; i < n; i++)
    {
        dist[i][i] = 0;
        for (j = i + 1; j < n; j++)
            dist[i][j] = dist[j][i] = inf;
    }
}
 
void floyd ()
{
    int i, j, k;
    for (k = 0; k < n; k++)
        for (i = 0; i < n; i++)
            for (j = 0; j < n; j++)
                if (dist[i][k] != inf && dist[k][j] != inf &&
					dist[i][k] + dist[k][j] < dist[i][j])
                    dist[i][j] = dist[i][k] + dist[k][j];
}
 
int main()
{
    int t, cc = 1, q, a, b, s, e, ans, i;
    scanf ("%d", &t);
    while (t--)
    {
        scanf ("%d%d", &n, &q);
        init();
        while (q--)
        {
            scanf ("%d%d", &a, &b);
            dist[a][b] = dist[b][a] = 1;
        }
        floyd ();
        scanf ("%d%d", &s, &e);
        ans = 0;
        for (i = 0; i < n; i++)
        {
            if (dist[s][i] == inf || dist[i][e] == inf)
                continue;
            int tp = dist[s][i] + dist[i][e];
            if (tp > ans)
                ans = tp;
        }
        printf ("Case %d: %d\n", cc++, ans);
    }
    return 0;
}

 

你可能感兴趣的:(C++,算法,ACM,最短路,KIDx)