POJ - 2387 Til the Cows Come Home

POJ - 2387 链接
双向边,求最短路径长度,一道铁定的板子无疑了,这里用了堆优化的Dijkstra来写。

//Powered
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const int N1 = 1e3 + 10, N2 = 4e3 + 10;
int head[N1], to[N2], nex[N2], value[N2], cnt;
int visit[N1], dis[N1], n, m;
struct cmp {
    bool operator () (const PII &a, const PII &b) const {
        return a.second > b.second;
    }
};
void add(int x, int y, int w) {
    to[cnt] = y;
    value[cnt] = w;
    nex[cnt] = head[x];
    head[x] = cnt++;
}
void Dijkstra() {
    for(int i = 1; i <= n; i++) dis[i] = INF, visit[i] = 0;
    dis[1] = 0;
    priority_queue<PII, vector<PII>, cmp> q;
    q.push(make_pair(1, 0));
    while(!q.empty()) {
        int temp = q.top().first;
        q.pop();
        if(visit[temp]) continue;
        visit[temp] = 1;
        for(int i = head[temp]; i; i = nex[i]) {
            if(dis[to[i]] > dis[temp] + value[i]) {
                dis[to[i]] = dis[temp] + value[i];
                q.push(make_pair(to[i], dis[to[i]]));
            }
        }
    }
    printf("%d\n", dis[n]);
}
int main() {
    // freopen("in.txt", "r", stdin);
    int x, y, w;
    while(scanf("%d %d", &m, &n) != EOF) {
        cnt = 1;
        for(int i = 0; i < m; i++) {//双向加边
            scanf("%d %d %d", &x, &y, &w);
            add(x, y, w);
            add(y, x, w);
        }
        Dijkstra();
    }
    return 0;
}
posted @ 2020-01-06 18:39  lifehappy  阅读(63)  评论(0编辑  收藏  举报