zoukankan      html  css  js  c++  java
  • 九度 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
    ", res);
        }
        return 0;
    }
  • 相关阅读:
    第一部分:开发前的准备-第二章 基础入门
    多线程笔记
    .net平台下垃圾回收机制
    xml基本操作和保存配置文件应用实例
    .net平台下C#socket通信(中)
    .net平台下C#socket通信(上)
    泛型
    面向过程和面向对象及面向对象的三大特征
    值类型和引用类型及参数传递
    js中typeof与instanceof区别
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3575689.html
Copyright © 2011-2022 走看看