dijkstra算法~痛苦三个半时

畅通工程续

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 22889    Accepted Submission(s): 8035


Problem Description
某省自从实行了很多年的畅通工程计划后,终于修建了很多路。不过路多了也不好,每次要从一个城镇到另一个城镇时,都有许多种道路方案可以选择,而某些方案要比另一些方案行走的距离要短很多。这让行人很困扰。

现在,已知起点和终点,请你计算出要从起点到终点,最短需要行走多少距离。
 

Input
本题目包含多组数据,请处理到文件结束。
每组数据第一行包含两个正整数N和M(0<N<200,0<M<1000),分别代表现有城镇的数目和已修建的道路的数目。城镇分别以0~N-1编号。
接下来是M行道路信息。每一行有三个整数A,B,X(0<=A,B<N,A!=B,0<X<10000),表示城镇A和城镇B之间有一条长度为X的双向道路。
再接下一行有两个整数S,T(0<=S,T<N),分别代表起点和终点。
 

Output
对于每组数据,请在一行里输出最短需要行走的距离。如果不存在从S到T的路线,就输出-1.
 

Sample Input
3 3
0 1 1
0 2 3
1 2 1
0 2
3 1
0 1 1
1 2
 

Sample Output
2
-1

 最开始用的是Bellman-Ford算法,因为这个算法求的是有向无环图,所以我又改了改,用的是矩阵存储,但是还是没有过。后来用dijkstra算法,本来是用dfs更新最小距离的,但是这个也没过,可能是我对dfs哪里设置的条件不对。后来看书上的算法,这才过了。好郁闷! 

这道题有几点值得说:

1、这是个双向图。

2、a—>b和b—>a的长度可能不一样,坑爹啊

3、a—>b的路可能有多条,你得取个最小的存,巨坑爹啊

4、注意所用算法特点,当s==t时是否需要单独列出来说明。

#include<iostream>
#include<algorithm>
#define MAX 200
#define INF 100000000
using namespace std;
int cost[MAX][MAX];
int d[MAX], N;
bool used[MAX];
void dijkstra(int s){
    fill(d, d + MAX, INF);
    d[s] = 0;
    while (true){
        int v = -1;
        for (int u = 0; u < N; u++){
            if (!used[u] && (v == -1 || d[u] < d[v]))v = u;
        }
        if (v == -1)break;
        used[v] = true;
        for (int u = 0; u < N; u++){
            d[u] = min(d[u], d[v] + cost[v][u]);
        }
    }
}
int main()
{
    int M, s, t, x;
    while (cin >> N >> M){
        memset(used, 0, sizeof(used));
        for (int i = 0; i < MAX; i++){
            fill(cost[i], cost[i] + MAX, INF);
        }
        for (int i = 0; i < M; i++){
            cin >> s >> t >> x;
            if (cost[s][t]>x){
                cost[s][t] = x;
                cost[t][s] = x;
            }
        }
        cin >> s >> t;//起点和终点

        if (s == t){
            cout << 0 << endl;
        }
        else {
            dijkstra(s);
            if (d[t] != INF){
                cout << d[t] << endl;
            }
            else{
                cout << -1 << endl;
            }
        }
    }
    return 0;
}

 

posted @ 2014-02-17 21:50  偶尔会寂寞  阅读(330)  评论(2编辑  收藏  举报