HDOJ 1874 畅通工程续

单源最短路径,Dijkstra,参考白书的写法;

注意INF不能定义为0x7fffffff,因为后面相加可能会溢出,题目中距离最大为10000;

这道题的变态之处在于有重边,遇到重边时需要更新w[i, j]w[j, i],WA多次,15ms。

# include <stdio.h>
# include <string.h>

# define INF 0x10ffffff

int main()
{
    int k, i, j, n, m, s, t;
    char v[201];
    int x, d[201], w[201][201];
        
    while (~scanf("%d%d", &n, &m))
    {
        for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            w[i][j] = INF;
        for (k = 0; k < m; ++k)
        {
            scanf("%d%d%d", &i, &j, &x);
            if (w[i][j] > x) w[j][i] = w[i][j] = x;
           }
        scanf("%d%d", &s, &t);
        if (s == t) {puts("0"); continue;}
        
        memset(v, 0, sizeof(v));
        for (k = 0; k < n; ++k) d[k] = INF;
        d[s] = 0;
        for (k = 0; k < n; ++k)
        {
            x = INF;
            for (j = 0; j < n; ++j) if (!v[j] && d[j]<=x) x = d[i=j];
            v[i] = 1;
            for (j = 0; j < n; ++j) if (d[j] > (m=d[i]+w[i][j])) d[j] = m;
        }
        
        if (d[t] < INF) printf("%d\n", d[t]);
        else puts("-1");
    }
    
    return 0;
}

posted on 2012-04-22 14:46  getgoing  阅读(247)  评论(0编辑  收藏  举报

导航