HDU 1595 find the longest of the shortest 最短路变形

  • Post author:
  • Post category:其他



题目



https://cn.vjudge.net/problem/HDU-1595


题意

:给出一个不超过1000个点的带权无向图,求删掉其中一条边后最短路的最大值。


思路

:先Dijkstra或SPFA求出原图最短路,显然,当删掉的边不在最短路内时,最短路不变。

因此只需枚举原图最短路上的每一条边,将其删掉求最短路求最大值即为答案。


代码

:C++11

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <stack>
using namespace std;

const int maxn = 1000 + 10;
const int INF = 1e9 + 7;

struct Edge
{
    int id;
    int from, to, val;
    Edge() {}
    Edge(int id, int from, int to, int val): from(from), to(to), val(val), id(id) {}
    Edge(int from, int val): from(from), val(val) {}
    bool operator < (const Edge &t) const
    {
        return t.val < val;
    }
};

vector<Edge> pic[maxn];
vector<Edge> edges;
int d[maxn], p[maxn];
vector<int> ve;

int n, m;

void init()
{
    for(int i = 0; i <= n; i++)
    {
        pic[i].clear();
    }
    edges.clear();
    ve.clear();
}

int dij(int ignore)
{
    for(int i = 1; i <= n; i++)
    {
        d[i] = INF;
        p[i] = -1;
    }
    priority_queue<Edge> q;
    d[1] = 0;
    q.push(Edge(1, 0));
    while(!q.empty())
    {
        int cur = q.top().from;
        int uval = q.top().val;
        q.pop();
        for(auto &e : pic[cur])
        {
            if(e.id == ignore) continue;
            if(uval + e.val < d[e.to])
            {
                d[e.to] = uval + e.val;
                p[e.to] = e.id;
                q.push(Edge(e.to, d[e.to]));
            }
        }
    }
    return d[n];
}

void findpath()
{
    int cur = n;
    while(cur != 1)
    {
        ve.push_back(p[cur]);
        cur = edges[p[cur]].from == cur ? edges[p[cur]].to : edges[p[cur]].from;
    }
}

int main()
{
    while(scanf("%d%d", &n, &m) != EOF)
    {
        init();
        for(int i = 0; i < m; i++)
        {
            int a, b, v;
            scanf("%d%d%d", &a, &b, &v);
            pic[a].push_back(Edge(i, a, b, v));
            pic[b].push_back(Edge(i, b, a, v));
            edges.push_back(Edge(i, a, b, v));
        }
        dij(-1);
        findpath();
        int ans = 0;
        for(int i = 0; i < ve.size(); i++)
        {
            ans = max(ans, dij(ve[i]));
        }
        cout << ans << endl;
    }
    return 0;
}



版权声明:本文为Rewriter_huanying原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。