九度 1545 奇怪的连通图(最短路径变形)

题目

已知一个无向带权图,求最小整数k。使仅使用权值小于等于k的边,节点1可以与节点n连通

 

思路

1. 这应该是最短路径的变形题目

2. 把经典 dijkstra 的距离计算公式稍微变形一下就好了

3. 这道题 BFS 应该也可以做

4. 下面的代码超时了, 最后一个案例没能算出来, 我尝试把 Edge 都换成 Edge*, 没想到更慢...

 

代码 未通过 九度 测试

#include <iostream>
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;

class Edge {
public:
    Edge(int _ed, int _wt):ed(_ed), weight(_wt){}
    Edge() {
        Edge(0,0);
    }
    int ed, weight;

    bool operator<(const Edge &ths) const {
        return this->weight > ths.weight;
    }
};

vector<Edge> graph[10010];
int dis[10010];


int dijkstra(int n) {
    priority_queue<int> heap;
    heap.push(1);
    dis[1] = 0;

    while(!heap.empty()) {
        int father = heap.top();
        heap.pop();
        if(father == n)
            continue;

        for(int i = 0; i < graph[father].size(); i ++) {
            int j = graph[father][i].ed;

            if(max(dis[father],graph[father][i].weight) < dis[j]) {
                dis[j] = max(dis[father],graph[father][i].weight);
                heap.push(j);
            }
        }
    }

    if(dis[n] == 0X3F3F3F3F)
        return -1;
    return dis[n];
}

int main() {
    freopen("testcase.txt", "r", stdin);
    int nodes, edges;
    while(scanf("%d%d", &nodes, &edges) != EOF) {
        int st, ed, wt;
        for(int i = 1; i <= nodes; i ++) {
            graph[i].clear();
            dis[i] = 0X3F3F3F3F;
        }

        for(int i = 0; i < edges; i ++) {
            scanf("%d%d%d", &st, &ed, &wt);
            graph[st].push_back(Edge(ed, wt));
            graph[ed].push_back(Edge(st, wt));
        }

        int res = dijkstra(nodes);
        printf("%d\n", res);
    }
    return 0;
}

 

posted @ 2014-03-01 21:41  SangS  阅读(272)  评论(0编辑  收藏  举报